#!/usr/local/bin/perl
# script perl pour corriger les fichiers spec a partir d'une table
# de filtres
#
sub usage
{   print <<END_USAGE ;
 usage: $0 [-bB -eE] [-v] [-ttabfile]  specfile
 read a specfile (fourc) and correct the counts taking into account a filter table
 if -t is not set, looks for 'filter.dat' file. 
 -v set $0 to verbose mode
 
END_USAGE
	}
	
require "getopts.pl";
&Getopts('b:e:t:hv');

if ( $opt_h ) { &usage; exit;}
if ( @ARGV != 1 ) { &usage; print " no specfilename found\n\n"; exit; }
if ( !$opt_t )  { $opt_t = "filter.dat";}

unless ( open ( IN, $opt_t) )
{  print " unable to open '$opt_t' filters table file\n\n";
   &usage; exit;
	}
while ( $line = <IN> )
{  next if ( $line =~ m/^#/);
   ($i,$a) = split /\s+/, $line;
	$abs[$i] = $a;
	print " abs[$i] = $abs[$i]\n";
   }
close IN;

unless ( open ( IN, $ARGV[0]) )
{  print " unable to open '$ARGV[0]' spec_file\n\n";
   &usage; exit;
	}
$specname = $ARGV[0];
#if ( $specname =~ m//// )
while ( $line = <IN> )
{  next unless ( $line =~ m/^#S/);
   $index++;
	($id, $scan ) = split /\s+/, $line;
	next if ( $scan < $opt_b );
	if ( $opt_e && $scan > $opt_e) { exit } ;
	$name = "scan".$scan.".".$index."_".$specname;
	process_scan ($name, $line);
   }
close IN;


sub process_scan
{	my ( $name, $line)  = @_;
	my $id, $ncol, @labels, @values;
	print " $name $line";
   open ( OUT, ">$name" )|| die "unable to open $name for writing";
	print OUT  "$line";
	print OUT  "#C corrected by $0 for absorption\n";
   while ( $line = <IN> )
   {   if ( $line =~ m/^#/)
	    {   print OUT $line;
		     if ( $line =~ m/^#R/) { close OUT; return }
#		     if ( $line =~ m/^#S/) { close OUT; return }
		     if ( $line =~ m/^#N/) { ($id, $ncol) = split /\s+/, $line ;}
		     if ( $line =~ m/^#L/) 
			  {  if ( $opt_v) { print $line; }
			     @labels = split /\s+/, $line; 
			     $id = shift @labels;
				  $pseudoCindex = $pfilterindex = $vct14index = -1;
				  for ( $i = 0; $i < @labels; $i++ )
				  {   if ( $labels[$i] eq "pseudoC" ) { $pseudoCindex = $i; }
				      if ( $labels[$i] eq "pfilter" ) { $pfilterindex = $i; }
				      if ( $labels[$i] eq "vct1/4" )  { $vct14index = $i; }
				      }
				  if ( $opt_v)
				  {   print " @labels \n pseudoCindex=$pseudoCindex,  pfilterindex=$pfilterindex, vct14index=$vct14index\n";
				      };
				  if ( $pseudoCindex == -1 || $pfilterindex == -1 || $vct14index == -1)
				  {   print " @labels \n scan skipped, fields are missing\n";
				      return;
				      };
		     }  }
		 else
		 {  @values = split /\s+/, $line; 
		    $filter= $values[$pfilterindex];
			 $count = $values[$vct14index];
			 $values[$vct14index] = $values[$pseudoCindex] * $abs[$filter];
		    if ( $opt_v ) 
			 {  print "f=$filter c=$count --> @values \n";
				 }
		    print OUT "@values\n";
		    }	  
		 }
   close OUT;
   }
 
