#!/usr/bin/perl

# TROWEL - To Render Our Wonderful Excellent Lightvectors
# Use TROWEL to apply cement
#
# Script to cement multiple images using different weights
#
# requires:
#  cementinit, cementi, plm2pnm (executables), and cement.txt in the directory
#  cement.txt can have comments, and it can also have unused lightvectors, e.g.
#  v001  # with no cement weights after it is ignored
#  (this is so you can ls v???.ppm > cement.txt, or the like and then just
#  put weights on the ones you want to use).
#
# bug reports, etc: mann@eecg.toronto.edu
#
#############################################################

use strict;                     #To try and stop me from installing bugs

my($lineOfInput,@inputParams);  # inputparams is a list of lists, each sublist
                                # containing picturename and the 3 weights. Yes
                                # it hurts readability, but it gives me so much

#die "Need a filename" if ($#ARGV != 0);


if($#ARGV==-1)
{
    open(COMMANDFILE,"<cement.txt");
    system("trowel.pl cement.txt");
    exit(0);
}

open(COMMANDFILE,"$ARGV[0]");

#printf("$#ARGV File name is $ARGV[0]\n");
#printf("Opening $ARGV[0]\n");


my($vectorIndex,$numVectors);
$vectorIndex = 0;

#Parse file into aforementioned nasty array of arrays
while ($lineOfInput = <COMMANDFILE>) {
  $lineOfInput =~ s/^(.*?)#(.*)$/$1/;
  if ($lineOfInput =~ /^([\S]+)\s+([\.|\d|-]+)\s+([\.|\d|-]+)\s+([\.|\d|-]+)/ ) {
      $inputParams[$vectorIndex] -> [0] = $1;
      $inputParams[$vectorIndex] -> [1] = $2;
      $inputParams[$vectorIndex] -> [2] = $3;
      $inputParams[$vectorIndex] -> [3] = $4;
      $vectorIndex++;
  }
  elsif (!($lineOfInput =~ /^\s*$/)) {
    #Allow blank lines once comments are stripped, but complain about other imparsables
    printf "Bad input line:\n$lineOfInput";
  }

}

$numVectors = $vectorIndex;
$vectorIndex = 0;

#printf("cementinit $inputParams[0]->[0] $inputParams[0]->[1] $inputParams[0]->[2] $inputParams[0]->[3] -o total.plm\n");
system("cementinit $inputParams[0]->[0] $inputParams[0]->[1] $inputParams[0]->[2] $inputParams[0]->[3] -o $ARGV[0].plm\n");

for ($vectorIndex=1;$vectorIndex<$numVectors;$vectorIndex++)
{
    #    printf("About to: ./cementi trowel_out.plm.gz $inputParams[$vectorIndex]->[0] $inputParams[$vectorIndex]->[1] $inputParams[$vectorIndex]->[2] $inputParams[$vectorIndex]->[3] \n");

    if($inputParams[$vectorIndex]->[1]!=0 || $inputParams[$vectorIndex]->[2]!=0 || $inputParams[$vectorIndex]->[3]!=0)
    {
        #        printf("cementi total.plm $inputParams[$vectorIndex]->[0] $inputParams[$vectorIndex]->[1] $inputParams[$vectorIndex]->[2] $inputParams[$vectorIndex]->[3] \n");
        system("cementi $ARGV[0].plm $inputParams[$vectorIndex]->[0] $inputParams[$vectorIndex]->[1] $inputParams[$vectorIndex]->[2] $inputParams[$vectorIndex]->[3] \n");
    }
}

#printf("plm2pnm total.plm -o total.ppm\n");

system("plm2pnm $ARGV[0].plm -o $ARGV[0].jpg\n");
#system("rm $filename.plm\n");

