#!/usr/bin/perl
#
# Check the image adjustment magnitude factor (mag zero point)
#   for all images in an ensemble output.  If an image has
#   an adjustment factor larger than a certain threshold
#   (meaning "more clouds, more extinction"), then move
#   that .pht file to a subdir called "extinguished_pht".

$subdir = "./extinguished_pht";
if (-d $subdir) {
  # already exists, do nothing
} else {
  # make the subdirectory
  mkdir($subdir);
}

# only accept .pht files with image adjustment values below this:
$max_em = 11.6;
#$max_em = 11.80;

# name of the solve*img file
$img_file = "./solve_maxi5_clear.img";

open(IMG_FILE, "$img_file") || die("can't open file $img_file");
while(<IMG_FILE>) {
  $line = $_;
  if ($line =~ /^#/) {
    next;
  }
  @words = split(/\s+/, $line);
  $pht_file= $words[1];
  $em = $words[4];
  $sig_em = $words[5];

  if ($em < $max_em) {
    # this image was fine.  Do nothing
  }
  else {
    printf "  $pht_file has em %6.3f > %6.3f ... moving to %s \n",
                 $em, $max_em, $subdir;
    $cmd = "mv $pht_file $subdir";
    $ret = exec_cmd($cmd);
    next;
  }

}
close(IMG_FILE);


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);
}


