#!/usr/bin/perl
#
# Given a .pht file, look at the "flag" column.  If the column is "1",
#    then the star was saturated.  In that case, change the 
#    uncertainty value to a negative number.
#
# We need to do this as a crutch because "phot" sets flag value,
#    but "multipht" expects a negative uncertainty, for saturated stars.
#
# MWR 8/20/2009

$debug = 1;

# 1-indexed column holding flag = 1 for saturated
$flag_col = 12;
# 1-indexed column holding uncertainty
@uncert_cols = (7, 9, 11);

$tempfile = "set_uncert_neg.tmp";

@files = glob("mrdel*.pht");
#@files = glob("mrdelv-082V_fit.pht");
foreach $file (@files) {
  if ($debug > 1) {
    printf "next is file %s \n", $file;
  }
  open(TEMPFILE, ">$tempfile") || die("can't open file $tempfile");
  open(INFILE, "$file") || die("can't open file $file");
  while (<INFILE>) {
    $line = $_;
    if ($line =~ /^#/) {
      print OUTFILE "%s", $line;
      next;
    }
    
    chomp($line);
    $line = " " . $line;
    @words = split(/\s+/, $line);

    $flag = $words[$flag_col];
    if ($flag == 0) {
      printf TEMPFILE "%s\n", $line;
    }
    else {
      if ($debug > 0) {
        if ($flag == 1) {
          printf " found flag=1 in file %s \n", $file;
        }
      }
      if ($debug > 1) {
        printf " found flag != 0 in following line \n";
        printf " %s \n", $line;
      }
      for ($i = 1; $i <= $#words; $i++) { 
        $make_neg = 0;
        for ($j = 0; $j <= $#uncert_cols; $j++) {
          if ($debug > 1) {
            printf " does i %d  = j %d \n", $i, $uncert_cols[$j];
          }
          if ($uncert_cols[$j] == $i) {
            if ($debug > 1) {
              printf " will change val of word %d = %s in next line \n",
                    $i, $words[$i];
            }
            printf TEMPFILE " -%s ", $words[$i];
            $make_neg = 1;
            last;
          }
        }
        if ($make_neg == 0) {
          printf TEMPFILE " %s ", $words[$i];
        }
      }
      printf TEMPFILE "\n";
    }

  }
  close(INFILE);
  close(TEMPFILE);


  # now replace the original .pht file with the modified version
  $cmd = "mv $tempfile $file";
  $ret = `$cmd`;

}

exit 0;

