#!/usr/bin/perl
#
# find and measure stars in each frame, generating .coo and .pht files

$xvista_dir = "/home/richmond/xvista";

$debug = 1;

# set to 1 to see pictures, one frame at a time
$interactive = 0;

# set to 1 to use "masked" versions of images
$use_masked = 0;

# set to 1 to restrict search to the box shown below
$use_box = 1;
$box_num = 3;
#$cmd = "$xvista_dir/box 3 cr=628 cc=953 nr=600 nc=600";
$cmd = "$xvista_dir/box 3 sr=10 sc=10 nr=290 nc=490";
$retval = `$cmd`;
if ($debug > 0) {
  printf "using a box $cmd ... \n";
}

  @files1 = glob("iy*.fit");
  @files = (@files1, @files2, @files3);

$nframes = 0;
foreach $file (@files) {
#foreach $file (@files1, @files2, @files3) {
  $frame_array[$nframes] = $file;
  $nframes++;
}

# now process each frame in turn
foreach $file (@frame_array) {
  $base = $file;
  $base =~ s/\./_/;
  if ($use_masked == 1) {
    $base =~ s/masked\///;
  }
  printf "now working on $file = $base\n";

 if (1 == 1) {

  $cmd = "$xvista_dir/sky $file bin=5";
  if ($use_box == 1) {
    $cmd .= " box=$box_num ";
  }
  $ret = exec_cmd($cmd);
  
  # for VRI 
  $cmd = "$xvista_dir/stars $file minsig=7  minfwhm=1.5 maxfwhm=6.0 minsharp=-1.0 maxsharp=1.0 minround=-2.0 maxround=1.7 movemax=2 outfile=$base.coo  ";
#  $cmd .= " convolve fwhm=5 image=foo.fts ";
#   $cmd .= " verbose ";
  if ($use_box == 1) {
    $cmd .= " box=$box_num ";
  }
  if ($interactive == 1) {
    $cmd .= " verbose show ";
    system("$xvista_dir/tv $file zoom=1 z=sky-100 l=500 zoom=1; sleep 2");
    #system("tv $file zoom=1 z=2550 l=500 zoom=1; sleep 2");

    if ($debug > 0) {
      printf "cmd is ..$cmd.. \n";
    }
    `$cmd`;
  } else {
    if ($debug > 0) {
      printf "cmd is ..$cmd.. \n";
    }
    `$cmd`;
  }
 }


  if ($interactive == 1) {
    printf "skipping phot because interactive \n";
  }
  else {

    $cmd = "$xvista_dir/phot $file infile=$base.coo outfile=$base.pht aper=2 aper=3 aper=4 ";
    $cmd .= " skyinner=10 skyouter=20  ";
    $cmd .= " saturate=30000 readnoise=15 gain=2.02 empscatter";
    if ($debug > 0) {
      printf "cmd is ..$cmd.. \n";
    }
    exec_cmd($cmd);
   }

   if ($interactive == 1) {
     printf "\nhit return to continue: \n";
     $a = <STDIN>;
     `killall -1 tv`;
   }
 

 
}


exit 0;
  



##############################################################################
# PROCEDURE: exec_cmd
#
# DESCRIPTION: Execute the given shell command line.  If the $debug flag
#              is set, we print to stdout the command line, and
#              also print out the result string.
#
# RETURNS:
#              the result of the command
#
#
sub exec_cmd {

  my($cmd, $ret);

  $cmd = $_[0];

  if ($debug > 0) {
    printf "cmd is ..$cmd.. \n";
  }
  $ret = `$cmd`;
  if ($debug > 0) {
    printf "ret is ..$ret.. \n";
  }

  return($ret);
}


