/*----------------------------------------------------------------------------
 * 
 * scan_sbe.l -- 
 * 
 * Author          : Jaccard Pierre
 * Created On      : 2000/01/25 14:22:03
 * Last Modified By: Jaccard Pierre
 * Last Modified On: 2000/12/15 12:50:26
 * Directory       : /mnt/local/data/jaccard/codas/2000-11-21/codas3/gfi/src/apps/ctd/
 * ------------------------------------------------------------------------ * 
 * VERSION CONTROL: 
 * 
 *   $Author$
 *   $Date$
 *   $Id$
 *   $Name$
 *   $Revision$
 *   $State$
 *   $Log$
 * 
 *--------------------------------------------------------------------------*/

/**
 * Scan SBE CTD header files and generate standard header files. This
 * programme uses a lexical scanner to determine header fields and their
 * meanings. Configuration for the lexical scanner must be provided in file
 * "scan_sbe.lex",in the working directory. See separate documentation for
 * more information. 
 **/

/* ------------------------------------------------------------------
   Definition section 
   ------------------------------------------------------------------ */

/* The next block will be copied verbatim into the source */
%{

#define HAVE_VFSCANF 1
#define VERSION "Version: $Revision$ $Date$"
#define PRGM    "scan_sbe"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <dirent.h>

 
#define LINE_LENGTH   120                        /* Length of a line  */
#define FIELD_LENGTH   20                        /* Length of a field */
#define EOH           "*END*"                    /* End of header     */
#define HEADER_SUFFIX "hdr"                      /* Header suffix     */
#define DEFAULT_LEX   "scan_sbe.lex"             /* Name of lex-file  */
  
/* Strings with characetrs to exclude from strings */
#define EXCLUDE_FROM_STRING_0 (char*)NULL
#define EXCLUDE_FROM_STRING_1 "§!\"#%&/()=?`|+@£${[]}´^~*'_-:.;,<>"
  
#define BADSHORT     32767                     
#define BADINT       32767                     
#define BADFLOAT     1.0E38                     
#define ADJ_BADFLOAT 1.0E37        /* Adjustment for comparisons with 
                                      bad floats */
 
/* The following defines the codes used in this application. This registered
   in the list code_names will be used for reporting errors  */
#define NO_CODE                0
#define UNKNOWN_CODE           1
#define UNKNOWN_KEYWORD_CODE   2
#define UNKNOWN_RULE_CODE      3
#define UNKNOWN_NAME_CODE      4
#define UNDEFINED_VALUE_CODE   5
#define INVALID_VALUE_CODE     6
/* */
#define OPEN_CODE             10
#define CLOSE_CODE            11
#define READ_CODE             12
#define WRITE_CODE            13
#define SEEK_CODE             14
#define RENAME_CODE           15
/* */
#define STRING_CODE           20
#define INT_CODE              21
#define FLOAT_CODE            22
#define SHORT_CODE            23
#define CHAR_CODE             24
/* */
#define OPTION_CODE           50
#define ARGUMENT_CODE         51
/* */
#define HEADER_OFFSET_CODE   100
#define LATITUDE_CODE        101
#define LONGITUDE_CODE       102
#define DATE_TIME_CODE       103
#define STATION_CODE         104
#define SHIP_CODE            105
#define CRUISE_CODE          106
#define PROJECT_CODE         107
#define AREA_CODE            108
#define BOTTOM_CODE          109
#define VERSION_CODE         110
#define TSN_CODE             111
#define CSN_CODE             112
#define PSN_CODE             113

/* List of the required header fields in the output file */
#define HEADER_FIELDS        LATITUDE_CODE, \
                             LONGITUDE_CODE, \
                             DATE_TIME_CODE, \
                             STATION_CODE, \
                             SHIP_CODE, \
                             CRUISE_CODE, \
                             PROJECT_CODE, \
                             AREA_CODE, \
                             BOTTOM_CODE, \
                             VERSION_CODE, \
                             TSN_CODE, \
                             CSN_CODE, \
                             PSN_CODE
  
/* Used to store a list with codes and their associated names */
 typedef struct
 {
   char *name;
   short code;
 } CODE_NAME_LIST_TYPE;

 typedef struct 
 {
   short degree, minute, second;
 } I_POSITION_TYPE;
 
 typedef struct
 {
   float degree, minute, second;
 } F_POSITION_TYPE;
 
 typedef struct
 {
   char tsn[FIELD_LENGTH], csn[FIELD_LENGTH], psn[FIELD_LENGTH], 
     version[FIELD_LENGTH];
 } SN_TYPE;
 
 typedef struct
 {
   char cruise[FIELD_LENGTH], ship[FIELD_LENGTH], project[FIELD_LENGTH], 
     area[FIELD_LENGTH], station[FIELD_LENGTH];
   int  bottom;
 } MISC_TYPE;
    
 typedef struct
 {
   short year, month, day, hour, minute, second;
 } YMDHMS_TIME_TYPE;
 
 /* Header structure */
 typedef struct 
 {
   I_POSITION_TYPE   ilat, ilon;
   F_POSITION_TYPE   flat, flon;
   YMDHMS_TIME_TYPE  time;
   SN_TYPE           sn;
   MISC_TYPE         misc;
   char              hlat, hlon;
 } HDR_TYPE; 
   
 /* Option structure */
 typedef struct {
   HDR_TYPE *hdr;
   char suffix[FIELD_LENGTH];
 } OPT_TYPE;

 /* Required for opening the input for the lexical analyzer */
 extern FILE *yyin;
    
 /* Global Variables */
 int IERR = 0;             /* Error status     */
 int VERBOSE = 0;          /* Verbose mode     */
 int INTERACTIVE = 0;      /* Interactive mode */

 /* File Variables */
 static HDR_TYPE hdr;              /* Header structure                */
 static FILE *fp_hdr;              /* Pointer to header file          */
 static int lexstat;               /* Current lext status             */
 static int line_num;              /* Current line number in header   */
 static long fpos;                 /* Start of current header field   */
  
  /* Code names. This list is used for reporting warnings and errors. */
  static CODE_NAME_LIST_TYPE code_names[]=
  {
    {"NO CODE"        , NO_CODE},
    {"UNKNOWN CODE"   , UNKNOWN_CODE},
    {"UNKNOWN KEYWORD", UNKNOWN_KEYWORD_CODE},
    {"UNKNOWN RULE"   , UNKNOWN_RULE_CODE},
    {"UNKNOWN NAME"   , UNKNOWN_NAME_CODE},
    {"UNDEFINED VALUE", UNDEFINED_VALUE_CODE},
    {"INVALID VALUE"  , INVALID_VALUE_CODE},
    {"STRING"         , STRING_CODE},
    {"CHAR"           , CHAR_CODE},
    {"INTEGER"        , INT_CODE},
    {"SHORT"          , SHORT_CODE},
    {"FLOAT"          , FLOAT_CODE},
    {"OPTION"         , OPTION_CODE},
    {"ARGUMENT"       , ARGUMENT_CODE},
    {"OPEN"           , OPEN_CODE},
    {"CLOSE"          , CLOSE_CODE},
    {"WRITE"          , WRITE_CODE},
    {"READ"           , READ_CODE},
    {"RENAME"         , RENAME_CODE},
    {"LATITUDE"       , LATITUDE_CODE},
    {"LONGITUDE"      , LONGITUDE_CODE},
    {"DATE TIME"      , DATE_TIME_CODE},
    {"STATION"        , STATION_CODE},
    {"SHIP"           , SHIP_CODE},
    {"CRUISE"         , CRUISE_CODE},
    {"AREA"           , AREA_CODE},
    {"PROJECT"        , PROJECT_CODE},
    {"BOTTOM"         , BOTTOM_CODE},
    {"VERSION"        , VERSION_CODE},
    {"T SENSOR"       , TSN_CODE},
    {"C SENSOR"       , CSN_CODE},
    {"P SENSOR"       , PSN_CODE},
    {(char*) NULL, 0}
  };

  /* Correspondance between month names and their associated number */
  static CODE_NAME_LIST_TYPE month_name_list[]=
  {
    {"Jan",  1},
    {"Feb",  2},
    {"Mar",  3},
    {"Apr",  4},
    {"May",  5},
    {"Jun",  6},
    {"Jul",  7},
    {"Aug",  8},
    {"Sep",  9},
    {"Oct", 10},
    {"Nov", 11},
    {"Dec", 12},
    {(char*)NULL, 0}
  };

  static CODE_NAME_LIST_TYPE scanf_format_list[]=
    {
      {"%hd", SHORT_CODE },
      {"%d" , INT_CODE   },
      {"%c" , CHAR_CODE  },
      {"%f" , FLOAT_CODE },
      {"%s" , STRING_CODE},
      {(char*)NULL, 0}
    };

  /* Required fields in the output file. The list must be terminated with an
     EOF */
  static int field_list[] = { HEADER_FIELDS, EOF };

static int err(int test, int code, char *fmt, ...);
static int warn(int test, int code, char *fmt, ...);
static int get_code_number(int *code, char *name, CODE_NAME_LIST_TYPE *list);
static int read_keyword(int code, char *str, char *fmt, ...);

%}

/* Definition of keywords for the lexical file */
ROL       .*\n
EOL       \n                      
COMMENT   ^[\t ]*#.*\n
EMPTY     ^[\t ]*\n
STRING    [^%#\n]+
KEYWORD   %[A-Za-z0-9_]+%

/* Latitude */
DLATI     %DLATI%
DLATF     %DLATF%
MLATI     %MLATI%
MLATF     %MLATF%
SLATI     %SLATI%
SLATF     %SLATF%
HLATC     %HLATC%

/* Longitude */
DLONI     %DLONI%
DLONF     %DLONF%
MLONI     %MLONI%
MLONF     %MLONF%
SLONI     %SLONI%
SLONF     %SLONF%
HLONC     %HLONC%

/* Sensor serial numbers */
TSN       %TSN%
CSN       %CSN%
PSN       %PSN%
VER       %VERSION%

/* Date and Time */
IYEAR     %IYEAR%
IMONTH    %IMONTH%
CMONTH    %CMONTH%
IDAY      %IDAY%
IHOUR     %IHOUR%
IMINUTE   %IMINUTE%
ISECOND   %ISECOND%

/* Ship, Cruise, ... */
SHIP      %SHIP%
CRUISE    %CRUISE%
BOTTOM    %BOTTOM%
AREA      %AREA%
PROJECT   %PROJECT%
STATION   %STATION%

/* Start conditions */

%x SKIP

%%

%{
   char cbuff[LINE_LENGTH];
   int  ibuff;
%}

{EOL}             { if(lexstat){
                      return(lexstat);
                    }
                  } 
                      
{COMMENT}         { /* Ignored */
                  }

{EMPTY}           { /* Ignored */
                  }

{STRING}          { /* Try to read string from input file */
                    if(err( read_keyword(STRING_CODE, yytext, yytext), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }

                  /* LATITUDE */ 
{DLATI}           { 
                    if(err( read_keyword(LATITUDE_CODE, yytext, 
                                         "%hd", &(hdr.ilat.degree)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{DLATF}           { 
                    if(err( read_keyword(LATITUDE_CODE, yytext, 
                                         "%f", &(hdr.flat.degree)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{MLATI}           { 
                    if(err( read_keyword(LATITUDE_CODE, yytext, 
                                         "%hd", &(hdr.ilat.minute)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{MLATF}           { 
                    if(err( read_keyword(LATITUDE_CODE, yytext, 
                                         "%f", &(hdr.flat.minute)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{SLATI}           { 
                    if(err( read_keyword(LATITUDE_CODE, yytext, 
                                         "%hd", &(hdr.ilat.second)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{SLATF}           { 
                    if(err( read_keyword(LATITUDE_CODE, yytext, 
                                         "%f", &(hdr.flat.second)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{HLATC}           { 
                    if(err( read_keyword(LATITUDE_CODE, yytext, 
                                         "%c", &(hdr.hlat)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }

                  /* LONGITUDE */ 
{DLONI}           { 
                    if(err( read_keyword(LONGITUDE_CODE, yytext, 
                                         "%hd", &(hdr.ilon.degree)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{DLONF}           { 
                    if(err( read_keyword(LONGITUDE_CODE, yytext, 
                                         "%f", &(hdr.flon.degree)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{MLONI}           { 
                    if(err( read_keyword(LONGITUDE_CODE, yytext, 
                                         "%hd", &(hdr.ilon.minute)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{MLONF}           { 
                    if(err( read_keyword(LONGITUDE_CODE, yytext, 
                                         "%f", &(hdr.flon.minute)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{SLONI}           { 
                    if(err( read_keyword(LONGITUDE_CODE, yytext, 
                                         "%hd", &(hdr.ilon.second)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{SLONF}           { 
                    if(err( read_keyword(LONGITUDE_CODE, yytext, 
                                         "%f", &(hdr.flon.second)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{HLONC}           { 
                    if(err( read_keyword(LONGITUDE_CODE, yytext, 
                                         "%c", &(hdr.hlon)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }

                  /* SERIAL NUMBERS */
{TSN}             { 
                    if(err( read_keyword(TSN_CODE, yytext, 
                                         "%F", &(hdr.sn.tsn)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{CSN}             { 
                    if(err( read_keyword(CSN_CODE, yytext, 
                                         "%F", &(hdr.sn.csn)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{PSN}             { 
                    if(err( read_keyword(PSN_CODE, yytext, 
                                         "%F", &(hdr.sn.psn)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{VER}             { 
                    if(err( read_keyword(VERSION_CODE, yytext, 
                                         "%F", &(hdr.sn.version)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }

                  /* DATE and TIME */
{IYEAR}           { 
                    if(err( read_keyword(DATE_TIME_CODE, yytext, 
                                         "%hd", &(hdr.time.year)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{IMONTH}          { 
                    if(err( read_keyword(DATE_TIME_CODE, yytext, 
                                         "%hd", &(hdr.time.month)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{CMONTH}          { 
                    strcpy(cbuff, "");
                    if(err( read_keyword(DATE_TIME_CODE, yytext, 
                                         "%s", &cbuff), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                    else{
                      if(err(get_code_number(&ibuff, cbuff, month_name_list),
                             INVALID_VALUE_CODE, 
                             "Getting code for month %s\n", cbuff))
                        return(IERR);
                      hdr.time.month = (short) ibuff;
                      if(err(IERR, DATE_TIME_CODE, 
                             "Converting month \"cbuff\"\n"))
                        return(IERR);
                    }
                  }
{IDAY}            { 
                    if(err( read_keyword(DATE_TIME_CODE, yytext, 
                                         "%hd", &(hdr.time.day)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{IHOUR}           { 
                    if(err( read_keyword(DATE_TIME_CODE, yytext, 
                                         "%hd", &(hdr.time.hour)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{IMINUTE}         { 
                    if(err( read_keyword(DATE_TIME_CODE, yytext, 
                                         "%hd", &(hdr.time.minute)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }
{ISECOND}         { 
                    if(err( read_keyword(DATE_TIME_CODE, yytext, 
                                         "%hd", &(hdr.time.second)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;
                  }

                  /* SHIP, CRUISE, ... */
{SHIP}            { 
                    if(err( read_keyword(SHIP_CODE, yytext, 
                                         "%F", &(hdr.misc.ship)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;                      
                  }
{CRUISE}          { 
                    if(err( read_keyword(CRUISE_CODE, yytext, 
                                         "%F", &(hdr.misc.cruise)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;                      
                  }
{AREA}            { 
                    if(err( read_keyword(AREA_CODE, yytext, 
                                         "%F", &(hdr.misc.area)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;                      
                  }
{PROJECT}         { 
                    if(err( read_keyword(PROJECT_CODE, yytext, 
                                         "%F", &(hdr.misc.project)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;                      
                  }
{STATION}         { 
                    if(err( read_keyword(STATION_CODE, yytext, 
                                         "%s", &(hdr.misc.station)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;                      
                  }
{BOTTOM}          { 
                    if(err( read_keyword(BOTTOM_CODE, yytext, 
                                         "%d", &(hdr.misc.bottom)), 
                            READ_CODE, 
                            "Reading \"%s\" from header file\n", yytext))
                      return(IERR);
                    if(lexstat == NO_CODE)
                      BEGIN SKIP;                      
                  }


{KEYWORD}         { /* This is an unknown keyword */
                    err(1, UNKNOWN_KEYWORD_CODE, 
                        "Unknown keyword: %s\n", yytext);
                    return(IERR);
                  }

.                 { 
                    err(1, UNKNOWN_RULE_CODE,
                        "Don't know how to handle lexical input \"%s\"\n",
                        yytext);
                    return(IERR);
                  }

<SKIP>{ROL}       { BEGIN INITIAL; }

%%

/* ------------------------------------------------------------------
   Action section 
   ------------------------------------------------------------------ */

/* ------------------------------------------------------------------
  get_code_name - Get the name of a given code

  RETURNS: the given code, or UNKNOWN_CODE if no name is associated to
           the given list.

  WARNINGS: 
     - if no name is associated to the given list.

  ERRORS: none
  ------------------------------------------------------------------ */
static int get_code_name(/* Sting for holding the name */
                         char *name, 
                         /* Code value */
                         int code, 
                         /* Pointer to list with codes and associated names */
                         CODE_NAME_LIST_TYPE *list)
{
  
  CODE_NAME_LIST_TYPE *p;
  
  p = list; 
  while((p->name != (char*)NULL) && (p->code != code)) p++;
  if(warn((p->name == (char*)NULL), UNKNOWN_CODE, 
          "No name associated to code %-d\n", code)){        
    code = get_code_name(name, UNKNOWN_CODE, code_names); 
    return(code);
  }
  strcpy(name, p->name);
  return(code);
}
  
/* ------------------------------------------------------------------
   get_code_number - Get the number of the given name

   RETURNS: EOF if no code can be found

   WARNINGS: none 
      
   ERRORS: none
   ------------------------------------------------------------------ */
static int get_code_number(int *code, char *name, CODE_NAME_LIST_TYPE *list){
  
  CODE_NAME_LIST_TYPE *p;
  
  p = list;
  while((p->name != (char*)NULL) && strcmp(p->name, name) != 0) p++;
  if(p->name == (char*)NULL)
    return(EOF);
  *code = p->code;
  return(0);
}

/* ------------------------------------------------------------------
   warn - Write a warning message to stderr

   This function uses the list "code_names" for printing the name of
   the given code.
   
   Set the format string to (char *)NULL to avoid a message.

   RETURNS: Zero if the test does not evaluate to true, or the given code, or
            UNKNOWN_CODE if no name is associated to it.

   WARNINGS: none

   ERRORS: none
   ------------------------------------------------------------------ */
static int warn(/* Test to evaluate. If true, a warning message is 
                   generated.*/
                   int test, 
                   /* Code for the warning message */
                   int code, 
                   /* Format string for warning message */
                   char *fmt, 
                   /* Arguments assiciated to the format string */
                   ...)
{
  
  char name[LINE_LENGTH];
  va_list ap;
  
  if(test){
    if(fmt){
      code = get_code_name(name, code, code_names);
      fprintf(stderr, "\n!!! WARNING %-d: %s\n", code, name);
      va_start(ap, fmt);
      vfprintf(stderr, fmt, ap);
      va_end(ap);
      fflush(stderr);
    }
    return(code);
  }
  return(0);
}

/* ------------------------------------------------------------------
   err - Output an error message and set IERR

   This function uses the list "code_names" for printing the name of
   the given code. The error code is defined by the result of the test, or by
   the given code if non-zero. Global variable IERR is set to this value.
   
   Set the format string to (char *)NULL to avoid a message.

   RETURNS: Zero if the test does not evaluate to true, or the given code, or
            UNKNOWN_CODE if no name is associated to it.

   WARNINGS: none

   ERRORS: none
   ------------------------------------------------------------------ */
static int err(/* Test to evaluate. An error is reported if it evaluates to
                  true */
               int test, 
               /* Code value corresponding to the error */
               int code, 
               /* Format string for the message */
               char *fmt, 
               /* Arguments associated to the format string */
               ...)
{
  
  char name[LINE_LENGTH];
  va_list ap;
  
  if(test){
    if(!code) code = test;
    if(fmt){
      code = get_code_name(name, code, code_names);
      fprintf(stderr, "\n!!! ERROR %-d: %s\n", code, name);
      va_start(ap, fmt);
      vfprintf(stderr, fmt, ap);
      va_end(ap);
      fflush(stderr);
    }
    IERR = code;
    return(code);
  }
  return(0);
}
 
/* ------------------------------------------------------------------
   strtrim - Trim leading and trailing spaces
   
   RETURNS: Zero
   
   WARNINGS: none

   ERRORS: none
   ------------------------------------------------------------------ */
int strtrim(char *s)
{

  int i, j, i0, i1;

  i0 = 0;
  i1 = strlen(s);

  /* Reamove leading spaces */
  i = i0;
  while((i < i1) && isspace(s[i])) i++;
  i0 = i;
  
  /* Remove trailing spaces */
  i = i1-1;
  while((i > i0) && isspace(s[i])) i--;
  i1 = i;

  /* Create copy of trimmed string */
  j = 0;
  for(i=i0; i<=i1; i++)
    s[j++] = s[i];
  s[j] = '\0';
  
  return(0);
}
     
/* ------------------------------------------------------------------
   read_keyword - Read the value associated to a keyword

   This function is used for reading the different fields in the header file.
   It is called by the lexical analyzer.

   This function uses file pointer to header file "fp_hdr". If successful,
   variable "lexstat" is set to the given code, or NO_CODE if failure.
   Currently, only one value can be read.

   Strings with code STRING_CODE are treated differently. The format string
   must contain the whole string to macth. A substring of the same length (but
   less than LINE_LENGTH) is read from the file and compared to the given
   format. This code is used to determine if the current header line
   corresponds to the given field name.

   A special format string is %F, for reading a field content as a string
   containing white spaces. A substring of length FIELD_LENGTH, but not
   extending the current line is read and returned in the given argument.

   RETURNS: error code IERR

   WARNINGS: none

   ERRORS: 
      - SEEK_CODE if it cannot seek back in the input file
   ------------------------------------------------------------------ */
static int read_keyword(/* Code correspinding to data to be read */
                        int code, 
                        /* Current buffer of data from the lexical analyzer.
                           This is the same as yytext */
                        char *str, 
                        /* Format string for reading the data */
                        char *fmt, 
                        /* Arguments associated to the format string */
                        ...)
{
  
  va_list ap;
  char cbuff[LINE_LENGTH], *c;
  long cpos;
  int n;
  
#if (HAVE_VFSCANF != 1)
  CODE_NAME_LIST_TYPE *p;
  char  last_c;
  char  *cptr;
  int   *iptr;
  float *fptr;
#endif

  /* Try to read header file according to the format */    
  if(VERBOSE)
    fprintf(stderr, "Now trying: %s ... ", str); 
  if(code == STRING_CODE){
    fgets(cbuff, strlen(fmt)+1, fp_hdr);
    n = strcmp(cbuff, fmt) ? 0 : 1;
  }
  else if(strcmp(fmt, "%F") == 0){
    n = 0;
    cpos = ftell(fp_hdr);
    if(fgets(cbuff, FIELD_LENGTH, fp_hdr)){
      /* Trim spaces */
      strtrim(cbuff);
      /* Copy string into argument */
      va_start(ap, fmt);
      c = (char *) va_arg(ap, char *);
      strcpy(c, cbuff);
      va_end(ap);
      n = 1;
    }
  }
  else{
#if (HAVE_VFSCANF == 1)    
    va_start(ap, fmt);
    n = vfscanf(fp_hdr, fmt, ap);
    va_end(ap);
#else
    /*
     * Get code for format
     */
    p = scanf_format_list;
    while((p->code != 0) && (strcmp(p->name, fmt) != 0))
      p++;
    if(p->code == 0)
      return( err(READ_CODE, code, 
                  "\n!!!ERROR: no code associated to format string \"%s\"\n",
                  fmt));
    /*
     * We've got a code for this format
     */
    va_start(ap, fmt);
    switch(p->code)
    {
      case INT_CODE:
        iptr = (int *) va_arg(ap, int *);
        n = fscanf(fp_hdr, "%d", iptr);
        break;
      case SHORT_CODE:
        iptr = (int *) va_arg(ap, int *);
        n = fscanf(fp_hdr, "%hd", (short *) iptr);
        break;
      case FLOAT_CODE:
        fptr = (float *) va_arg(ap, float *);
        n = fscanf(fp_hdr, "%f", fptr);
        break;
      case CHAR_CODE:
        cptr = (char *) va_arg(ap, char *);
        n = fscanf(fp_hdr, "%c", cptr);
        break;
      case STRING_CODE:
        cptr = (char *) va_arg(ap, char *);
        n = fscanf(fp_hdr, "%s", cptr);
        break;
      default:
        err(1, READ_CODE, "Reading input format \"%s\"\n", fmt);
        n = 0;
        break;
    }
    va_end(ap);
#endif /* HAVE_VFSCANF */
  
  }
  
  /* Success */
  if(n == 1){
    lexstat = code;
    if(VERBOSE)
      fprintf(stderr, "success\n");
    return(0);
  }
  
  /* Failure */
  if(VERBOSE)
    fprintf(stderr, "failure\n");
  get_code_name(cbuff, code, code_names);
  if(err( fseek(fp_hdr, fpos, SEEK_SET), SEEK_CODE,
          "Seeking header file at line %-d:\n%s%-d\n%s%s\n%s%s\n", line_num,
          "   current code     : ", cbuff,
          "   current lex input: ", str)) 
    return(IERR);
  lexstat = NO_CODE;
  return(0);
}

/* ------------------------------------------------------------------
   init_header - Initialize the header structure

   All data are set to their associated bad values, except for strings which
   are set to the empty string. On request, the structure can be initialized
   with coded default values.
   
   RETURNS: 0

   WARNINGS: none

   ERRORS: none
   ------------------------------------------------------------------ */
int init_header(/* Pointer to header structure */
                HDR_TYPE *hdr, 
                /* If default values should be initialized */
                int def)
{

  static int header_fields[] = { HEADER_FIELDS, EOF };
  int i;

  /* */
  hdr->ilat.degree = BADSHORT;
  hdr->ilat.minute = BADSHORT;
  hdr->ilat.second = BADSHORT;
  /* */
  hdr->ilon.degree = BADSHORT;
  hdr->ilon.minute = BADSHORT;
  hdr->ilon.second = BADSHORT;
  /* */
  hdr->flat.degree = BADFLOAT;
  hdr->flat.minute = BADFLOAT;
  hdr->flat.second = BADFLOAT;
  /* */
  hdr->flon.degree = BADFLOAT;
  hdr->flon.minute = BADFLOAT;
  hdr->flon.second = BADFLOAT;
  /* */
  hdr->time.year   = BADSHORT;
  hdr->time.month  = BADSHORT;
  hdr->time.day    = BADSHORT;
  hdr->time.hour   = BADSHORT;
  hdr->time.minute = BADSHORT;
  hdr->time.second = BADSHORT;
  /* */
  hdr->hlat = hdr->hlon = '\0';
  /* */
  hdr->sn.tsn[0] = hdr->sn.csn[0] = hdr->sn.psn[0] = 
    hdr->sn.version[0] = '\0';
  /* */
  hdr->misc.ship[0] = hdr->misc.project[0] = hdr->misc.area[0] = 
    hdr->misc.cruise[0] = hdr->misc.station[0] = '\0';
  /* */
  hdr->misc.bottom = BADINT;

  if(def){
    strcpy(hdr->sn.tsn,       "UNKNOWN"); 
    strcpy(hdr->sn.csn,       "UNKNOWN"); 
    strcpy(hdr->sn.psn,       "UNKNOWN"); 
    strcpy(hdr->sn.version,   "UNKNOWN");
    strcpy(hdr->misc.area,    "UNKNOWN"); 
  }

  /*
   * Initialize the list of required header fields
   */
  i = 0;
  while(header_fields[i] != EOF){
    field_list[i] = header_fields[i];
    i++;
  }

  return(0);
}
     
/* ------------------------------------------------------------------
   check_string - Check a string

   Checks if the string is defined. On demand, special characters can be
   removed and all characters set to upper case.

   The length of the string must not exceed LINE_LENGTH.

   RETURNS:
      - Zero on success
      - UNDEFINED_VALUE_CODE if the string is empty
      
   WARNINGS: none

   ERRORS: none
   ------------------------------------------------------------------ */
int check_string(/* String to check */
                 char *str,
                 /* String of characters to be removed. Set it to NULL if all
                    characters should be kept */
                 char *excl,
                 /* If characters should be set to upper case */
                 int uc)
{

  
  char cbuff[LINE_LENGTH];
  int  i, j, k;

  /* Check if the string is defined */
  if(!strlen(str))
    return(UNDEFINED_VALUE_CODE);

  /* Trim string */
  strtrim(str);

  /* Remove all special characters */
  if(excl){
    for(i=0; i<strlen(excl); i++){
      strcpy(cbuff, str);
      k = 0;
      for(j=0; j<strlen(cbuff); j++){
        if(cbuff[j] != excl[i])
          str[k++] = cbuff[j];
      }
      str[k] = '\0';
    }
  }
   
  /* Set characters to upper case */
  if(uc){
    for(i=0; i<strlen(str); i++)
      str[i] = toupper(str[i]);
  }

  /* Check if the string is still defined */
  if(!strlen(str))
    return(UNDEFINED_VALUE_CODE);

  return(0);
}
  
/* ------------------------------------------------------------------
   check_ival - Check integer value

   Checks if the given value is not bad, or within a certain range (inclusive
   the lower boundary, exclusive the upper).
   
   RETURNS: Zero if successful, UNDEFINED_VALUE_CODE for bad data, or
            INVALID_VALUE_CODE if not within the given range.
            
   WARNINGS: none

   ERRORS: none
   ------------------------------------------------------------------ */
int check_ival(/* Value to check */
               int value, 
               /* Minimal value allowed */
               int min, 
               /* Maximal value allowed */
               int max)
{

  if(value == BADINT) 
    return(UNDEFINED_VALUE_CODE);  
  if((value < min) || (value >= max))
    return(INVALID_VALUE_CODE);
  return(0);
}

/* ------------------------------------------------------------------
   check_fval - Check float value

   Checks if the given value is not bad, or within a certain range (inclusive
   the lower boundary, exclusive the upper).

   RETURNS: Zero if successful, UNDEFINED_VALUE_CODE for bad data, or
            INVALID_VALUE_CODE if not within the given range.
            
   WARNINGS: none

   ERRORS: none
   ------------------------------------------------------------------ */
int check_fval(/* Value to check */
               float value, 
               /* Minimal value allowed */
               float min, 
               /* Maximal value alloed */
               float max)
{
  
  if(value > ADJ_BADFLOAT)
    return(UNDEFINED_VALUE_CODE);
  if((value < min) || (value >= max))
    return(INVALID_VALUE_CODE);
  return(0);
}

/* ------------------------------------------------------------------
   check_position_field - Check the value of a position field

   Check and determine the value of the given position field (i.e. degree,
   minute or second). It first tries to read the field from the integer
   holder. If successful, it looks if a decimal value is available in the
   float holder, in which case this must be less than one (i.e. only the
   decimal part). If no integer value is available, it tries to get the value
   from the float holder.

   The final value is checked according to the given range. See functions
   check_ival() and check_fval() for more information.

   On output, the integer or float holder is updated with the value, the other 
   one being set to bad.

   RETURNS: 
      - UNDEFINED_VALUE_CODE if both holders are set to bad
      - INVALID_VALUE_CODE if no valid data is found, or too much data is
        available
      - INT_CODE if successful and the position field is an integer
      - FLOAT_CODE if successful and the position field is a float

   WARNINGS: none
   
   ERRORS: none

   2000/12/14 PJ
              Modified so that if one has an integer *AND* a float value,
              the float value is divided by hundred. and added to the integer
              value. This allows reading of floats with comma as decimal
              point. 
   ------------------------------------------------------------------ */
int check_position_field(/* Pointer to integer holder */
                         short *ival, 
                         /* Pointer to float holder */
                         float *fval, 
                         /* Minimal allowed value */
                         float min, 
                         /* Maximal allowed value */
                         float max)
{
 
  float fpos = BADFLOAT;
  short ipos = BADSHORT;
  int code;
 
  /* Check if an integer value is defined */
  if(*ival != BADSHORT){
    /* A decimal value is allowed, but only the decimals */
    if(*fval < ADJ_BADFLOAT){
      if(*fval < 1.0){
        /* 2000/12/14 PJ
         *
         * fpos = (float) (ipos) + fpos;
         */
        fpos = (float) (ipos) + fpos/100.0;
        code = FLOAT_CODE;
      }
      else
        code = INVALID_VALUE_CODE;
    }
    else{
      ipos = *ival;
      code = INT_CODE;
    }
  }
  /* Check for a defined float value */
  else if(*fval < ADJ_BADFLOAT){
    fpos = *fval;
    code = FLOAT_CODE;
  }
  else
    code = UNDEFINED_VALUE_CODE;

  /* Check the value and updates the holder */
  switch(code)
    {
    case INT_CODE:
      if(check_ival((int)ipos, floor(min), ceil(max)))
        code = INVALID_VALUE_CODE;
      else{
        *ival = ipos;
        *fval = BADFLOAT;
      }
      break;
    case FLOAT_CODE:
      if(check_fval(fpos, min, max))
        code = INVALID_VALUE_CODE;
      else{
        *ival = BADSHORT;
        *fval = fpos;
      }
      break;
    default:
      break;
    }

  return(code);
}
      
/* ------------------------------------------------------------------
   check_position - Check a position

   Check and determine position value from the integer and float holders.
   Individual fields are processed by function check_position_field() (i.e.
   degree, minute and second). If a parent field is found to be a float, its
   children are ignored. For example, minute and second are ignored if degree
   are decimal and second is ignored if minute is decimal.

   The calculated position is checked against a given range by functions
   check_ival() and check_fval().

   On output, both holders are updated with the given position. Hemisphere
   sign is not checked.
   

   RETURNS: 
      - Zero on success
      - UNDEFINED_VALUE_CODE if a required position field is not defined
      - INVALID_VALUE_CODE 
           - if a required field does not contain valid data
           - if the processed position is not valid
      - UNKNOWN_CODE if function check_position_field() does not return
        an expected value. This should not happen.

    WARNINGS: if a default value from the command line should be used.

    ERRORS: lots of them if position cannot be processed correctly.
   ------------------------------------------------------------------ */
int check_position(/* Code associated to position structure */
                   int code, 
                   /* Pointer to structure of integer holders */
                   I_POSITION_TYPE *ipos, 
                   /* Pointer to structure of float holders */
                   F_POSITION_TYPE *fpos,
                   /* Minimal value allowed */
                   float min, 
                   /* Maximal value allowed */
                   float max)
{
  
  char  cbuff[LINE_LENGTH];
  float pos;
  int   status;

  /* Check degree */
  status = check_position_field(&(ipos->degree), &(fpos->degree), min, max);
  switch(status)
    {
    case UNDEFINED_VALUE_CODE:
      err(1, code, "Undefined value for degree\n");
      return(status);
      break;
    case INVALID_VALUE_CODE:
      err(1, code, "Invalid value for degree\n%s%-d\n%s%12.6f\n",
          "   i-degree: ", ipos->degree,
          "   f-degree: ", fpos->degree);
      return(status);
      break;
    case INT_CODE:
      pos = (float) ipos->degree;
      break;
    case FLOAT_CODE:
      pos = fpos->degree;
      break;
    default:
      get_code_name(cbuff, status, code_names);
      err(1, code, 
          "Invalid value status for degree:\n%s%-d\n%s%s\n",
          "   value: ", status,
          "   name : ", cbuff);
      return(UNKNOWN_CODE);
    }
 
  /* Check for minutes */
  if(status == INT_CODE){
    status = check_position_field(&(ipos->minute), &(fpos->minute), 0.0, 60.0);
    switch(status)
      {
      case UNDEFINED_VALUE_CODE:
        err(1, code, "Undefined value for minute\n");
        return(status);
        break;
      case INVALID_VALUE_CODE:
        err(1, code, "Invalid value for minute\n%s%-d\n%s%12.6f\n",
            "   i-degree: ", ipos->minute,
            "   f-degree: ", fpos->minute);
        return(status);
        break;
      case INT_CODE:
        pos += ((float) ipos->minute)/60.0;
        break;
      case FLOAT_CODE:
        pos += fpos->minute/60.0;
        break;
      default:
        get_code_name(cbuff, status, code_names);
        err(1, code, 
            "Invalid value status for minute\n%s%-d\n%s%s\n",
            "   value: ", status,
            "   name : ", cbuff);
        return(UNKNOWN_CODE);
      }
  }
  
  /* Check for seconds */
  if(status == INT_CODE){
    status = check_position_field(&(ipos->second), &(fpos->second), 0.0, 60.0);
    switch(status)
      {
      case UNDEFINED_VALUE_CODE:
        err(1, code, "Undefined value for second\n");
        return(status);
        break;
      case INVALID_VALUE_CODE:
        err(1, code, "Invalid value for second\n%s%-d\n%s%12.6f\n",
            "   i-degree: ", ipos->second,
            "   f-degree: ", fpos->second);
        return(status);
        break;
      case INT_CODE:
        pos += ((float) ipos->second)/3600.0;
        break;
      case FLOAT_CODE:
        pos += fpos->second/3600.0;
        break;
      default:
        get_code_name(cbuff, status, code_names);
        err(1, code, 
            "Invalid value status for second:\n%s%-d\n%s%s\n",
            "   value: ", status,
            "   name : ", cbuff);
        return(UNKNOWN_CODE);
      }
  }

  /* Check position value */
  if(err( check_fval(pos, min, max), code, 
          "Invalid position: %12.6f\n", pos))
    return(INVALID_VALUE_CODE);
  
  /* Update the holders */
  fpos->degree = pos;
  ipos->degree = (short)fpos->degree;
  fpos->minute = (fpos->degree - (float)ipos->degree) * 60.0;
  ipos->minute = (short)fpos->minute;
  fpos->second = (fpos->minute - (float)ipos->minute) * 60.0;
  ipos->second = (short)fpos->second;
    
  return(0);
}
        
/* ------------------------------------------------------------------
   check_header - Check values from the header

   Check and process values from the elements in the header structure. If
   given values are undefined or invalid, it will try to take those from the
   default structure.

   Hemisphere are checked and set to upper case.

   RETURNS: Zero if sucessfull, or an error code if the given value is
            undefined or invalid.

   WARNINGS: whenever a default value has to be used.

   ERRORS: lots of them if something goes wrong.
   ------------------------------------------------------------------ */
int check_header(/* Code corresponding to the elements that should be
                    processed */
                 int code, 
                 /* Pointer to the header structure */
                 HDR_TYPE *hdr,
                 /* Pointer to default values */
                 HDR_TYPE *def)
{

  char cbuff[LINE_LENGTH];
  char hemi;
  YMDHMS_TIME_TYPE *t;
  MISC_TYPE        *m;
  SN_TYPE          *sn;
  
  /* Initializations */
  t  = &(hdr->time);
  m  = &(hdr->misc);
  sn = &(hdr->sn);
  get_code_name(cbuff, code, code_names);

  switch(code)
    {
    case LATITUDE_CODE:
      IERR = check_position(code, &(hdr->ilat), &(hdr->flat), 0.0, 90.0);
      if(err( IERR, IERR, "Processing %s\n", cbuff))
        return(IERR);
      /* Check the hemisphere */
      hemi = hdr->hlat;
      hemi = toupper(hemi);
      if((hemi != 'N') && (hemi != 'S')){
        hemi = def->hlat;
        hemi = toupper(hemi);
        warn(1, code, "%s%c\n%s%c\n",
             "   Invalid hemisphere   : ", hdr->hlat,
             "   Using default instead: ", hemi);
      }
      if(err( (hemi != 'N') && (hemi != 'S'), code,
              "Invalid hemisphere %c\n", hemi))
        return(INVALID_VALUE_CODE);
      hdr->hlat = hemi;
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %02hd %7.4f %c\n", cbuff,
                hdr->ilat.degree, hdr->flat.minute, hdr->hlat);
      }
      break;
    case LONGITUDE_CODE:
      IERR = check_position(code, &(hdr->ilon), &(hdr->flon), 0.0, 360.0);
      if(err( IERR, 0, "Processing %s\n", cbuff))
        return(IERR);
      /* Check the hemisphere */
      hemi = hdr->hlon;
      hemi = toupper(hemi);
      if((hemi != 'W') && (hemi != 'E')){
        hemi = def->hlon;
        hemi = toupper(hemi);      
        warn(1, code, "%s%c\n%s%c\n",
             "   Invalid hemisphere   : ", hdr->hlon,
             "   Using default instead: ", hemi);
      }
      if(err( (hemi != 'W') && (hemi != 'E'), code,
              "Invalid hemisphere %c\n", hemi))
        return(INVALID_VALUE_CODE);
      hdr->hlon = hemi;
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %03hd %7.4f %c\n", cbuff,
                hdr->ilon.degree, hdr->flon.minute, hdr->hlon);
      }
      break;
    case DATE_TIME_CODE:
      /* Check year */
      if(t->year == BADSHORT){
        t->year = def->time.year;
        warn(1, code, "Using default value for year: %-d\n", t->year);
      }
      if(t->year < 1900) t->year += 1900;
      if(t->year < 1970) t->year += 100;
      if( err( check_ival((int)t->year, 1970, (int)BADSHORT), 0,
               "Checking value for year: %-d\n", t->year))
        return(IERR);      
      /* Check month */
      if( err( check_ival((int)t->month, 1, 13), 0,
               "Checking value for month: %-d\n", t->month))
        return(IERR);
      /* Check day */
      if( err( check_ival((int)t->day, 1, 32), 0,
               "Checking value for day: %-d\n", t->day))
        return(IERR);
      /* Check hour */
      if( err( check_ival((int)t->hour, 0, 24), 0,
               "Checking value for hour: %-d\n", t->hour))
        return(IERR);
      /* Check minute */
      if( err( check_ival((int)t->minute, 0, 60), 0,
               "Checking value for minute: %-d\n", t->minute))
        return(IERR);
      /* Check second */
      if( check_ival((int)t->second, 0, 60) )
        t->second = 0;
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %04hd/%02hd/%02hd %02hd:%02hd:%02hd\n",
                cbuff, t->year, t->month, t->day, 
                t->hour, t->minute, t->second);
      }
      break;
    case BOTTOM_CODE:
      if( err( check_ival(m->bottom, 0, 10000), 0,
               "Checking value for %s: %-d\n", cbuff, m->bottom))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %-d\n", cbuff, m->bottom);
      }
      break;
    case SHIP_CODE:
      if(check_string(m->ship, EXCLUDE_FROM_STRING_1, 1)){
        strcpy(m->ship, def->misc.ship);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(m->ship, EXCLUDE_FROM_STRING_1, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, m->ship);
      }
      break;
    case CRUISE_CODE:
      if(check_string(m->cruise, EXCLUDE_FROM_STRING_1, 1)){
        strcpy(m->cruise, def->misc.cruise);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(m->cruise, EXCLUDE_FROM_STRING_1, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, m->cruise);
      }
      break;
      break;
    case STATION_CODE:
      if(check_string(m->station, EXCLUDE_FROM_STRING_1, 1)){
        strcpy(m->station, def->misc.station);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(m->station, EXCLUDE_FROM_STRING_1, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, m->station);
      }
      break;
      break;
    case AREA_CODE:
      if(check_string(m->area, EXCLUDE_FROM_STRING_1, 1)){
        strcpy(m->area, def->misc.area);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(m->area, EXCLUDE_FROM_STRING_1, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, m->area);
      }
      break;
      break;
    case PROJECT_CODE:
      if(check_string(m->project, EXCLUDE_FROM_STRING_1, 1)){
        strcpy(m->project, def->misc.project);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(m->project, EXCLUDE_FROM_STRING_1, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, m->project);
      }
      break;
      break;
    case TSN_CODE:
      if(check_string(sn->tsn, EXCLUDE_FROM_STRING_0, 1)){
        strcpy(sn->tsn, def->sn.tsn);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(sn->tsn, EXCLUDE_FROM_STRING_0, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, sn->tsn);
      }
      break;
      break;
    case CSN_CODE:
      if(check_string(sn->csn, EXCLUDE_FROM_STRING_0, 1)){
        strcpy(sn->csn, def->sn.csn);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(sn->csn, EXCLUDE_FROM_STRING_0, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, sn->csn);
      }
      break;
    case PSN_CODE:
      if(check_string(sn->psn, EXCLUDE_FROM_STRING_0, 1)){
        strcpy(sn->psn, def->sn.psn);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(sn->psn, EXCLUDE_FROM_STRING_0, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: %s\n", cbuff, sn->psn);
      }
      break;
    case VERSION_CODE:
      if(check_string(sn->version, EXCLUDE_FROM_STRING_0, 1)){
        strcpy(sn->version, def->sn.version);
        warn(1, code, "Undefined string. Using default instead\n");
      }
      if( err( check_string(sn->version, EXCLUDE_FROM_STRING_0, 1),
               0, "Checking value for %s\n", cbuff))
        return(IERR);
      if(VERBOSE){
        fprintf(stderr, "   Checked %s: [%s]\n", cbuff, sn->version);
      }
      break;
    case NO_CODE:
      return(0);
      break;
    default:
      err(1, code, "Invalid code\n");
      return(IERR);
    }

  return(0);
}

/* ------------------------------------------------------------------
   write_header - Write the new header

   Write to the output file the header line corresponding to the given code.
   If this is NO_CODE, the current header line is considered as unrequired and 
   is copied as is from the input to the output file. In this case, string
   line must contain the input header line. If the code is UNKNOWN_CODE, the
   function looks through the list of required header lines for those which
   have not been written yet and append them to the end of the output file.
   This is usefull for inserting header lines which are not present in the
   input file.

   On output, the list of required header lines is updated.

   RETURNS: Zero on success or an error code.

   WARNINGS: none

   ERRORS: if an error is raised
   ------------------------------------------------------------------ */
int write_header(/* Pointer to output file */
                 FILE *fp, 
                 /* Code of current header item */
                 int code, 
                 /* Pointer to header structure */
                 HDR_TYPE *hdr, 
                 /* Pointer to current header line */
                 char *line, 
                 /* Pointer to default header values */
                 HDR_TYPE *def)
{

  char cbuff[LINE_LENGTH];
  int i;

  if(code == UNKNOWN_CODE){
    /* Loop through missing lines */
    i = 0;
    while( field_list[i] != EOF ){
      /* Check for missing field */
      if(field_list[i]){
        code = field_list[i];
        get_code_name(cbuff, code, code_names);
        if(VERBOSE)
          fprintf(stderr, "Appending data for %s\n", cbuff); 
        if(err( check_header(code, hdr, def), IERR,
                "Checking field for %s\n", cbuff))
          return(IERR);
        if(err( write_header(fp, code, hdr, (char*)NULL, def), IERR,
                "Writing field for %s\n", cbuff))
          return(IERR);
      }
      i++;
    }
    /* Write the end of header */
    if(VERBOSE)
      fprintf(stderr, "Adding end of header: %s\n", EOH);
    fprintf(fp, "%s\n", EOH);
    return(0);
  }

  i = code - HEADER_OFFSET_CODE - 1;
  switch(code)
    {
    case LATITUDE_CODE:
      fprintf(fp, "* Latitude = %02hd %06.4f %c\n", 
              hdr->ilat.degree, hdr->flat.minute, hdr->hlat);
      field_list[i] = 0;
      break;
    case LONGITUDE_CODE:
      fprintf(fp, "* Longitude = %03hd %06.4f %c\n", 
              hdr->ilon.degree, hdr->flon.minute, hdr->hlon);
      field_list[i] = 0;
      break;
    case DATE_TIME_CODE:
      fprintf(fp, "* Time = %04hd/%02hd/%02hd %02hd:%02hd:%02hd\n",
              hdr->time.year, hdr->time.month, hdr->time.day,
              hdr->time.hour, hdr->time.minute, hdr->time.second);
      field_list[i] = 0;
      break;
    case BOTTOM_CODE:
      fprintf(fp, "* Depth = %-d\n", hdr->misc.bottom);
      field_list[i] = 0;
      break;
    case SHIP_CODE:
      fprintf(fp, "* Ship = %s\n", hdr->misc.ship);
      field_list[i] = 0;
      break;
    case CRUISE_CODE:
      fprintf(fp, "* Cruise = %s\n", hdr->misc.cruise);
      field_list[i] = 0;
      break;
    case STATION_CODE:
      fprintf(fp, "* Station = %s\n", hdr->misc.station);
      field_list[i] = 0;
      break;
    case AREA_CODE:
      fprintf(fp, "* Area = %s\n", hdr->misc.area);
      field_list[i] = 0;
      break;
    case PROJECT_CODE:
      fprintf(fp, "* Project = %s\n", hdr->misc.project);
      field_list[i] = 0;
      break;
    case TSN_CODE:
      fprintf(fp, "* Temperature SN = %s\n", hdr->sn.tsn);
      field_list[i] = 0;
      break;
    case CSN_CODE:
      fprintf(fp, "* Conductivity SN = %s\n", hdr->sn.csn);
      field_list[i] = 0;
      break;
    case PSN_CODE:
      fprintf(fp, "* Pressure SN = %s\n", hdr->sn.psn);
      field_list[i] = 0;
      break;
    case VERSION_CODE:
      fprintf(fp, "* SBE Software Version = %s\n", hdr->sn.version);
      field_list[i] = 0;
      break;
    case NO_CODE:
      if(line)
        fprintf(fp, "%s", line);
      break;
    }
  return(0);
}

/* ------------------------------------------------------------------
   print_usage - Print usage information
   
   RETURNS: Zero
   ------------------------------------------------------------------ */
int print_usage(void)
{

  fprintf(stderr, "

   %s - %s

   USAGE name [options]

   OPTIONS:
      -C <CSN>
      -E
      -N
      -P <PSN>
      -S
      -T <TSN>
      -V
      -W
      -a <area>
      -c <cruise>
      -h
      -i 
      -p <project>
      -s <ship>
      -y <year>

", PRGM, VERSION);

  return(0);
}

/* ------------------------------------------------------------------
   parse_options - Parse command line options

   RETURNS: The number of arguments parsed as options. If it fails, the
            function exists abnormally.

   WARNINGS: none

   ERRORS: If the option code is not recognized.
   ------------------------------------------------------------------ */
int parse_options(int argc, char **argv, OPT_TYPE *opt)
{

  extern char *optarg;
  extern int  optind;

  int c, long_index=0;

  char short_opts[]="C:P:T:EWNSZ:a:dc:p:s:y:hvi";
  enum OPT_CODE 
    {
      OPT_COND    = 'C',
      OPT_TEMP    = 'T',
      OPT_PRESS   = 'P',
      OPT_EAST    = 'E',
      OPT_WEST    = 'W',
      OPT_NORTH   = 'N',
      OPT_SOUTH   = 'S',
      OPT_SUFFIX  = 'Z',
      OPT_AREA    = 'a',
      OPT_CRUISE  = 'c',
      OPT_DISPLAY = 'd',
      OPT_SHIP    = 's',
      OPT_PROJECT = 'p',
      OPT_YEAR    = 'y',
      OPT_HELP    = 'h',
      OPT_VERBOSE = 'v'
    };
  struct option long_opts[]=
    {
      {"conductivity-sensor", required_argument, 0, OPT_COND    },
      {"pressure-sensor"    , required_argument, 0, OPT_PRESS   },
      {"temperature-sensor" , required_argument, 0, OPT_TEMP    },
      {"east-longitude"     , no_argument      , 0, OPT_EAST    },
      {"west-longitude"     , no_argument      , 0, OPT_WEST    },
      {"north-latitude"     , no_argument      , 0, OPT_NORTH   },
      {"south-latitude"     , no_argument      , 0, OPT_SOUTH   },
      {"header-suffix"      , required_argument, 0, OPT_SUFFIX  },
      {"area-name"          , required_argument, 0, OPT_AREA    },
      {"cruise-name"        , required_argument, 0, OPT_CRUISE  },
      {"project-name"       , required_argument, 0, OPT_PROJECT },
      {"ship-name"          , required_argument, 0, OPT_SHIP    },
      {"year-base"          , required_argument, 0, OPT_YEAR    },
      {"no-display"         , required_argument, 0, OPT_DISPLAY },
      {"help"               , no_argument      , 0, OPT_HELP    },
      {"Help"               , no_argument      , 0, OPT_HELP    },
      {"HELP"               , no_argument      , 0, OPT_HELP    },
      {"verbose"            , no_argument      , 0, OPT_VERBOSE },
      {"Verbose"            , no_argument      , 0, OPT_VERBOSE },
      {"VERBOSE"            , no_argument      , 0, OPT_VERBOSE },
    };

  HDR_TYPE *hdr;

  /*
   * Initializations
   */
  hdr = opt->hdr;

  /*
   * Loop through options
   */
  while(1){
    
    c = getopt_long(argc, argv, short_opts, long_opts, &long_index);
    if(c == -1)
      break;

    switch(c){
      
      case OPT_HELP:
        print_usage();
        exit(EXIT_FAILURE);
        break;
      case OPT_VERBOSE:
        VERBOSE = 1;
        break;
      case OPT_COND:
        strcpy(hdr->sn.csn, optarg);
        break;
      case OPT_PRESS:
        strcpy(hdr->sn.psn, optarg);
        break;
      case OPT_TEMP:
        strcpy(hdr->sn.tsn, optarg);
        break;
      case OPT_EAST:
        hdr->hlon = 'E';
        break;
      case OPT_NORTH:
        hdr->hlat = 'N';
        break;
      case OPT_WEST:
        hdr->hlon = 'W';
        break;
      case OPT_SOUTH:
        hdr->hlat = 'S';
        break;
      case OPT_SUFFIX:
        strcpy(opt->suffix, optarg);
        break;
      case OPT_AREA:
        strcpy(hdr->misc.area, optarg);
        break;
      case OPT_CRUISE:
        strcpy(hdr->misc.cruise, optarg);
        break;
      case OPT_SHIP:
        strcpy(hdr->misc.ship, optarg);
        break;
      case OPT_PROJECT:
        strcpy(hdr->misc.project, optarg);
        break;
      case OPT_YEAR:
        hdr->time.year = (short) atoi(optarg);
        break;
      case OPT_DISPLAY:
        if(getenv("DISPLAY"))
          unsetenv("DISPLAY");
        break;
      default:
        print_usage();
        exit(EXIT_FAILURE);
        break;
    }
  }

  return(optind);
}

/* ------------------------------------------------------------------
   MAIN
   ------------------------------------------------------------------ */

int main(int argc, char **argv){
  
  OPT_TYPE opts;                /* Structure for options         */
  HDR_TYPE def_hdr;             /* Header structure for defaults */
  char idir[LINE_LENGTH];       /* Input directory               */
  char gname[LINE_LENGTH];      /* Generic header file name      */
  char dir_sep = '/';           /* Directory separator           */
  struct dirent *dentry;        /* Directory entry               */
  DIR *dp_dir;                  /* Pointer to input directory    */
  int iarg;                     /* Number of options on cmd line */
  char fhdr[LINE_LENGTH];       /* Name of header file           */
  char fout[LINE_LENGTH];       /* Name of final output file     */
  FILE *fp_out;                 /* File pointer to output file   */
  char cbuff[LINE_LENGTH];      /* Temporary buffer              */
  char line[LINE_LENGTH];       /* Line buffer from header       */

  int i;

  /* These are temporary */
  char flex[]=DEFAULT_LEX;
  char lexstr[LINE_LENGTH];

  /* Initializations */
  opts.hdr = &(def_hdr);
  strcpy(opts.suffix, HEADER_SUFFIX);
  init_header(&def_hdr, 1);     /* With default values */
  
  /* Options and default values */
  iarg = parse_options(argc, argv, &opts);

  /* Loop through directory entries */
  while(iarg < argc){
    /* Initializations */
    yyin = fp_hdr = fp_out = fp_hdr = NULL;
    strcpy(cbuff, argv[iarg++]);
    /* Get directory separator and generic header file name */
    i = strlen(cbuff);
    while((i >= 0) && (cbuff[i] != '/') && (cbuff[i] != '\\')) i--;
    /* A directory path is required for detrmining the directory separator */
    if(i < 0){
      fprintf(stderr, "\nName of input files must contain directory path\n");
      exit(-1);
    }
    /* Save directory separator, input directory and generic name */
    dir_sep = cbuff[i];
    strncpy(idir, cbuff, i+1);
    idir[i+1] = '\0';
    strcpy(gname, cbuff+i+1);
    /* Open directory */
    if(err( (dp_dir = opendir(idir)) == NULL, OPEN_CODE, 
            "Opening input directory: %s\n", idir))
      goto on_error;
    /* Loop through directory entries */
    while((dentry = readdir(dp_dir)) != NULL){
      /* Check if the file starts with the same generic name, and ends with
         the correct suffix */
      i = strlen(dentry->d_name);
      while((i > 0) && (dentry->d_name[i] != '.')) i--;
      if(i <= 0)
        continue;
      strcpy(cbuff, dentry->d_name + (i+1));
      if((strstr(dentry->d_name, gname) != dentry->d_name) ||
         (strcmp(cbuff, opts.suffix) != 0))
        continue;
      /* Build name for output file */
      strcpy(fout, dentry->d_name);
      /* Build full input name */
      strcpy(fhdr, idir);
      strcat(fhdr, dentry->d_name);
      fprintf(stderr, "HEADER FILE: %s\n", fhdr);
      
      /* --- PROCESS HEADER FILE --- */

      /* Initializations */
      init_header(&hdr, 0);
      line_num = 0;
        
      /* Open input/output files */
      if(err((fp_hdr = fopen(fhdr, "r")) == NULL, OPEN_CODE, 
             "Opening header file \"%s\"\n", fhdr))
        goto on_error;
      if(err((yyin = fopen(flex, "r")) == NULL, OPEN_CODE, 
             "Opening lexical definitionfile \"%s\"\n", flex))
        goto on_error;
      if(err((fp_out = fopen(fout, "w")) == NULL, OPEN_CODE, 
             "Opening output file \"%s\"\n", fout))
        goto on_error;
      
      /* Loop through header file */
      while(!IERR && !feof(fp_hdr)){
        /* Keep start of line */
        fpos = ftell(fp_hdr);
        /* Check for end of header */
        if(err( (fscanf(fp_hdr, "%s", cbuff) != 1), READ_CODE, 
                "Reading file \"%s\" for end of header\n", fhdr))
          goto on_error;
        if(!strcmp(cbuff, EOH)){
          if(VERBOSE)
            fprintf(stderr, "Reached the end of the header: %s\n", EOH);
          break;
        }
        /* Position back to start of line */
        fseek(fp_hdr, fpos, SEEK_SET);
        /* Update line number */
        line_num++ ;
        /* Verbose */
        if(VERBOSE){
          if(err( fgets(cbuff, LINE_LENGTH, fp_hdr) == NULL, READ_CODE,
                  "Current header line at line %-d\n", line_num))
            goto on_error;
          fprintf(stderr, "Now processing header line %-d:\n  %s", 
                  line_num, cbuff);
          fseek(fp_hdr, fpos, SEEK_SET);
        } 
        /* Initialize lexical file */
        rewind(yyin);
        /* Parse header file */
        yylex();
        if(err(IERR, IERR, "Parsing header file with lexical analyzer\n"))
          goto on_error;
        if(VERBOSE){
          get_code_name(cbuff, lexstat, code_names);
          fprintf(stderr, "Returned code from lexical analyzer: %-d %s\n",
                  lexstat, cbuff);
        }
        /* Update name of lex status */
        get_code_name(lexstr, lexstat, code_names);
        /* Process data */
        if( err( check_header(lexstat, &hdr, &def_hdr), IERR,
                 "Checking header data for %s\n", lexstr))
          goto on_error;
        /* Move back to beginning of line.This is necessary as the %F fomat can
           read up to end (including it) of the line */    
        fseek(fp_hdr, fpos, SEEK_SET);
        /* Read up to next input header line */
        if( err( fgets(line, LINE_LENGTH, fp_hdr) == NULL, READ_CODE,
                 "Seeking forward header file at line %-d\n", line_num))
          goto on_error;    
        /* Write output */
        if( err( write_header(fp_out, lexstat, &hdr, line, &def_hdr), IERR, 
                 "Writing header data for %s\n", lexstr))
          goto on_error;
        /* Reset lexical status */
        lexstat = NO_CODE;
      }
      
      /* Write rest of header */
      if( err( write_header(fp_out, UNKNOWN_CODE, &hdr, (char*)NULL, &def_hdr), 
               IERR, "Writing end of header or missing lines\n"))
        goto on_error;
            
      /* Close input/output files */
      fclose(fp_hdr);
      fclose(yyin);
      fclose(fp_out);
      fp_hdr = yyin = fp_out = NULL;
            
    } /* Loop through directory entries      */
  }   /* Loop through command line arguments */

 on_error:

  if(fp_hdr) fclose(fp_hdr);
  if(yyin)   fclose(yyin);
  if(fp_out) fclose(fp_out);

  err(IERR, IERR, "!!! Abnormal termination of %s !!!\n", argv[0]);
  fflush(stderr);

  return(IERR);

}
            













