#!/usr/bin/perl -w

if(!open(FIN, "<tof.dat")) {
    printf("can't open tof.dat\n");
}
if(!open(FOUT, ">time0.dat")) {
    printf("can't open time0.dat\n");
}

@lo = (-26.0,14,32,53,70,90,111);
@hi = (-20,20,40,58,80,97,117);

$line=<FIN>;
$line=<FIN>;
$entrycounter = 0;

while($line=<FIN>) {

    $entrycounter++;
    next if($entrycounter>220);
    print $entrycounter, "\n";
    $eline=<FIN>;
    chomp($line);
    chomp($eline);
    $line =~ s/^\s+//;
    $eline =~ s/^\s+//;

    @p = split(/ +/,$line);
    @e = split(/ +/,$eline);
    
    $counter = 0;
    $x0 = 0;
    $current = 1;

   if($e[0]<1.0 && $p[0]<$hi[0] && $p[0]>$lo[0] ) {
       for($i=1;$i<6;$i++) {
	   if($e[$i]<1.0 && $p[$i]<$hi[$i] && $p[$i]>$lo[$i]){
	       $x0 = ($i*$p[0]+$p[$i])/($i+1);
	       $counter++;
	       $current = $i;
	       printf("p[0]=%f,i=%d, p[i]=%f x0=%f\n",$p[0],$i,$p[$i],$x0);

	       last;
	   }
       }
    }
    for($i=$current;$i<5;) {
	if($e[$i]<1.0 && $p[$i]<$hi[$i] && $p[$i]>$lo[$i]) {
	    for($j=$i+1;$j<6;$j++) {
		if($e[$j]<1.0 && $p[$j]<$hi[$j] && $p[$j]>$lo[$j]) {
		    $counter++;
		    $x0=$x0+($j*$p[$i]-$i*$p[$j])/($j-$i);
		    printf("i=%d,j=%d,p[i]=%f,p[j]=%f\n,x0=%f",$i,$j,$p[$i],$p[$j],$x0);
		    $i=$j;
		    last;
		}
	    }
	}
	last if($i!=$j);
    }
    if ($counter == 0) {
	$x0 = 0;
    }
    else {
	$x0 = $x0/$counter;
    }
    print FOUT $x0, "\n";
}










