/*===========================================================================
  Copyright (C) 2001 European Southern Observatory (ESO)

  This program is free software; you can redistribute it and/or 
  modify it under the terms of the GNU General Public License as 
  published by the Free Software Foundation; either version 2 of 
  the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public 
  License along with this program; if not, write to the Free 
  Software Foundation, Inc., 675 Massachusetss Ave, Cambridge, 
  MA 02139, USA.

  Corresponding concerning ESO-MIDAS should be addressed as follows:
    Internet e-mail: midas@eso.org
    Postal address: European Southern Observatory
            Data Management Division 
            Karl-Schwarzschild-Strasse 2
            D 85748 Garching bei Muenchen 
            GERMANY
===========================================================================*/
/* Program  : readback.c                                                   */
/* Author   : G. Mulas  -  ITAL_FLAMES Consortium                          */
/* Date     :                                                              */
/*                                                                         */
/* Purpose  : Missing                                                      */
/*                                                                         */
/*                                                                         */
/* Input:  see interface                                                   */ 
/*                                                                      */
/* Output:                                                              */
/*                                                                         */
/* DRS Functions called:                                                   */
/* none                                                                    */ 
/*                                                                         */ 
/* Pseudocode:                                                             */
/* Missing                                                                 */ 
/*                                                                         */ 
/* Version  :                                                              */
/* Last modification date: 2002/08/05                                      */
/* Who     When        Why                Where                            */
/* AMo     02-08-05   Add header         header                            */
/*-------------------------------------------------------------------------*/


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <flames_midas_def.h>
#include <flames_freeback.h>
#include <flames_uves.h>
#include <flames_newmatrix.h>
#include <flames_allocback.h>
#include <flames_readback.h>

flames_err readback(flames_background *backbuffer, char *filename, int xdegree, 
                    int ydegree)
{

    flames_background *newbackbuffer;
    int tid=0;
    int ncol=0;
    int nrow=0;
    flames_err status=0;
    int ordercol=0;
    int xcol=0;
    int ybkgcol=0;
    int xstacol=0;
    int xendcol=0;
    int ystacol=0;
    int yendcol=0;
    int i=0;
    int selstatus=0;
    float ptablein=0;
    int null=0;

    TCTOPN(filename, F_I_MODE, &tid);
    TCIGET(tid, &ncol, &nrow);

    /* initialise backbuffer scalars */
    backbuffer->Window_Number = (int32_t) nrow;
    backbuffer->xdegree = xdegree;
    backbuffer->ydegree = ydegree;
    if (nrow > 0) {
        if (allocback(backbuffer) != NOERR) {
            /* problems allocating the background buffer */
            SCTPUT("Error allocating the background buffer");
            SCSEPI();
            return flames_midas_fail();
        }
    }
    else {
        SCTPUT("No background windows available");
        SCSEPI();
        return flames_midas_fail();
    }

    backbuffer->Window_Number = 0;

    /* read in the background structure */
    if ((status = TCCSER(tid, "X", &xcol)) != 0) {
        SCTPUT("Error searching the :X column in the background table");
        SCSEPI();
        return flames_midas_fail();
    }
    if ((status = TCCSER(tid, "YBKG", &ybkgcol)) != 0) {
        SCTPUT("Error searching the :YBKG column in the background table");
        SCSEPI();
        return flames_midas_fail();
    }
    if ((status = TCCSER(tid, "ORDER", &ordercol)) != 0) {
        SCTPUT("Error searching the :ORDER column in the background table");
        SCSEPI();
        return flames_midas_fail();
    }
    if ((status = TCCSER(tid, "XSTA", &xstacol)) != 0) {
        SCTPUT("Error searching the :XSTA column in the background table");
        SCSEPI();
        return flames_midas_fail();
    }
    if ((status = TCCSER(tid, "XEND", &xendcol)) != 0) {
        SCTPUT("Error searching the :XEND column in the background table");
        SCSEPI();
        return flames_midas_fail();
    }
    if ((status = TCCSER(tid, "YSTA", &ystacol)) != 0) {
        SCTPUT("Error searching the :YSTA column in the background table");
        SCSEPI();
        return flames_midas_fail();
    }
    if ((status = TCCSER(tid, "YEND", &yendcol)) != 0) {
        SCTPUT("Error searching the :YEND column in the background table");
        SCSEPI();
        return flames_midas_fail();
    }
    if (xcol==-1 || ybkgcol==-1 || ordercol==-1 || xstacol==-1 || xendcol==-1 ||
                    ystacol==-1 || yendcol==-1) {
        SCTPUT("Missing columns in the background table");
        SCSEPI();
        return flames_midas_fail();
    }

    for (i=1; i<=nrow; i++) {
        /* is this row selected? */
        TCSGET(tid, i, &selstatus);
        if (selstatus == TRUE) {
            backbuffer->Window_Number++;
            TCERDR(tid,i,xcol,&ptablein,&null);
            backbuffer->x[backbuffer->Window_Number] = (double) ptablein;
            TCERDR(tid,i,ybkgcol,&ptablein,&null);
            backbuffer->y[backbuffer->Window_Number] = (double) ptablein;
            TCERDR(tid,i,ordercol,&ptablein,&null);
            backbuffer->window[backbuffer->Window_Number][1] = (double) ptablein;
            TCERDR(tid,i,xstacol,&ptablein,&null);
            backbuffer->window[backbuffer->Window_Number][2] = (double) ptablein;
            TCERDR(tid,i,xendcol,&ptablein,&null);
            backbuffer->window[backbuffer->Window_Number][3] = (double) ptablein;
            TCERDR(tid,i,ystacol,&ptablein,&null);
            backbuffer->window[backbuffer->Window_Number][4] = (double) ptablein;
            TCERDR(tid,i,yendcol,&ptablein,&null);
            backbuffer->window[backbuffer->Window_Number][5] = (double) ptablein;
        }
    }

    /* close the background table */
    TCTCLO(tid);

    /* Now create a new backbuffer of the right size */
    if (!(newbackbuffer = calloc(1, sizeof(flames_background)))) {
        SCTPUT("Allocation error during the allocation of new backbuffer structure");
        SCSEPI();
        return flames_midas_fail();
    }

    /* initialise newbackbuffer scalars */
    newbackbuffer->Window_Number = backbuffer->Window_Number;
    newbackbuffer->xdegree = backbuffer->xdegree;
    newbackbuffer->ydegree = backbuffer->ydegree;
    if (allocback(newbackbuffer) != NOERR) {
        /* problems allocating the background buffer */
        SCTPUT("Error allocating the new background buffer");
        SCSEPI();
        return flames_midas_fail();
    }

    for (i=1; i<=newbackbuffer->Window_Number; i++) {
        newbackbuffer->x[i] = backbuffer->x[i];
        newbackbuffer->y[i] = backbuffer->y[i];
        newbackbuffer->window[i][1] = backbuffer->window[i][1];
        newbackbuffer->window[i][2] = backbuffer->window[i][2];
        newbackbuffer->window[i][3] = backbuffer->window[i][3];
        newbackbuffer->window[i][4] = backbuffer->window[i][4];
        newbackbuffer->window[i][5] = backbuffer->window[i][5];
    }

    backbuffer->Window_Number = nrow;
    if (freeback(backbuffer) != NOERR) {
        SCTPUT("Error freeing backbuffer internals\n");
        SCSEPI();
        return flames_midas_fail();
    }

    backbuffer->Window_Number = newbackbuffer->Window_Number;
    backbuffer->x = newbackbuffer->x;
    backbuffer->y = newbackbuffer->y;
    backbuffer->window = newbackbuffer->window;
    backbuffer->coeff = newbackbuffer->coeff;
    backbuffer->expon = newbackbuffer->expon;

    free(newbackbuffer);

    return NOERR;

}
