/*===========================================================================
  Copyright (C) 1995-2009 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 Massachusetts Ave, Cambridge, 
  MA 02139, USA.
 
  Correspondence 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
===========================================================================*/

#include <stdio.h>
#include <gl_defs.h>
#include <xm_defs.h>
#include <midas_def.h>

#define MAXROWS		300
#define MAXIMAGE	80
#define MAXAIRM		20
#define DEFAULT_AIRM	1
#define NAMELEN		20
#define IDENTLEN	40


extern void GetNameInputCatalog(),  DropTrailingBlanks();
extern int  file_exists(), AppendDialogText();

void UpdateAirmass(); 
int ExistDescriptor(), ExistAirmass();


static Widget NameForm, ValueForm;
static int ItemsForm;

/**************************************************************************
  FillAirmassForm(): fill the text form with :
     - name & ident of each image of the input catalog in one text widget
       (read/only).
     - airmass value in the other text widget (read/write).
  If the input catalog is invalid, returns FALSE, else TRUE.
*/
int FillAirmassForm( w_name, w_value) 
Widget w_name, w_value;
{
    char incat[MAXLINE];
    char *image_list, *airmass_list;
    char name[MAXLINE], ident[MAXLINE];
    char line[MAXLINE];
    float airmass;
    FILE *fp;
    extern char *XmTextFieldGetString();

    NameForm = w_name;
    ValueForm = w_value;
    ItemsForm = 0;

    GetNameInputCatalog(incat);

    if ( !file_exists(incat, ".cat") )
	return FALSE;

    airmass_list = XtMalloc((unsigned) MAXIMAGE * MAXROWS);
    image_list = XtMalloc((unsigned) MAXAIRM * MAXROWS);
    airmass_list[0] = image_list[0] = '\0';

/* Unfortunately this routine doesn't work. It opens the catalog only once.
   If the catalog is modified before the next call, it doesn't take care of
   it and still gets the old entries. We'll read the catalog by hand.
    SCCGET(incat, 1, name, ident, &entry);
*/

    if ( strstr(incat, ".cat") == NULL )
        strcat(incat, ".cat");

    fp = fopen(incat, "r");
    fgets(line, MAXLINE, fp); /* read comments line */
    while ( fgets(line, MAXLINE, fp) != NULL ) {
        strncpy(name, line, NAMELEN); 
	name[NAMELEN] = '\0';
        strncpy(ident, line+NAMELEN, IDENTLEN); 
	ident[IDENTLEN] = '\0';
        DropTrailingBlanks(name);
    	sprintf(image_list, "%s%s %s\n", image_list, name, ident);
	if ( ExistAirmass(name, &airmass) )
    	    sprintf(airmass_list, "%s%.6f\n", airmass_list, airmass);
	else
    	    sprintf(airmass_list, "%s%d\n", airmass_list, DEFAULT_AIRM);
        ItemsForm++;
    }
    fclose(fp);

    XmTextSetString(w_name, image_list);
    XmTextSetString(w_value, airmass_list);

    XtFree(airmass_list);
    XtFree(image_list);

    return TRUE;
}

void UpdateAirmassValues()
{
    char *name_index, *value_index;
    char *name_list, *value_list;
    char name[MAXLINE], ident[MAXLINE], value[MAXLINE];
    int i;
    float fval;

    name_list = XmTextGetString(NameForm);
    value_list = XmTextGetString(ValueForm);

    name_index = name_list;
    value_index = value_list;
    for ( i = 0; i < ItemsForm; i++ ) {
        sscanf(name_index, "%s%[^\n]", name, ident);
        sscanf(value_index, "%[^\n]", value);
        sscanf(value, "%f", &fval);
	UpdateAirmass(name, fval);
        name_index += strlen(name) + strlen(ident) + 1;
        value_index += strlen(value) + 1;
    }

    XtFree(name_list);
    XtFree(value_list);
}

/*************************************************************************
 MissingAirmassInCatalog(): check if the images of the input catalog have
 the airmass descriptor. Return TRUE if any of them don't have it.
*/
int MissingAirmassInCatalog()
{
    char incat[MAXLINE], name[MAXLINE], line[MAXLINE];
    float airmass;
    FILE *fp;

    GetNameInputCatalog(incat);

    if ( !file_exists(incat, ".cat") )
	return TRUE;

    if ( strstr(incat, ".cat") == NULL )
        strcat(incat, ".cat");

    fp = fopen(incat, "r");
    fgets(line, MAXLINE, fp); /* read comments line */
    while ( fgets(line, MAXLINE, fp) != NULL ) {
        strncpy(name, line, NAMELEN); 
	name[NAMELEN] = '\0';
        DropTrailingBlanks(name);
	if ( !ExistAirmass(name, &airmass) )
    	    return TRUE;
    }
    fclose(fp);

    return FALSE;
}

/****************************************************************
 ReadAirmassValues(): read the airmass values of the image names 
*/
void ReadAirmassValues()
{
}

void UpdateAirmass( image, airmass )
char *image;
float airmass;
{
    char command[MAXLINE];
    float local_airm;
    int unit, id;

    if ( !file_exists(image, ".bdf") )
	return;

    if ( !ExistDescriptor(image, "O_AIRM") ) {
	sprintf(command, "write/desc %s o_airm/r/1/1 %f", image, airmass);
	AppendDialogText(command);
	return;
    }
    SCFOPN(image, D_R4_FORMAT, 0, F_IMA_TYPE, &id);
    local_airm = airmass;
    SCDWRR(id, "O_AIRM", &local_airm, 1, 1, &unit);
    SCFCLO(id);
}

/******************************************************************************
 ExistAirmass(): checks if the descriptor O_AIRM or AIRMASS exists in 'image'.
                 if it exists, returns the value in the variable 'airmass'.
*/

int ExistAirmass( image, airmass )
char *image;
float *airmass;
{
    int retval, nulval; /* useless */
    char descnam[10];
    int unit, id;

    if ( ExistDescriptor(image, "O_AIRM") )
        strcpy(descnam, "O_AIRM");
    else if ( ExistDescriptor(image, "AIRMASS") )
        strcpy(descnam, "AIRMASS");
    else
        return FALSE;

    SCFOPN(image, D_R4_FORMAT, 0, F_IMA_TYPE, &id);
    SCDRDR(id, descnam, 1, 1, &retval, airmass, &unit, &nulval);
    SCFCLO(id);

    return TRUE;
}

/****************************************************************************
 ExistDescriptor(): checks if the descriptor 'desc' exists in 'image'.
*/
int ExistDescriptor( image, desc )
char *image;    /* name of the image */
char *desc;     /* descriptor name */
{
    int retval, nulval, id;
    char type;

    if ( file_exists( image, ".bdf" ) ) {
        SCFOPN( image, D_R4_FORMAT, 0, F_IMA_TYPE, &id );
        SCDFND( id, desc, &type, &retval, &nulval );
        if ( type != ' ' ) {
            SCFCLO(id);
            return(TRUE);
        }
        SCFCLO(id);
    }
    return(FALSE);
}
