#!/usr/bin/perl
#
# Read a datafile.
#    Try to fit it with a single gaussian, only free parameter = time

$debug = 0;

use POSIX;

# read data from this file
$infile = "make_noisy_gauss.0.3.out";
$ndata = 0;
open(INFILE, "$infile") || die("can't open file $infile");
while (<INFILE>) {
  $line = $_;
  if ($line =~ /^#/) {
    next;
  }
  $line = " " . $line;
  @words = split(/\s+/, $line);
  $data_t_array[$ndata] = $words[1];
  $data_v_array[$ndata] = $words[2];
  if ($debug > 1) {
    printf " data %3d  t %8.3f  v %8.3f \n", 
       $ndata, $data_t_array[$ndata], $data_v_array[$ndata];
  }
  $ndata++;
}
if ($debug > 0) {
  printf " read %5d items from data file %s \n", $ndata, $infile;
}





$amp = 1.0;
$fwhm = 1.0;
$sigma = $fwhm / 2.35;


# we loop over possible guessed times
$start_guess = 1;
$end_guess = 19;
$d_guess = 0.1;
for ($guess_t = $start_guess; $guess_t < $end_guess; $guess_t += $d_guess) {

     if ($debug > 0) {
       printf " guess_t is now %8.3f \n", $guess_t;
     }
     $k_sum = 0;

     # we now generate a model with this guessed time
     #    and compare to the data, compute k (like chi)
     $start_t = 0;
     $end_t = 100;
     $dt = 1.0;

     for ($i = 0; $i < $ndata; $i++) {
     
       $t = $data_t_array[$i];
       $arg = 0.0 - ($t - $guess_t)*($t - $guess_t)/(2.0*$sigma*$sigma);
       $model_v = $amp*exp($arg);
     
       $diff = $model_v - $data_v_array[$i];
       $diff_sq = $diff*$diff;
       $k_sum += $diff_sq;

       if ($debug > 0) {
         printf " %8.3f %8.3f  %8.3f    k now %8.3f \n", 
            $t, $model_v, $data_v_array[$i], $k_sum;
       }
     
     }

     # now we can spit out the value of guess and the k_sum
     printf "  guess_t %8.3f  k_sum %8.3f \n", $guess_t, $k_sum;



}

exit 0;

