/* $Id: xsh_paf_save.c,v 1.30 2012-12-18 16:09:54 amodigli Exp $
 *
 * This file is part of the IRPLIB Package
 * Copyright (C) 2002,2003 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, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */

/*
 * $Author: amodigli $
 * $Date: 2012-12-18 16:09:54 $
 * $Revision: 1.30 $
 * $Name: not supported by cvs2svn $
 */

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

/*-----------------------------------------------------------------------------
                                   Includes
 -----------------------------------------------------------------------------*/

#include <cpl.h>

#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <regex.h>
#include <assert.h>

#include "xsh_data_instrument.h"
#include "xsh_qc_handling.h"
#include "xsh_msg.h"
#include "xsh_paf_save.h"
#include "xsh_error.h"


/*-----------------------------------------------------------------------------
                        Defines and Static variables
 -----------------------------------------------------------------------------*/

/* Use at least this many places when printing the PAF key */
#define PAF_KEY_LEN 21
/* Right justify the PAF key and separate with an extra space */
#define PAF_KEY_FORMAT "%-21s "

/*----------------------------------------------------------------------------*/
/**
 * @defgroup xsh_paf_save    PAF file creation
 * @ingroup xsh_tools
 *
 */
/*----------------------------------------------------------------------------*/

/**@{*/

/*-----------------------------------------------------------------------------
                              Function codes
 -----------------------------------------------------------------------------*/
static FILE * irplib_paf_init(const xsh_instrument * instrume,
                              const char * recipe,
                              const char * filename,
                              const cpl_propertylist* primary_header) ;
static cpl_error_code irplib_paf_dump( qc_description *pqc, 
  const char * kwnamw, const cpl_propertylist * paflist,
				       FILE *paf ) ;
static cpl_error_code irplib_paf_dump_int( char *kw, int value,
					     const char *comment, FILE *paf ) ;
static cpl_error_code irplib_paf_dump_double( char *kw, double value,
					     const char *comment, FILE *paf ) ;
static cpl_error_code irplib_paf_dump_string( char *kw, const char * value,
					     const char *comment, FILE *paf ) ;
/*----------------------------------------------------------------------------*/

/**
  @brief   Create a new PAF file
  @param   instrument Name of instrument in capitals (NACO, VISIR, etc.)
  @param   recipe   Name of recipe
  @param   paflist  Propertylist to save
  @param   filename Filename of created PArameter File
  @param   pro_catg The PRO.CATG of the product file
  @return  CPL_ERROR_NONE or the relevant CPL error code on error

  Create a PAF from some FITS cards from the file
  ref_file and QC parameters in a propertylist qclist.
  All QC parameters relevant to the product are checked. A message 
  is issued for each missing QC parameter.

*/
/*----------------------------------------------------------------------------*/
cpl_error_code xsh_paf_save( const xsh_instrument * instrument,
			     const char *recipe,
			     const cpl_propertylist * paflist,
			     const char * filename,
			     const char * pro_catg )
{
  qc_description * pqc ;
  FILE *paf = NULL ;
  const char * arm ;

  XSH_ASSURE_NOT_NULL( instrument ) ;
  XSH_ASSURE_NOT_NULL( recipe ) ;
  XSH_ASSURE_NOT_NULL( paflist ) ;
  XSH_ASSURE_NOT_NULL( filename ) ;

  arm = xsh_instrument_arm_tostring( (xsh_instrument *)instrument ) ;
  xsh_msg_dbg_low( "=====>>>>> paf_save (%s, %s, %s)", recipe,
		   arm, pro_catg ) ;

  paf = irplib_paf_init( instrument, recipe, filename, paflist ) ;

  pqc = NULL ;
  /*
    Find all QC relevant for this product and check if they are
    present in the FITS header. Print a message for each missing QC
  */
  while ( (pqc = xsh_get_qc_desc_by_recipe( recipe, pqc )) != NULL ) {
    xsh_msg_dbg_low( "    Found KW: %s\n", pqc->kw_name ) ;
    /*
      Check that the QC is relevant for this pro_catg
    */
#if 1
    if ( xsh_is_qc_for_pro_catg( pro_catg, pqc ) == 0 ) {
      // No, ignore it
      xsh_msg_dbg_low( "QC '%s' not for PRO.CATG '%s'", pqc->kw_name,
		       pro_catg ) ;
      continue ;
    }
#endif
    /*
      Check that the QC is relevant for this arm
    */
    if ( xsh_is_qc_for_arm( arm, pqc ) == 0 ) {
      /* No, ignore it */
      xsh_msg_dbg_low( "QC '%s' not for arm '%s'", pqc->kw_name, arm ) ;
      continue ;
    }
    /* Check if kw is in the propertylist
       There is a special case if the keyword contains the letter 'i':
       in this case one should search for all the KW in the propertylist
       by replacing i by 0, 1, 2, ... untill not found
    */
    if ( strchr( pqc->kw_name, 'i' ) != NULL ) {
      /* Special multiple kw with 0, 1, 2, .. */
      char kformat[256]; 
      const char *pk;
      char* pm;
      int i ;
      xsh_msg_dbg_low( " ++++ Multiple KW '%s'", pqc->kw_name ) ;

      for( i = 0, pk = pqc->kw_name, pm = kformat ; *pk != '\0' ; i++, pk++ )
	if ( *pk == 'i' ) {
	  strcpy( pm, "%d" ) ;
	  pm += 2 ;
	}
	else *pm++ = *pk ;
      *pm = '\0' ;
      for( i = 0 ; i<10 ; i++ ) {
	char curname[256] ;
	sprintf( curname, kformat, i ) ;
	xsh_msg_dbg_low( "      %d --> '%s'", i, curname ) ;
	if ( cpl_propertylist_has( paflist, curname ) ) {
	  xsh_msg_dbg_low( "QC Parameter \"%s\" is in propertylist",
			 curname ) ;
	  /* Dump data to PAF */
	  irplib_paf_dump( pqc, curname, paflist, paf ) ;
	}
	else break ;
      }
      if ( i == 0 ) xsh_msg( "QC Parameter \"%s\" NOT in propertylist",
			     pqc->kw_name ) ;
    }
    else if ( cpl_propertylist_has( paflist, pqc->kw_name ) ) {
      xsh_msg_dbg_low( "QC Parameter \"%s\" is in propertylist",
		     pqc->kw_name ) ;
      /* Dump data to PAF */
      irplib_paf_dump( pqc, pqc->kw_name, paflist, paf ) ;
    }
    else xsh_msg_debug( "QC Parameter \"%s\" NOT in propertylist",
		  pqc->kw_name ) ;

  }

  /* Close PAF */
  fclose( paf ) ;

 cleanup:
  return cpl_error_get_code() ;

}

/**
  @brief   Open a new PAF file, output a default header.
  @param   instrument  Name of instrument in capitals (NACO, VISIR, etc.)
  @param   recipe    Name of recipe
  @param   filename  Filename of created product
  @param   primary_header primary header
  @return  PAF stream or NULL on error

  This function creates a new PAF file with the requested file name.
  If another file already exists with the same name, it will be overwritten
  (if the file access rights allow it).

  This function returns an opened file pointer, ready to receive more data
  through fprintf()'s. The caller is responsible for fclose()ing the file.

  Possible _cpl_error_code_ set in this function:
  - CPL_ERROR_NULL_INPUT if an input pointer is NULL
  - CPL_ERROR_FILE_IO if fopen(), or fprintf() fails

 */
/*----------------------------------------------------------------------------*/
static FILE * irplib_paf_init(const xsh_instrument * instrument,
                              const char * recipe,
                              const char * filename,
                              const cpl_propertylist* primary_header)
{
  FILE * paf = NULL;
  char * paf_id = NULL;
  const char paf_desc[] = "QC file";
  int nlen;
  cpl_error_code error;
  const char* key_value = NULL;


  cpl_ensure(instrument != NULL, CPL_ERROR_NULL_INPUT, NULL);
  cpl_ensure(recipe     != NULL, CPL_ERROR_NULL_INPUT, NULL);
  cpl_ensure(filename   != NULL, CPL_ERROR_NULL_INPUT, NULL);

#if 0
  paf_id = cpl_malloc(sizeof(char) * 
		      (strlen(instrument) + strlen("/") + strlen(recipe) + 1));
  assert( paf_id != NULL);
  strcpy(paf_id, instrument);
  strcat(paf_id, "/");
  strcat(paf_id, recipe);
#else
  paf_id = xsh_stringcat_any( recipe, (void*)NULL ) ;
#endif
  paf = fopen(filename, "w");

  if (paf == NULL) {
    cpl_free(paf_id);
    cpl_ensure(0, CPL_ERROR_FILE_IO, NULL);
    return NULL;
  }

  /* Some ugly, traditional error handling that obscures
     the actual functionality (i.e. to fprintf() some strings) */
    
  error = CPL_ERROR_NONE;

  if (!error) {
    nlen = fprintf(paf, "PAF.HDR.START         ;# start of header\n");
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }

  if (!error) {
    nlen = fprintf(paf, "PAF.TYPE              \"pipeline product\" ;\n");
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }

  if (!error) {
    nlen = fprintf(paf, "PAF.ID                \"%s\"\n", paf_id);
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }

  if (!error) {
    nlen = fprintf(paf, "PAF.NAME              \"%s\"\n", filename);
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }

  if (!error) {
    nlen = fprintf(paf, "PAF.DESC              \"%s\"\n", paf_desc);
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }

  if (!error) {
    nlen = fprintf(paf, "PAF.CHCK.CHECKSUM     \"\"\n");
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }

  if (!error) {
    nlen = fprintf(paf, "PAF.HDR.END           ;# end of header\n");
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }


  if(cpl_propertylist_has(primary_header,"ARCFILE")) {
    key_value=cpl_propertylist_get_string(primary_header,"ARCFILE");
  } else {
    key_value="ARCFILE_NOT_FOUND";
  }
  if (!error) {
    nlen = fprintf(paf, "ARCFILE               \"%s\";# archive file name\n",key_value);
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }

  if(cpl_propertylist_has(primary_header,"PIPEFILE")) {
    key_value=cpl_propertylist_get_string(primary_header,"PIPEFILE");
  } else {
    key_value="PIPEFILE_NOT_FOUND";
  }
  if (!error) {
    nlen = fprintf(paf, "PIPEFILE              \"%s\";# File name of data product\n",key_value);
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }


  if(cpl_propertylist_has(primary_header,"PRO.REC1.PIPE.ID")) {
    key_value=cpl_propertylist_get_string(primary_header,"PRO.REC1.PIPE.ID");
  } else {
    key_value="PRO_REC1_PIPE_ID_NOT_FOUND";
  }
  if (!error) {
    nlen = fprintf(paf, "PRO.REC1.PIPE.ID      \"%s\";# Pipeline (unique) identifier\n",key_value);
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }




  if (!error) {
    nlen = fprintf(paf, "PRO.TYPE              \"REDUCED\";# Product type\n");
    if (nlen <= PAF_KEY_LEN) error = CPL_ERROR_FILE_IO;
  }



  if (!error) {
    nlen = fprintf(paf, "\n");
    if (nlen != 1) error = CPL_ERROR_FILE_IO;
  }

  cpl_free(paf_id);


  fflush( paf ) ;

  if(paf != NULL) {
    return paf;
  }

  if (error) {
     cpl_msg_error(cpl_func, "Could not write PAF: %s", filename);
     fclose(paf);
     cpl_ensure(0, error, NULL);
   }

  return NULL;
}

static void no_space( char * str )
{
  for( ; *str != '\0' ; str++ )
    if ( *str == ' ' ) *str = '.' ;
}

/**
  @brief   Print a propertylist as PAF
  @param   pqc  Pointer to the description of the QC parameter
  @param   kwname Keyword name
  @param   paflist Propertylist from which the values are extracted
  @param   paf   PAF stream
  @return  CPL_ERROR_NONE or the relevant _cpl_error_code_ on error

  The property names are printed with these modifications:
   Any space-character is replaced by a . (dot).

  Thus a property name
  QC PART1 PART2 PART3
  will cause the printing of a line with QC.PART1.PART2.PART3 as key.

  Supported property-types:
  CPL_TYPE_CHAR (cast to int)
  CPL_TYPE_INT 
  CPL_TYPE_LONG (only if sizeof(long) == sizeof(int), cast to int)
  CPL_TYPE_FLOAT (cast to double)
  CPL_TYPE_DOUBLE
  CPL_TYPE_STRING
 
  Possible _cpl_error_code_ set in this function:
  - CPL_ERROR_NULL_INPUT       if an input pointer is NULL
  - CPL_ERROR_FILE_IO          if fprintf() fails
  - CPL_ERROR_UNSUPPORTED_MODE if the list contains unsupported property-types

 */
static cpl_error_code irplib_paf_dump( qc_description *pqc, const char *kwname,
				       const cpl_propertylist * paflist,
				       FILE *paf )
{
  cpl_error_code err=CPL_ERROR_NONE;
  char * keydot = NULL, *pk ;

  keydot = cpl_strdup( kwname ) ;
  pk = keydot ;
  /* Replace spaces by dots */
  no_space( keydot ) ;
  if ( strncmp( keydot, "ESO.", 4 ) == 0 ) pk += 4 ;
  xsh_msg_dbg_low( "irplib_dump: '%s'", pk ) ;

  switch( cpl_propertylist_get_type( paflist, kwname ) ) {
  case CPL_TYPE_CHAR:
    err = irplib_paf_dump_int(pk,
			      cpl_propertylist_get_char( paflist, kwname),
			      pqc->kw_help, paf);
    break ;
  case CPL_TYPE_INT:
    err = irplib_paf_dump_int(pk,
			      cpl_propertylist_get_int( paflist, kwname),
			      pqc->kw_help, paf);
    break;
  case CPL_TYPE_LONG:
    if (sizeof(long) == sizeof(int)) /* FIXME: Change to #if */
    err = irplib_paf_dump_int(pk,
			      cpl_propertylist_get_long( paflist,
							 kwname),
			      pqc->kw_help, paf);
    break;
  case CPL_TYPE_FLOAT:
    err = irplib_paf_dump_double(pk,
				 cpl_propertylist_get_float( paflist,
							     kwname),
				 pqc->kw_help, paf);
    break;
  case CPL_TYPE_DOUBLE:
    err = irplib_paf_dump_double(pk,
				 cpl_propertylist_get_double( paflist,
							      kwname),
				 pqc->kw_help, paf);
    break;
  case CPL_TYPE_STRING:
    err = irplib_paf_dump_string(pk,
				 cpl_propertylist_get_string( paflist,
							     kwname),
				 pqc->kw_help, paf);
    break;
  default:
    err = CPL_ERROR_UNSUPPORTED_MODE;
  }
  cpl_free(keydot);
  return err ;
}

/**
  @brief    Print an int-property as PAF
  @param    key      Property key
  @param    value    Property value
  @param    comment  Optional property comment
  @param    paf      PAF stream
  @return   CPL_ERROR_NONE or the relevant _cpl_error_code_ on error
  @see irplib_paf_dump_string

 */
static cpl_error_code irplib_paf_dump_int( char *key, int value,
					const char *comment, FILE *paf )
{
  cpl_ensure_code(paf,   CPL_ERROR_NULL_INPUT);
  cpl_ensure_code(key,   CPL_ERROR_NULL_INPUT);

  if (comment == NULL)
    cpl_ensure_code(fprintf(paf, PAF_KEY_FORMAT "%d\n",
			    key, value) > PAF_KEY_LEN,
		    CPL_ERROR_FILE_IO);
  else
    cpl_ensure_code(fprintf(paf, PAF_KEY_FORMAT "%d ; # %s\n",
			    key, value, comment) > PAF_KEY_LEN,
		    CPL_ERROR_FILE_IO);

  return CPL_ERROR_NONE;
}

/**
  @brief    Print a double-property as PAF
  @param    key      Property key
  @param    value    Property value
  @param    comment  Optional property comment
  @param    paf      PAF stream
  @return   CPL_ERROR_NONE or the relevant _cpl_error_code_ on error
  @see irplib_paf_dump_string

*/
static cpl_error_code irplib_paf_dump_double( char *key, double value,
					  const char *comment, FILE *paf )
{
  cpl_ensure_code(paf,   CPL_ERROR_NULL_INPUT);
  cpl_ensure_code(key,   CPL_ERROR_NULL_INPUT);

  if (comment == NULL)
    cpl_ensure_code(fprintf(paf, PAF_KEY_FORMAT "%.10g\n",
			    key, value) > PAF_KEY_LEN,
		    CPL_ERROR_FILE_IO);
  else
    cpl_ensure_code(fprintf(paf, PAF_KEY_FORMAT "%.10g ; # %s\n",
			    key, value, comment) > PAF_KEY_LEN,
		    CPL_ERROR_FILE_IO);

  return CPL_ERROR_NONE;
}

/**
  @brief    Print a string-property as PAF
  @param    key      Property key
  @param    value    Property value
  @param    comment  Optional property comment
  @param    paf      PAF stream
  @return   CPL_ERROR_NONE or the relevant _cpl_error_code_ on error

  Possible _cpl_error_code_ set in this function:
  - CPL_ERROR_NULL_INPUT if a non-optional input pointer is NULL
  - CPL_ERROR_FILE_IO if fprintf() fails
 */
static cpl_error_code irplib_paf_dump_string( char *key, const char * value,
					   const char *comment, FILE *paf )
{
  cpl_ensure_code(paf,   CPL_ERROR_NULL_INPUT);
  cpl_ensure_code(key,   CPL_ERROR_NULL_INPUT);
  cpl_ensure_code(value, CPL_ERROR_NULL_INPUT);

  if (comment == NULL)
    cpl_ensure_code(fprintf(paf, PAF_KEY_FORMAT "\"%s\"\n",
			    key, value) > PAF_KEY_LEN,
		    CPL_ERROR_FILE_IO);
  else
    cpl_ensure_code(fprintf(paf, PAF_KEY_FORMAT "\"%s\" ; # %s\n",
			    key, value, comment) > PAF_KEY_LEN,
		    CPL_ERROR_FILE_IO);

  return CPL_ERROR_NONE;
}


/**@}*/
