/*
 * This file is part of the ESO SINFONI Pipeline
 * Copyright (C) 2004,2005 European Southern Observatory
 *
 * 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, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */
/*----------------------------------------------------------------------------

   File name    :   sinfo_detlin_ini_by_cpl.c
   Author       :   Andrea Modigliani
   Created on   :    May 17, 2004
   Description  :    produce and read an .ini file for the search of static
                        bad pixels
 ---------------------------------------------------------------------------*/
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
/*---------------------------------------------------------------------------
                                Includes
 ---------------------------------------------------------------------------*/
#include <string.h>
#include "sinfo_detlin_ini_by_cpl.h"
#include "sinfo_error.h"
#include "sinfo_hidden.h"
#include "sinfo_raw_types.h"
#include "sinfo_functions.h"
#include "sinfo_file_handling.h"
/*---------------------------------------------------------------------------
                    Functions private to this module
 ---------------------------------------------------------------------------*/
static void     
parse_section_frames(detlin_config *, 
                     cpl_frameset* sof, cpl_frameset** raw,int* status);
static void     
parse_section_response(detlin_config *, cpl_parameterlist* cpl_cfg);

/**@{*/
/**
 * @addtogroup sinfo_detlin Detector Linearity Determination Functions
 *
 * TBD
 */

/**
  @name     sinfo_parse_cpl_input_detlin
  @memo     Parse input frames & parameters and create a blackboard.
  @param    cpl_cfg pointer to parameterlist
  @param    sof pointer to input set of frames
  @param    raw pointer to input set of raw frames
  @return   1 newly allocated detlin_config blackboard structure.

  @doc      The requested ini file is parsed and a blackboard object is 
            created, then updated accordingly. Returns NULL in case of error.
 */

detlin_config * 
sinfo_parse_cpl_input_detlin(cpl_parameterlist * cpl_cfg, cpl_frameset* sof, 
                             cpl_frameset** raw)
{

    detlin_config    *    cfg ;
    int                   status ;

    /* check on input ini file removed */
    /* loading input ini file removed */


    cfg = sinfo_detlin_cfg_create();

    /*
     * Perform sanity checks, fill up the structure with what was
     * found in the ini file
     */

    status = 0 ;
    parse_section_response(cfg, cpl_cfg);
    parse_section_frames(cfg, sof, raw,  &status);
    if (status > 0) {
        sinfo_msg_error("parsing cpl input");
        sinfo_detlin_free(&cfg);
        cfg = NULL ;
        return NULL ;
    }
    return cfg ;
}

/**
  @name     parse_section_frames
  @memo     Parse input frames.
  @param    cfg pointer to detlin_config structure
  @param    sof pointer to input set of frames
  @param    raw pointer to input set of raw frames
  @param    status status of function
  @return   void

 */

static void   
parse_section_frames(detlin_config * cfg,
                     cpl_frameset * sof,
                     cpl_frameset** raw,
                     int* status)
{

    int                     i=0;
    char* tag=NULL;
    int  nraw = 0;
    int  nraw_good = 0;
    cpl_frame* frame=NULL;
    char spat_res[FILE_NAME_SZ];
    char lamp_status[FILE_NAME_SZ];
    char band[FILE_NAME_SZ];
    int ins_set=0;

    sinfo_extract_raw_frames_type(sof,raw,RAW_LINEARITY_LAMP);

    nraw=cpl_frameset_get_size(*raw);

    if (nraw < 1) {
        sinfo_msg_error( "Too few (%d) raw frames (%s)  present in"
                        "frameset!Aborting...",nraw, RAW_LINEARITY_LAMP);
        (*status)++;
        return;
    }



    /* get "general:infile" read it, check input sinfo_matrix */
    /* Allocate structures to go into the blackboard */
    cfg->framelist = cpl_malloc(nraw * sizeof(char*));

    /* read input frames */
    for (i=0 ; i<nraw ; i++) {
        /* cfg->framelist[i] = cpl_malloc(FILE_NAME_SZ * sizeof(char));  */
        frame = cpl_frameset_get_frame(*raw,i);
        if(sinfo_file_exists((char*)cpl_frame_get_filename(frame))==1)
        {
            tag = (char*)cpl_frame_get_tag(frame) ;
            if(sinfo_is_flat_lindet(tag) || sinfo_is_dark(tag)) {
                /* Store file name into framelist */
                cfg->framelist[i]=cpl_strdup(cpl_frame_get_filename(frame));
                nraw_good++;
            }
        }
    }

    /* Copy relevant information into the blackboard */
    cfg->nframes         = nraw_good ;


    if (nraw_good < (cfg->order+1)) {
        sinfo_msg_error( "Too few (%d) raw frames (%s)  present in"
                        "frameset as we do a %d order polymnomial fit"
                        "!Aborting...",nraw_good,
                        RAW_LINEARITY_LAMP,cfg->order);

        (*status)++;
        return;
    }


    strcpy(cfg -> outName, BP_LIN_OUT_FILENAME);

    check_nomsg(frame = cpl_frameset_get_frame(*raw,0));
    sinfo_get_spatial_res(frame,spat_res);

    switch(sinfo_frame_is_on(frame))
    {
    case 0:
        strcpy(lamp_status,"on");
        break;
    case 1: 
        strcpy(lamp_status,"off");
        break;
    case -1:
        strcpy(lamp_status,"undefined");
        break;
    default: 
        strcpy(lamp_status,"undefined");
        break;


    }

    sinfo_get_band(frame,band);
    sinfo_msg("Spatial resolution: %s lamp status: %s band: %s \n",
              spat_res,              lamp_status,    band);


    sinfo_get_ins_set(band,&ins_set);


    cleanup:

    return;
}
/**
  @name     parse_section_response
  @memo     Parse response parameters.
  @param    cfg pointer to detlin_config structure
  @param    cpl_cfg pointer to input parameters
  @return   void

 */
static void     
parse_section_response(detlin_config * cfg,cpl_parameterlist *   cpl_cfg)
{
    cpl_parameter *p;

    p = cpl_parameterlist_find(cpl_cfg, "sinfoni.bp_lin.order");
    cfg -> order = cpl_parameter_get_int(p);

    p = cpl_parameterlist_find(cpl_cfg,"sinfoni.bp_lin.thresh_sigma_factor");
    cfg->threshSigmaFactor = (float) cpl_parameter_get_double(p);

    p = cpl_parameterlist_find(cpl_cfg, "sinfoni.bp_lin.low_rejection");
    cfg -> loReject = (float) cpl_parameter_get_double(p);

    p = cpl_parameterlist_find(cpl_cfg, "sinfoni.bp_lin.high_rejection");
    cfg -> hiReject = (float) cpl_parameter_get_double(p);

    p = cpl_parameterlist_find(cpl_cfg,"sinfoni.bp_lin.nlin_threshold");
    cfg->nonlinearThresh = (float) cpl_parameter_get_double(p);

    /* name of the data cube storing the found polynomial coefficients */
    strcpy(cfg->coeffsCubeName, BP_LIN_COEFFS_CUBE_OUT_FILENAME);

    return ;
}
/**
@name sinfo_detlin_free
@memo deallocates detlin_config structure
@param cfg pointer to detlin_config structure
@return void
 */
void
sinfo_detlin_free(detlin_config ** cfg)
{  
    int i=0;
    if(*cfg!=NULL) {
        for(i=0;i<(*cfg)->nframes; i++) {
            if((*cfg)->framelist[i] != NULL) cpl_free((*cfg)->framelist[i]);
        }
        cpl_free((*cfg)->framelist);
        sinfo_detlin_cfg_destroy((*cfg));
        *cfg = NULL;
    }
    return;

}
/**@}*/
