#!/usr/bin/perl
#

# copy "good" .coo and .pht files into this subdir
$subdir = "./weeded";

# only accept .coo files with these average properties
$max_fwhm = 3.5;
$min_round = -0.5;


@coo_files = glob("../pnv1915_*coo");
foreach $coo (@coo_files) {

  if ($debug > 0) {
    printf " next is $coo \n";
  }

  $num = 0;
  $fwhm_sum = 0;
  $round_sum = 0;

  open(COO, $coo) || die("can't open file $coo");
  while (<COO>) {
    $line = $_;
    @words = split(/\s+/, $line);
    $fwhm = $words[5];
    $round = $words[6];
   
    $fwhm_sum += $fwhm;
    $round_sum += $round;
    $num++;
  }
  close(COO);

  $fwhm_avg = $fwhm_sum / $num;
  $round_avg = $round_sum / $num;

  printf " %s  %7.2f  %7.2f \n", $coo, $fwhm_avg, $round_avg;

  $pht = $coo;
  $pht =~ s/.coo/.pht/;
  $pht =~ s/\.\./\./;
  $pht =~ s/_fit//;
  printf "old coo $coo  new pht $pht \n";

  # if the properties are okay, then copy the .coo and .pht
  #    files into the "weeded" subdir
  if ($fwhm_avg < $max_fwhm) {
    if ($round_avg > $min_round) {

      printf " will copy $coo \n";

      $cmd = "cp $coo $pht $subdir ";
      $ret = exec_cmd($cmd);

    }
  }

}


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


