/* @(#)comp_back.c	19.1 (ESO-IPG) 02/25/03 14:21:23 */
/* 

   Otmar Stahl, Anton Malina
   
   comp_back.c  

   subtract background and normalize flat

*/

/* general Midas includes */

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

/* FEROS specific includes */

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

int comp_back
#ifdef __STDC__
(
 int npix[], int imno, int imnor, int iparam[], 
 int nact, float **centers, int mode, int xysize[], int fibmode
)
#else
     (
      npix, imno, imnor, iparam, nact, centers, mode, xysize, fibmode
      )
     int npix[], imno, imnor, nact, iparam[], mode, xysize[2], fibmode; 
     float **centers;
#endif

{
  float **ya;
  double ** y2a;
  float smowidthx, smowidthy;
  float *x1, x2, *smooth, *raw, *xval, *yval;
  int  bgdist;
  int  i, j, k, m, n, offset, actvals, width1, width2;

  smowidthx = iparam[0];
  smowidthy = iparam[1];  
  width1 = iparam[2];
  width2 = iparam[3];
  bgdist = iparam[4];

  m = npix[0] / smowidthx;
  n = npix[1] / smowidthy;

  xval = vector (1, m);
  yval = vector (1, n);
  x1 = vector (0, npix[0]);
  smooth = vector (0, npix[0]);
  raw = vector (0, npix[0]);

  ya = matrix(1, m, 1, n);
  y2a = dmatrix(1, m, 1, n);

  /* populate arrays */

  for(k = 0; k < npix[0]; k++)
    {
      x1[k] = k;
    }
  for(k = 1; k <= m; k++)
    {
      j = k * smowidthx;
      xval[k] = j;
    }
  for(k = 1; k <= n; k++)
    {
      j = k * smowidthy;
      yval[k] = j;
    }

  /* fit background */

  fit_back(xval, yval, ya, y2a, npix, imno, m, n, nact, 
	   centers, xysize, bgdist, fibmode);

  /* compute and subtract background */
  
  for(i = 0; i < npix[1]; i++)
    {
      x2 = i;
      offset = npix[0] * i;
      nat_spline2d_int(xval, yval, ya, y2a, m, n, npix[0], x1, x2, smooth);

      SCFGET(imno, offset + 1, npix[0], &actvals, (char *) raw);

      if (mode == 0) /* subtract background */
	{
	  for(j = 0; j < npix[0]; j++)
	    {
	      raw[j] = raw[j] - smooth[j];
	    }
	  SCFPUT(imnor, offset + 1, npix[0], (char *) raw);
	}
      else /* write background */
	{
	  SCFPUT(imnor, offset + 1, npix[0], (char *) smooth);
	}
    }       

  free_dmatrix(y2a, 1, m, 1, n);
  return 0;
}



