#!/usr/bin/perl

#
# usage: ./dpr2pov <INFILE> <OUTFILE> <spheres/chips> [showpower]
#

use Term::ANSIColor qw(:constants);

########################
# Parse the command line

my $infile = "$ARGV[0]";
chomp ( $infile );
my $outfile = "$ARGV[1]";
chomp ( $outfile );
my $objecttype = "$ARGV[2]";
chomp ( $objecttype );
my $power = "false";
if( $ARGV[3] eq "showpower" ) {
    $power = "true";
}

########################################
# Create the output file from the header

system("cp utils/header_normal.pov $outfile");

open (INFILE, "$infile") 
    or die "can't open input file";

my $line = "";
my @path = split(/\//, $infile);
my $file = @path[-1];

print RED, "DPRSim: ", RESET;
print "Converting DPR data ($file) to Povray file...\n";

while ($line=<INFILE>) {
    chomp ( $line );
    @arr = split(/,/, $line);
    $x = @arr[1];
    $y = @arr[2];
    $z = @arr[3];
    $powered = @arr[4];
    $red = @arr[7];
    $green = @arr[8];
    $blue = @arr[9];
    $alpha = @arr[10];
    
    ##########################################################
    # Determine how to color the objects based on power status
    
    if( $power eq "true") {
	if ( $powered eq "1" ) {
	    $colortext = "texture { pigment { color red 1 transmit $alpha } }";
	}
	else {
	    $colortext = "texture { pigment { color blue 1 transmit $alpha } }";
	}
    }
    else {
	$colortext = "texture { pigment { color rgbt <$red, $green, $blue, $alpha> } }";
    }
    
    
    ###############################
    # Create the objects for povray
    
    if( $objecttype eq "spheres" ) {
	$outline = "sphere {\n<$x,$z,$y>, 1\n  $colortext\n }\n\n";
    }	
    if( $objecttype eq "chips" ) {
	$z -= 1;
	$top = $z + 0.25;
	$outline = "cylinder {\n<$x,$z,$y>,<$x,$top,$y>, 1\n  $colortext\n}\n\n";
    }
    
    ###############################
    # Write the objects to the file
    
    system("echo '$outline' >> $outfile");
}

close INFILE;

print RED, "DPRSim: ", RESET;
print "Rendering image using Povray...\n";
