/****************************************************************************/
/*                                                                          */
/*                          IAGA_fill_missing.c                             */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/* This program fills the given records in an IAGA-format file with missing */
/* data markers. The corrected data is then written into standard output.   */
/*                                                                          */
/* Usage:                                                                   */
/*    IAGA_fill_missing -s -e -o -c IAGAFile > NewIAGAFile                  */
/*         -s YYMMDDHHMMSS  First block to be filled with missing data      */
/*         -e YYMMDDHHMMSS  Last block to be filled with missing data       */
/*         -o StationID     Three letter ID of the station.                 */
/*         -c Components    Components to be filled                         */
/*         IAGAFile         Name of IAGA-format file.                       */
/*         NewIAGAFile      Name of corrected IAGA-format file.             */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/*                            Lasse Hakkinen                                */
/*                    Finnish Meteorological Institute                      */
/*                        Geophysical Research Division                     */
/*                              P.O.Box 503                                 */
/*                      FIN-00101, Helsinki, Finland                        */
/*                      e-mail: Lasse.Hakkinen@fmi.fi                       */
/*                      phone : (+358)-9-19294634                           */
/*                      fax   : (+358)-9-19294603                           */
/*                                                                          */
/*                      version 1.01        9.9.1999                        */
/****************************************************************************/
/****************************************************************************/
/*  Version history:                                                        */
/*                                                                          */
/*  1.01 09.09.1999 Fixed a Y2K bug in NewTime.h file which resulted in     */
/*                  incorrect year in date strings if year >= 2000.         */
/*  1.0  24.10.1996 First official release                                  */
/****************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "Usage.h"
#include "MagnData.h"
#include "IAGA.h"

char *version = "1.01";
char *date = "9.9.1999";

#define HeaderLineCount 4
#define UsageLineCount 10

char *HeaderText[HeaderLineCount] = {
"**************************************************************************",
"This program fills given records in an IAGA-format data file with missing",
"data markers (999999)",
"**************************************************************************",
};

char *UsageText[UsageLineCount] = {
" [-s] [-e] [-c] -o  [<] IAGAFile > NewIAGAFile",
"      [-s YYMMDDHHMMSS]    First record to be replaced with missing data.",
"                           If -s is missing then start of file is assumed.",
"      [-e YYMMDDHHMMSS]    Last record to be replaced with missing data.",
"                           If -e is missing then end of file is assumed.",
"      [-c XYZ]             Components to be replaced with missing data.",
"                           If missing then all components (XYZ) filled.",
"      -o StationID         Three letter ID of the station.",
"      IAGAFile             Name of IAGA-format file.",
"      NewIAGAFile          Name of new IAGA-format file.",
};



/*--------------------------------------------------------------------------*/
/*  Fill block of memory with missing data                                  */
/*--------------------------------------------------------------------------*/

void FillMissingData(long *DataPtr,register long Count)
{
    while (Count-- > 0) *DataPtr++ = MissingValue;
}




/*--------------------------------------------------------------------------*/
/*                          The main procedure                              */
/*--------------------------------------------------------------------------*/

int main(int argc, char *argv[])
{
    long    params;
    long    status = 0;
    long    FileCount = 0;
    char    FileName[100] = "";         /* Name of the original data file   */
    Time_sec StartTime = MIN_TIME;      /* Time of first data block (secs)  */
    Time_sec EndTime   = MAX_TIME;      /* Time of last data block          */
    char    StationID[20] = "???";      /* List of stations in command line */
    char    ComponentStr[5] = "XYZ";    /* List of components               */
    Network_struct IMAGE;               /* Structure containing the data    */
                                        /* for all stations.                */
    StationPtr  Station;                /* Pointer to the corrected station */
    char        Comp;                   /* Current magnetic component       */
    long        *DataPtr;               /* Dummy pointer to field value     */
    Time_sec    T;                      /* Current time                     */


    /*==========================*/
    /* Analyse the command line */
    /*==========================*/
    if (argc == 1) {        /* No arguments, show the usage text */
        PrintUsage(argv[0],0,HeaderLineCount,UsageLineCount);
        return OK;
    }

    for (params = 1; params < argc; params++) {
        if (*argv[params] != '-') {
            strcpy(FileName,argv[params]);
            FileCount++;
        } else {
            switch (*(argv[params]+1)) {
                case 's' : StartTime = StrToSecs(argv[++params],0); break;
                case 'e' : EndTime   = StrToSecs(argv[++params],0); break;
                case 'o' : strcpy(StationID,argv[++params]);        break;
                case 'c' : strcpy(ComponentStr,argv[++params]);     break;
                default  :
                    fprintf(stderr,"\n### %s: \"%s\" is not an option.\n\n",
                            argv[0], argv[params]);
                    PrintUsage(argv[0],1,HeaderLineCount,UsageLineCount);
                    return FAIL;
                    break;
            }
        }
    }


    /*=================================================*/
    /* Check that all necessary parameters are defined */
    /*=================================================*/
    
    if ((FileCount>1) || (strcmp(StationID,"???")==0))
    {
        PrintUsage(argv[0],1,HeaderLineCount,UsageLineCount);
        return FAIL;
    }

    /*====================================================*/
    /* Read the data from an IAGA format file into memory */
    /*====================================================*/

    status = ReadIAGA(FileName,&IMAGE,NULL,NULL,NULL);

    if (status != 0) {
        if (status == FileError)
            fprintf(stderr,"Error in reading file %s\n",FileName);
        if (status == OutOfMemory)
            fprintf(stderr,"Out of memory while reading file %s\n",FileName);
        if (status == FileFormatError)
            fprintf(stderr,"%s is not an IAGA format file\n",FileName);
        return FAIL;
    }

    /*=======================================================*/
    /* Check that the values of the parameters are resonable */
    /*=======================================================*/
    
    Station = FindStation(&IMAGE,StationID);
    
    if (Station == NULL) {
        fprintf(stderr,"Couldn't find station %s in %s\n",StationID,FileName);
        return FAIL;    
    }
    
    if (StartTime > EndTime) {
        fprintf(stderr,"StartTime > EndTime !?\n");
        return FAIL;    
    }

    if ((StartTime != MIN_TIME) &&
       (((StartTime-Station->StartTime) % Station->TimeStep) != 0)) {
        fprintf(stderr,
            "Illegal StartTime. There is no such data point in the datafile\n");
        return FAIL;    
    }

    if ((EndTime != MAX_TIME) &&
       (((EndTime-Station->StartTime) % Station->TimeStep) != 0)) {
        fprintf(stderr,
            "Illegal EndTime. There is no such data point in the datafile\n");
        return FAIL;    
    }

    /*=====================================================*/
    /* Fill data records with missing data marker (999999) */
    /*=====================================================*/

    if (StartTime == MIN_TIME) StartTime = Station->StartTime;
    if (EndTime == MAX_TIME) EndTime = Station->EndTime - Station->TimeStep;

    for (Comp=0;Comp < strlen(ComponentStr);Comp++) {
        DataPtr = GetDataPtr(Station,StartTime,ComponentStr[Comp]);
        for (T=StartTime; T<=EndTime; T += Station->TimeStep)
            *DataPtr++ = MissingValue;
    }

    /*==========================================*/
    /* Write the corrected file into stdout     */
    /*==========================================*/
    
    WriteIAGA(NULL,&IMAGE,NULL,NULL,NULL);

    FreeNetwork(&IMAGE);
    return OK;
}

