/*===========================================================================
  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  : mergebadpixels.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_uves.h>
#include <flames_newmatrix.h>
#include <flames_mergebadpixels.h>


flames_err mergebadpixels(flames_frame *framebuffer, char *badpxfname)
{
    int status=0;
    int badid=0;
    int actvals=0;
    int actsize=0;
    int unit=0;
    int null=0;
    int tnaxis=0;
    double *tstart=0;
    double *tstep=0;
    int *tnpix=0;
    int ibuf[5]={0,0,0,0,0};
    char messagebuffer[160];
    int32_t ix=0;
    frame_mask **newbadpixel=0;

    frame_mask *fmvecbuf1=0;
    frame_mask *fmvecbuf2=0;
    int32_t totpixuplimit=0;

    memset(messagebuffer, '\0', 160);

    /* allocate the local vectors */
    tstart = dvector(0,1);
    tstep = dvector(0,1);
    tnpix = ivector(0,1);
    newbadpixel = fmmatrix(0,framebuffer->subrows-1, 0, framebuffer->subcols-1);

    fmvecbuf1 = newbadpixel[0];
    fmvecbuf2 = framebuffer->badpixel[0];
    totpixuplimit = (framebuffer->subrows*framebuffer->subcols)-1;

    /* is this a good filename? */
    if ((status = SCFINF(badpxfname, 3, ibuf)) != 0) {
        /* I could not open the file for information */
        sprintf(messagebuffer, "File %s could not be opened",
                        badpxfname);
        SCTPUT(messagebuffer);
    }
    else {
        /* yes, the file exists; is it a data frame? */
        if (ibuf[0] != F_IMA_TYPE) {
            /* wrong file type */
            sprintf(messagebuffer, "File %s is not of the type required for a bad \
pixel mask",
badpxfname);
            SCTPUT(messagebuffer);
        }
        else {
            /* yes, it is a data frame; open it */
            if ((status = SCFOPN(badpxfname, D_I1_FORMAT, 0, F_IMA_TYPE,
                            &badid)) != 0) {
                /* I could not open the file: protest... */
                sprintf(messagebuffer, "File %s could not be opened",
                                badpxfname);
                SCTPUT(messagebuffer);
            }
            /* read naxis */
            if ((status=SCDRDI(badid, "NAXIS", 1, 1, &actvals, &tnaxis,
                            &unit, &null)) != 0) {
                /* something went wrong in SCDRDI */
                sprintf(messagebuffer, "Could not read the NAXIS descriptor in \
file %s", 
badpxfname);
                SCTPUT(messagebuffer);
            }
            /* does naxis match the data frame? */
            if (tnaxis != 2) {
                /* naxis does not match */
                sprintf(messagebuffer, "The dimensions of file %s do not match those \
of the data frames", 
badpxfname);
                SCTPUT(messagebuffer);
            }
            else {
                /* naxis matches, proceed to read start, step and npix */
                if ((status=SCDRDD(badid, "START", 1, 2, &actvals, tstart,
                                &unit, &null)) != 0) {
                    /* something went wrong in SCDRDD */
                    sprintf(messagebuffer, "Could not read the START descriptor in \
file %s", 
badpxfname);
                    SCTPUT(messagebuffer);
                }
                if ((status=SCDRDD(badid, "STEP", 1, 2, &actvals, tstep,
                                &unit, &null)) != 0) {
                    /* something went wrong in SCDRDD */
                    sprintf(messagebuffer, "Could not read the STEP descriptor in \
file %s", 
badpxfname);
                    SCTPUT(messagebuffer);
                }
                if ((status=SCDRDI(badid, "NPIX", 1, 2, &actvals, tnpix,
                                &unit, &null)) != 0) {
                    /* something went wrong in SCDRDI */
                    sprintf(messagebuffer, "Could not read the NPIX descriptor in \
file %s", 
badpxfname);
                    SCTPUT(messagebuffer);
                }
                /* do start, step and npix match the data frames? */
                if (fabs(tstart[0]-framebuffer->substartx) >= DEPSILON ||
                                fabs(tstart[1]-framebuffer->substarty) >= DEPSILON ||
                                fabs(tstep[0]-framebuffer->substepx) >= DEPSILON ||
                                fabs(tstep[1]-framebuffer->substepy) >= DEPSILON ||
                                tnpix[0] != framebuffer->subcols ||
                                tnpix[1] != framebuffer->subrows) {
                    /* the dimensions do not match */
                    sprintf(messagebuffer, "The dimensions of file %s do not match \
those of the data frames", 
badpxfname);
                    SCTPUT(messagebuffer);
                }
                else {
                    /* read in the badpixel mask */
                    if ((status = SCFGET(badid, 1,
                                    framebuffer->subrows*framebuffer->subcols,
                                    &actsize, (char *)newbadpixel[0]))
                                    != 0) {
                        /* something went wrong in SCFGET */
                        sprintf(messagebuffer, "Could not read the file %s as a bad \
pixel mask", 
badpxfname);
                        SCTPUT(messagebuffer);
                    }
                    /* did I get all the elements I asked for? */
                    if(actsize != framebuffer->subrows*framebuffer->subcols) {
                        /* some elements were lost: protest... */
                        sprintf(messagebuffer, "Could not completely read file %s as a \
bad pixel mask", 
badpxfname);
                        SCTPUT(messagebuffer);
                    }
                    else {
                        /* merge the new bad pixel mask in the data structure */
                        for(ix=0; ix<=totpixuplimit; ix++) {
                            if(fmvecbuf1[ix] != 0) {
                                /* mark as bad pixel */
                                fmvecbuf2[ix] = 1;
                            }
                        }
                    }
                }
            }
        }
    }

    /* free local temporarily allocated variables */
    free_dvector(tstart, 0, 1);
    free_dvector(tstep, 0, 1);
    free_ivector(tnpix, 0, 1);
    free_fmmatrix(newbadpixel, 0, framebuffer->subrows-1,
                  0, framebuffer->subcols-1);

    return(NOERR);

}

