#!/usr/bin/perl

  &read_template_data ;
  for($w=1;$w<=10;++$w){
    open g,"> tmp$w";
    for($i=0;$i<=$#D;++$i){
      if($D[$i]==$w){ printf g "$R[$i] $V[$i]\n"; }
    }
    close g;
  }


# Default Data
 $X1[0]= 163;    $X2[0]= 257 ;
 $R1[0]= 8.162 ; $R2[0]= 8.347 ;

 $X1[1]= 15;    $X2[1]= 212 ;
 $R1[1]= 8.997 ; $R2[1]= 9.379 ;

 $X1[2]= 100;    $X2[2]= 256 ;
 $R1[2]= 10.246; $R2[2]= 10.545;

 $X1[3]= 71 ;    $X2[3]= 299 ;
 $R1[3]= 11.272; $R2[3]= 11.702;

 $X1[4]= 170;    $X2[4]= 292 ;
 $R1[4]= 12.522; $R2[4]= 12.748;
 for($d=0;$d<5;++$d){
   $A[$d] = ($R2[$d] - $R1[$d] ) / ( $X2[$d] - $X1[$d] );
   $B[$d] =  $R1[$d] - $A[$d] * $X1[$d] ;
#  printf "%d %e %6.3f - %6.3f \n",$d,$A[$d],$A[$d]+$B[$d],$A[$d]*320+$B[$d];
 }

 
### new file  ---- Edit here ---
$file = "COMQ80064678";       # File name with path from current directory
$dd = 3 ; $x=245; $r=11.002 ; # Detector number, X position, Lambda 
#### 

$d=$dd-1;

$b=$r-$A[$d]*$x;$dB = $b-$B[$d] ;

$min=100000;$max=-100000;
for($d=0;$d<5;++$d){
  $c=sprintf "q_list_stat $file %d - 180 1 | ",$d+1;
  open g,$c ;
  while(<g>){
    chop ; split ;
    $v = $_[4];
    if($v>$max){$max=$v;}
    if($v<$min){$min=$v;}
  }
  close g;
}
for($d=0;$d<5;++$d){
  open h,"> new$d";
  $c=sprintf "q_list_stat $file %d - 180 1 | ",$d+1;
  open g,$c ;
  while(<g>){
    chop ; split ;
    $x = $_[1];
    $v = ($_[4]-$min)/($max-$min);
    $r = $A[$d] * $x + $B[$d]+$dB ;
    printf h "%f %e\n",$r,$v;
  }
  close g;
  close h;
  printf "Det %d  %8.4f  --  %8.4f \n",$d+1, 
    $A[$d] * 1 + $B[$d]+$dB,$A[$d] * 320 + $B[$d]+$dB ;
}


 
  open GNUPLOT, "| gnuplot -persist -geometry 2000x400";
  print GNUPLOT <<gnuplot_Commands_DoneA;
   set xlabel \"Wavelength\"
   set xrange[7.5:13.5]
  set nokey
 plot \"tmp1\" using 1:2 with lines lt 1, \"tmp2\" using 1:2 with lines lt 1 ,\\
\"tmp3\" using 1:2 with lines lt 1 , \"tmp4\" using 1:2 with lines lt 1, \\
\"tmp5\" using 1:2 with lines lt 1, \"tmp6\" using 1:2 with lines lt 2, \\
\"tmp7\" using 1:2 with lines lt 2, \"tmp8\" using 1:2 with lines lt 2, \\
\"tmp9\" using 1:2 with lines lt 2, \"tmp10\" using 1:2 with lines lt 2, \\
\"new0\" using 1:2 with lines, \"new1\" using 1:2 with lines , \\
\"new2\" using 1:2 with lines, \"new3\" using 1:2 with lines , \\
\"new4\" using 1:2 with lines

gnuplot_Commands_DoneA
  close GNUPLOT;



exit ;


sub read_template_data {
  $i=0;
  open g ,"<template_data.txt";
  while(<g>){
    chop ; split ; $D[$i]=$_[0] ;
    $R[$i]=$_[1] ; $V[$i]=$_[2] ;
    $i++;
  }
  close g;
}
