#!/usr/bin/perl
#
# Given a datafile, run the "run_matrix.pl" script on the data,
#    but in a special way:
#
#    If there are N measurements in the file, enter a loop which
#    runs N times.   In each iteration,
#
#      a) remove measurement i from the data file
#      b) run the fitting program on the N-1 remaining measurements
#
# The idea is to see if one particular measurement is causing
#    the results to vary strongly.
#
#
# Usage:
#                perl remove_one.pl    datafile
#
# MWR 8/8/2021

$debug = 1;

# name of program which fits model to data
$progname = "./matrix_gxand.pl";
# temp file used to create list of measurements with one missing
$temp_file = "./remove_one.tmp";

if ($#ARGV != 0) {
  printf "usage:  perl remove_one.pl   datafile \n";
  exit(1);
}
$infile = $ARGV[0];
if ($debug > 0) {
  printf " input file is $infile \n";
}


#  read in all the measurements from the input file
$num_pos = 0;
open(INFILE, "$infile") || die("can't open input file $infile");
while (<INFILE>) {
  $line = $_;
  @words = split(/\s+/, $line);
  if ($#words != 4) {
    printf " bad input line %d in file $infile, it follows \n", $num_pos;
    printf "%s", $line;
    exit(1);
  }

  chomp($line);
  $line_array[$num_pos] = $line;

  $num_pos++;
}
close(INFILE);
if ($debug > 0) {
  printf "  read %6d lines from file $infile \n", $num_pos;
}


###############################
#   Main loop: generate temp file with N-1 measurements, run program
#                 on that temp file, print results
#
for ($i = 0; $i < $num_pos; $i++) {
  open(OUTFILE, ">$temp_file") || die("can't create file $temp_file");
  for ($j = 0; $j < $num_pos; $j++) {
    if ($j != $i) {
      printf OUTFILE "%s\n", $line_array[$j];
    }
    else {
      if ($debug > 0) {
        printf " removing this line: %s \n", $line_array[$i];
      }
    }
  }
  close(OUTFILE);

  $cmd = "perl $progname $temp_file";
  $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);
}


