#!/bin/env perl

#use lib ("/home/freyberg/PERL/lib/perl5/site_perl/5.005/sun4-solaris/");
#use lib ("/gapps/perl/");
use Pezca; 

$prefix = $ARGV[0];

#$flux_pv = 'scaler_calc2';
#$flux_pv = 'DAQ:HEARTBEAT';
$flux_pv = 'IBCAD00CRCUR6';

$ENV{'EPICS_CA_ADDR_LIST'} = '129.57.255.14 129.57.27.255 129.57.194.255';

# check if script is already running

open(OUT,">/gluex/log/${prefix}_test.txt");
if (&CHECK_IF_RUNNING) {die "$0 already running\n";}
close(OUT);

print "Created lock file for $prefix \n" ;

$fit_x_file = "/gluex/log/${prefix}_fit_x.log";
$fit_y_file = "/gluex/log/${prefix}_fit_y.log";
$fit_tk_file = "/gluex/log/${prefix}_bp_fit_tk.log";

#$gnuplot = '/home/freyberg/GNUPLOT/gnuplot';
$gnuplot = 'gnuplot';

print "Setting monitor \n";

$errcode = Pezca::SetMonitorDouble( $flux_pv );

print "Monitor set \n";

$slm_cut = 5;

while(1) {
    print "Looping \n";
  if (Pezca::NewMonitorValueDouble( $flux_pv )) {
    ($err_code, $slm) = Pezca::GetDouble( $flux_pv );
    
    print "SLM $slm\n";
    if ($slm > $slm_cut) {
      ($err_code, @x) = Pezca::GetList("${prefix}_x",'double',64);
      ($err_code, @y) = Pezca::GetList("${prefix}_y",'double',64);
      ($err_code, @posx) = Pezca::GetList("${prefix}_x_lbl",'double',64);
      ($err_code, @posy) = Pezca::GetList("${prefix}_y_lbl",'double',64);
     
      print "x:@x\n";
      print "posx:@posx\n";      
      print "y:@y\n";
      print "posy:@posy\n";      
      $max_x = 0;
      $max_y = 0;
      $avg_x=0.; $avg_y=0.; $avg_x2=0.; $avg_y2=0.; $sum_x = 0.; $sum_y=0.;
      for ($i=0; $i<= $#x; $i++) {
	$x_err[$i] = sqrt($x[$i]);
	$y_err[$i] = sqrt($y[$i]);

	$avg_x += $posx[$i] * $x[$i];
	$avg_y += $posy[$i] * $y[$i];
	$avg_x2 += ( $posx[$i] )**2 * $x[$i];
	$avg_y2 += ( $posy[$i] )**2 * $y[$i];

	$sum_x += $x[$i];
	$sum_y += $y[$i];

	if ($x[$i] > $max_x) {
	  $max_x = $x[$i];
	  $mean_x = $posx[$i];
	}
	if ($y[$i] > $max_y) {
	  $max_y = $y[$i];
	  $mean_y = $posy[$i];
	}
      }

      if ( $sum_x > 0 ) {
	$avg_x =  $avg_x / $sum_x ;
	$avg_x2 =  $avg_x2 / $sum_x ;
	$rms_x = sqrt($avg_x2 - $avg_x**2);
      }
      else {
	$avg_x = 0.; $rms_x=0.;
      }
	
      if ( $sum_y > 0 ) {
	$avg_y =  $avg_y / $sum_y ;
	$avg_y2 =  $avg_y2 / $sum_y ;
	$rms_y = sqrt($avg_y2 - $avg_y**2);
      }
      else {
	$avg_y = 0.; $rms_y=0.;
      }

      print "Average  X is $avg_x, RMS is $rms_x \n";
      print "Average  Y is $avg_y, RMS is $rms_y \n";

      $back_x = $max_x/100.;
      $back_y = $max_y/100.;
      
      system("rm $fit_x_file");
      $ENV{FIT_LOG} = "$fit_x_file";
      print "$max_x  $max_y \n";
      open(GNUPLOT, "| $gnuplot ");
      
      #	    print GNUPLOT "set output '/dev/null' \n";
      print GNUPLOT "g(x) = back + max/(1.0 + ((mean -x)/crit)**2)**2 \n";
      print GNUPLOT "back = $back_x \n";
      print GNUPLOT "max = $max_x \n";
      print GNUPLOT "mean = $mean_x \n";
      print GNUPLOT "crit = 13 \n";
      print GNUPLOT "fit [-55:55] g(x) \'-\' using 1:2 via back, max, mean, crit \n";
      
      for ($i=0; $i <= $#x; $i++) {
#	$pos = (-31 + $i)*2;
	print GNUPLOT "$posx[$i]  $x[$i] $x_err[$i]\n";
      }
      print GNUPLOT "e\n";
      
      print GNUPLOT "quit \n";
      close(GNUPLOT);
      
      system("rm $fit_y_file");
      $ENV{FIT_LOG} = "$fit_y_file";
      #	
      open(GNUPLOT, "| $gnuplot ");
      
      #	    print GNUPLOT "set output '/dev/null' \n";
      print GNUPLOT "g(x) = back + max/(1.0 + ((mean -x)/crit)**2)**2 \n";
      print GNUPLOT "back = $back_y \n";
      print GNUPLOT "max = $max_y \n";
      print GNUPLOT "mean = $mean_y \n";
      print GNUPLOT "crit = 13 \n";
      print GNUPLOT "fit [-55:55] g(x) \'-\' using 1:2 via back, max, mean, crit \n";
      
      for ($i=0; $i <= $#y; $i++) {
#	$pos = (-30 + $i)*2;
	print GNUPLOT "$posy[$i]  $y[$i] $y_err[$i]\n";
      }
      print GNUPLOT "e\n";
      print GNUPLOT "quit \n";
      close(GNUPLOT);
      
      open(FIT_X, "< $fit_x_file");
      $final = 0;
      while(<FIT_X>) {
	chop;
	if (/^Final set/) {
	  $final = 1;
	}
	if (/^correlation/) {
	  $final = 0;
	}
	if ($final) {
	  print "$_\n";
	  if (/^back/) {
	    ($j1, $j2, $back_x, $j3, $err_back_x) = split;
	  }
	  if (/^max/) {
	    ($j1, $j2, $max_x, $j3, $err_max_x) = split;
	  }
	  if (/^mean/) {
	    ($j1, $j2, $mean_x, $j3, $err_mean_x) = split;
	  }
	  if (/^crit/) {
	    ($j1, $j2, $crit_x, $j3, $err_crit_x) = split;
	  }
	}
      } 
      open(FIT_Y, "< $fit_y_file");
      $final = 0;
      while(<FIT_Y>) {
	chop;
	if (/^Final set/) {
	  $final = 1;
	}
	if (/^correlation/) {
	  $final = 0;
	}
	if ($final) {
	  if (/^back/) {
	    ($j1, $j2, $back_y, $j3, $err_back_y) = split;
	  }
	  if (/^max/) {
	    ($j1, $j2, $max_y, $j3, $err_max_y) = split;
	  }
	  if (/^mean/) {
	    ($j1, $j2, $mean_y, $j3, $err_mean_y) = split;
	  }
	  if (/^crit/) {
	    ($j1, $j2, $crit_y, $j3, $err_crit_y) = split;
	  }
	}
      }
      print "$back_x +/- $err_back_x : $max_x +/- $err_max_x : $mean_x +/- $err_mean_x : $crit_x +/- $err_crit_x \n";
      print "$back_y +/- $err_back_y : $max_y +/- $err_max_y : $mean_y +/- $err_mean_y : $crit_y +/- $err_crit_y \n";
      
 #     $mean_x = -1.0*$mean_x;
 #     $mean_y = $mean_y - 8.41;
      
      $gp_photons_x = $max_x*$crit_x*0.78540;
      $gp_photons_y = $max_y*$crit_y*0.78540;
      
      $errcode = Pezca::PutDouble("${prefix}_mean_x",   $mean_x);
      $errcode = Pezca::PutDouble("${prefix}_width_x",  $crit_x);
      $errcode = Pezca::PutDouble("${prefix}_avg_x",    $avg_x);
      $errcode = Pezca::PutDouble("${prefix}_rms_x",    $rms_x);
      $errcode = Pezca::PutDouble("${prefix}_max_x",    $max_x);
      $errcode = Pezca::PutDouble("${prefix}_back_x",   $back_x);
      $errcode = Pezca::PutDouble("${prefix}_photons_x",$gp_photons_x);
      
      $errcode = Pezca::PutDouble("${prefix}_d_mean_x", $err_mean_x);
      $errcode = Pezca::PutDouble("${prefix}_d_width_x",$err_crit_x);
      $errcode = Pezca::PutDouble("${prefix}_d_max_x",  $err_max_x);
      $errcode = Pezca::PutDouble("${prefix}_d_back_x", $err_back_x);
      

      $errcode = Pezca::PutDouble("${prefix}_mean_y",   $mean_y);
      $errcode = Pezca::PutDouble("${prefix}_width_y",  $crit_y);
      $errcode = Pezca::PutDouble("${prefix}_avg_y",    $avg_y);
      $errcode = Pezca::PutDouble("${prefix}_rms_y",    $rms_y);
      $errcode = Pezca::PutDouble("${prefix}_max_y",    $max_y);
      $errcode = Pezca::PutDouble("${prefix}_back_y",   $back_y);
      $errcode = Pezca::PutDouble("${prefix}_photons_y",$gp_photons_y);
      
      $errcode = Pezca::PutDouble("${prefix}_d_mean_y", $err_mean_y);
      $errcode = Pezca::PutDouble("${prefix}_d_width_y",$err_crit_y);
      $errcode = Pezca::PutDouble("${prefix}_d_max_y",  $err_max_y);
      $errcode = Pezca::PutDouble("${prefix}_d_back_y", $err_back_y);
    } else {
      sleep 1;
    }
  } else {
    sleep 1;
  }
}
close(FIT_TK);

sub CHECK_IF_RUNNING {

# return 1 (true) if there is another instance of this script
# running. Returns 0 if this is the only instance of this script.

    print OUT "Check if Running SubrouTine\n";

    $result = 0;
    open(PS, "ps ax |");
    $my_pid = $$;
    $my_perl_script = $0;
    (@command) = split(/\//,$my_perl_script);
    $my_perl_script_name = $command[$#command];
    print OUT "looking for $my_perl_script : $my_perl_script_name\n";

    while(<PS>) {
	print OUT "$_";
	chop;
	if (/perl/) {
	    if (/$my_perl_script/) {
                if ( /$prefix/ ) {
                    @test = split(/\s+/,$_);
                    $no_pid = 1;
                    $index = 0;
                    while ($no_pid) {
                        if ($test[$index] =~ /\d+/) {
                            $pid_from_ps = $test[$index];
                            $no_pid = 0;
                        }
                        $index++;
                    }
                    
                    print OUT "$my_pid : $pid_from_ps : $my_perl_script\n";
                    if ($pid_from_ps != $my_pid) {
                        $result=1;
                    }
                }
	    }
	}
    }
    close(PS);

    return($result);
#    close(PS);
}


