/*

  Otmar Stahl

  ypos.c

  Compute yabs from yabs/order (in mm!) for rotation of CCD
  
  Input wavelemgth table needs two (R*4) columns:
  
  :XABS and :Y
  
  Parameters:
  
  1) Input / output wavelength table (line.tbl)
  2) Input table with coefficients of y-fit
  
  Algorithm:
  
  Compute yabs for (xabs/order)

.VERSION
 051014		last modif

*/

/* system includes */

#include <stdio.h>

/* general Midas includes */

#include <stdlib.h>

#include <tbldef.h>
#include <midas_def.h>
#include <ok.h>

/* FEROS specific includes */

#include <nrutil.h>
#include <mutil.h>

int main ()
{

  char wlc_table[60], pos_table[60], line[80];

  int i, j, iav, inull, tid1, tid2, ncol, nrow, nsort, acol, arow;
  int icol[3], null[2], select, nlast, nfirst, fit_deg;
  int dunit, dnul;

  float rnull, col[2], xabs, yabs;

  double *ad, dnull;
  
  SCSPRO ("ypos");
  
  TCMNUL(&inull,&rnull,&dnull);
  
  SCKGETC ("IN_A", 1, 60, &iav, wlc_table);
  SCKGETC ("IN_B", 1, 60, &iav, pos_table);

  TCTOPN (wlc_table, F_IO_MODE, &tid1);

  TCTOPN (pos_table, F_D_MODE, &tid2); 
  SCDRDI(tid2, "FIRSTORD", 1, 1, &iav, &nfirst, &dunit, &dnul);  
  SCDRDI(tid2, "ECHORD", 1, 1, &iav, &nlast, &dunit, &dnul); 
  SCDRDI(tid2, "FITORD", 1, 1, &iav, &fit_deg, &dunit, &dnul); 

  TCIGET (tid1, &ncol, &nrow, &nsort, &acol, &arow);

  /* columns :X and :Y must exist! */

  ad = dvector (1, fit_deg);

  TCCSER (tid1, ":X", &icol[0]);
  TCCSER (tid1, ":Y", &icol[1]);
  TCCSER(tid1, ":YABS", &icol[2]);
  if(icol[2] == -1)
    {
      TCCINI(tid1, D_R4_FORMAT, 1, "F8.4", "", ":YABS", &icol[2]);
      sprintf(line, "column YABS created %d",icol[2]);
      SCTPUT(line);
    }
  else
    {
      sprintf(line, "column YABS found");
      SCTPUT(line);
    }

  /* read input table */

  for (i = 1; i <= nrow; i++)
    {
      TCSGET(tid1, i, &select);
      if (select) {
	TCRRDR (tid1, i, 2, icol, col, null);
	xabs =  col[0];
	j =  (int) col[1];
	
	if(j>0) 
	  {
	    sprintf(line, "FIT%04i", nlast - (j - 1));
	    
	    SCDRDD(tid2, line, 1, fit_deg, &iav, &ad[1], &dunit, &dnul);
	    yabs =  eval_dpoly (xabs, ad, fit_deg);
	    TCEWRR(tid1, i, icol[2], &yabs);
	  }
      }
    }
  TCTCLO (tid1);
  TCTCLO (tid2);

  /* release memory and exit */

  free_dvector(ad, 1, fit_deg);
  SCSEPI ();
  exit(0);
}
