#!/usr/bin/perl

$ENV{UI_DIR} = "/home/embedded/UNIXimager";

#Packages to use
use Cwd;

#first we have some constants
$camera_out_name = "pork.ppm";
$start = cwd();
$bigjpg_dir = "vjpg";
$smalljpg_dir = "svjpg";
$smallppm_dir = "svppm";
@required_files = ("../UNIXimager/bin/dcs","ppm2all");
$ver_num ="4.0";

#check to see if the required files exist
foreach $file (@required_files) {
   if (!-e $file) {
	printf("Missing file %s!\n\n",$file);
	exit -1;
   }
}

if (!-d $bigjpg_dir) {
   printf("Creating %s/%s/\n",$start,$bigjpg_dir);
   `mkdir $bigjpg_dir`;
   if (!-d $bigjpg_dir) {die("Cannot create dir ",$start,"/",$bigjpg_dir);}
}

if (!-d $smalljpg_dir) {
   printf("Creating %s/%s/\n",$start,$smalljpg_dir);
   `mkdir $smalljpg_dir`;
   if (!-d $smalljpg_dir) {die("Cannot create dir", $start,"/",$smalljpg_dir);}
}

if (!-d $smallppm_dir) {
   printf("Creating %s/%s/\n",$start,$smallppm_dir);
   `mkdir $smallppm_dir`;
   if (!-d $smallppm_dir) {die("Cannot create dir ",$start,"/",$smallppm_dir);}
}

# see what highest number yet used is:
$pictnum=100;
for ($counter=999;$counter>99;$counter--){
  if (-e "$bigjpg_dir/v$counter.jpg") {
	$pictnum = $counter + 1;
	last;
  }
}
printf("dusting lightvector sv%d.jpg\n",$pictnum);

#Now we have $pictnum representing the next picture we are going to take
    if (-e $camera_out_name) {  `rm $camera_out_name`;}
    `../UNIXimager/bin/dcs -x -f ppm -a $camera_out_name`;
    if (!-e $camera_out_name) {
	printf("I think something went wrong.  Try again.\n");
    }
    else {	

      #now we convert the picture to other formats.
      `./ppm2all $camera_out_name $smalljpg_dir/sv$pictnum.jpg $smallppm_dir/sv$pictnum.ppm $bigjpg_dir/v$pictnum.jpg`;
      `chmod a-w $bigjpg_dir/v$pictnum.jpg`;
      printf("Converted %s to %s/sv%s.jpg, %s/sv%s.jpg, %s/v%s.jpg.\n",$camera_out_name,$smalljpg_dir,$pictnum,$smallppm_dir,$pictnum,$bigjpg_dir,$pictnum);
      `sync`;
      if (!-e "$bigjpg_dir/v$pictnum.jpg") {
	printf("Error creating big jpg %s/v%s.jpg!\n",$bigjpg_dir,$pictnum);
      }
      `rm $camera_out_name`;
      `zgv $smalljpg_dir/sv$pictnum.jpg`;      
   }

