{$H+}  // ansi strings
{$C+}  // assertions on
{
  process ./smo/ad0111.xy obtained with smo from ./dat/ad0111.xy
  result in ./nrm/ad0111.xy
  nrm ad0111
}
program nrm;

uses mtx09;

const // TODO regions should be taken in 2d arg of cmd line...
  regions='15,1500;3000,4000'; // the low and high frequency regions
                                // to calculate area and normalize
var
  d: mtx;          // input data
  xy: mtx;         // work matrix
  roi: mtx;        // define regions 1 and 2
  r: mtx;          // result table
  name: string;    // file name prefix
  a1, a2: double;  // area of low/high frequency regions
  n: longint;      // number of data rows in data files
  f: text;

function area(xy:mtx):double;
var
  i, n: longint;
  a, ym, dx: double;
begin
  n := lgn(xy);
  assert(n>1);
  a := 0;
  for i := 2 to n do begin
    ym := (elm(xy,i-1,2) + elm(xy,i,2))/2;
    dx := elm(xy,i,1) - elm(xy,i-1,1);
    a := a + ym * dx
  end;
  area := a
end;

begin
  assert(paramcount=1);
// file with smooth background calculated by smo
// MUST BE CONSISTANT with the shell script "run" where the
// the shell function "cmd" does the smo step and must find data
// and write its output as expected here...
  name := './smo/' + paramstr(1) + '.xy';
  equ(roi,regions); // TODO should accept a flat vector and remap with mym()
  mrd(d,name);
  n := lgn(d);
  // Calcul area of the 1st region
  zer(xy,n,2);
  elm(col(xy,1),col(d,1));
  elm(col(xy,2),col(d,5));
  lgn(xy,lgn(roi,1));
  // mwr(xy,'nrmlow.xy');
  a1 := area(xy);
  // high
  zer(xy,n,2);
  elm(col(xy,1),col(d,1));
  elm(col(xy,2),col(d,5));
  lgn(xy,lgn(roi,2));
  // mwr(xy,'nrmhi.xy');
  a2 := area(xy);
  // normalized data; area of low frequ. region = 100
  zer(r,lgn(d),4);
  elm(col(r,1),col(d,1));
  dvd(col(d,2),a1/100); elm(col(r,2),col(d,2));
  dvd(col(d,5),a1/100); elm(col(r,3),col(d,5));
  // read back original data in file name+'.txt'
  name := './dat/'+paramstr(1)+'.xy';
  mrd(d,name);
  assert(n=lgn(d));
  dvd(col(d,2),a1/100); elm(col(r,4),col(d,2));
  name := './nrm/'+paramstr(1)+'.xy';
  assert(col(r)=4);
  // output normalized data and area ratio as comments at end
  rwr(name);   // clear previous file because
  mwr(r,name); // this avatar of mwr appends
  // append comments with standard Pascal I/O procedure writeln()
  apn(name,f);     // open stream f in append mode
  writeln(f,'# aw/as ',a2/a1:0:3,'   a1 ',a1:0:4,'   a2 ',a2:0:4);
// output area ration as a "#" comment
  clo(f) // flush/close stream f
end.
