/****************************************************************************/
/*                                                                          */
/*                              IAGA_extend.c                               */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/* This program reads an IAGA format file and extends the start and end     */
/* times to given values. If the start and end times are not defined then   */
/* extension is made so that data starts and ends on full day boundaries.   */
/* Extended intervals will be filled with missing data markers.             */
/*                                                                          */
/* Usage:                                                                   */
/*    IAGA_extend_fullday [-s -e] [<] IAGAFile > NewIAGAFile                */
/*      -s YYMMDDHHMM       Time of first record to be written. If missing  */
/*                          then start time is set to previous full day     */
/*                          boundary (= 00:00:00 at the same day that data  */
/*                          actually starts). Extended interval will be     */
/*                          filled with missing data markers.               */
/*      -e YYMMDDHHMM       Time of the block not anymore written. If       */
/*                          missing then end time is set to next full day   */
/*                          boundary (= 00:00:00 at the next day). Extended */
/*                          interval will be filled with missing data       */
/*                          markers.                                        */
/*		-h HH				Number of hours included. If -h	is defined then	*/
/*							-e option is neglected.							*/
/*      IAGAFile            Name of IAGA-format file.                       */
/*      NewIAGAFile         Name of extended 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.0     9.9.1999                            */
/****************************************************************************/
/****************************************************************************/
/*  Version history:                                                        */
/*                                                                          */
/*  1.02 11.10.2010 Added -h option.									    */
/*  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  21.2.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.02";
char *date = "11.10.2010";

#define HeaderLineCount 6
#define UsageLineCount 15

char *HeaderText[HeaderLineCount] = {
"**************************************************************************",
" This program reads in an IAGA format file and extends the start and end  ",
" times to given values. If the start and end times are not defined then   ",
" the extension is done so that data will start and end on full day        ",
" boundaries. Extended intervals will be filled with missing data markers. ",
"**************************************************************************",
};

char *UsageText[UsageLineCount] = {
"  [-s -e] [<] IAGA_file > NewIAGA_file                                    ",
"       -s YYMMDDHHMM       Time of the first record to be written. If     ",
"                           missing then start time is set to previous full",
"                           day boundary (= 00:00:00 at the same day that  ",
"                           data actually starts). Extended interval will  ",
"                           be filled with missing data markers.           ",
"       -e YYMMDDHHMM       Time of the last record not written anymore.   ",
"                           If missing then end time is set to next full   ",
"                           day boundary (= 00:00:00 at the next day).     ",
"                           Extended interval will be filled with missing  ",
"                           data markers.                                  ",
"      -h HH                Number of hours included. If -h	is defined then",
"                           -e option is neglected.                        ",
"      IAGA_file            Name of IAGA-format file.                      ",
"      NewIAGA_file         Name of averaged IAGA-format file.             ",
};



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

int main(int argc, char *argv[])
{
    long params;                    /* Dummy index variable                 */
    long status = 0;                /* Status variable for file operations  */
    long FileCount = 0;             /* Number of files in command line      */
    char FileName[100]    = "";     /* Name of IAGA file                    */
	long HourCount = 0;				/* Number of hours to be processed		*/
    Time_sec StartTime = MIN_TIME;  /* Time of first block to be processed  */
    Time_sec EndTime   = MAX_TIME;  /* Time of last block to be processed   */
    Network_struct IMAGE;           /* Stations read from the data file     */
    Network_struct NEWIMAGE;        /* Time extended station list           */
    StationPtr Station;             /* Pointer to station in IMAGE struct   */
    StationPtr StationNew;          /* Pointer to station in NEWIMAGE struct*/
    StationInfoPtr p;               /* Pointer to StationInfoStruct defined */
                                    /* in StatInfo.h file.                  */

    
    /*==========================*/
    /* 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 'h' : HourCount = atol(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 the values of the parameters */
    /*====================================*/
    
    if (FileCount > 1) {
        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;
    }

    /*==================================*/
    /* Adjust the start and end times   */
    /*==================================*/
    
    if (StartTime == MIN_TIME)      /* Round to previous full day boundary  */
        StartTime = 86400*((IMAGE.StationList->StartTime)/86400);

	if (HourCount != 0) {
		EndTime = StartTime + 3600*HourCount;
	} else {
		if (EndTime == MAX_TIME) {      /* Round to next full day boundary      */
			if (((IMAGE.StationList->EndTime) % 86400) != 0)
				EndTime = 86400*((IMAGE.StationList->EndTime)/86400 + 1);
			else
				EndTime = IMAGE.StationList->EndTime;
		}
	}
    

    /*==============================================================*/
    /* Create a network structure containing the stations in IMAGE  */
    /* structure and fill the data fields with missing values       */
    /*==============================================================*/

    InitNetwork(&NEWIMAGE);
    Station = IMAGE.StationList;
    while (Station != NULL) {
        p = FindStationInfo(Station->StationID);
        if (strncmp(p->StationID,"   ",3) == 0) {
            fprintf(stderr,"### Station %s not found in StatInfo.h file.\n",
                    Station->StationID);
            fprintf(stderr,"### Add station to StatInfo.h file and ");
            fprintf(stderr,"recompile the program\n\n");
            return FAIL;
        }
        else {
            if (NewStation(&NEWIMAGE,p,StartTime,EndTime,
                    Station->TimeStep,Station->TempStep) != 0) {
                fprintf(stderr,"### Out of memory !\n");
                return FAIL;
            }
        }
        Station = Station->Next;
    }


    /*==============================================================*/
    /* Copy data from IMAGE structure to NEWIMAGE structure.        */
    /*==============================================================*/

    Station = IMAGE.StationList;
    while (Station != NULL) {
        StationNew = FindStation(&NEWIMAGE,Station->StationID);
        CopyMagnData(Station,StationNew,'X',StartTime,EndTime,0);
        CopyMagnData(Station,StationNew,'Y',StartTime,EndTime,0);
        CopyMagnData(Station,StationNew,'Z',StartTime,EndTime,0);
        CopyMagnData(Station,StationNew,'T',StartTime,EndTime,0);
        Station = Station->Next;
    }



    /*======================================================*/
    /* Write the extended data in IAGA format into stdout   */
    /*======================================================*/
    
    WriteIAGA(NULL,&NEWIMAGE,NULL,NULL,NULL);

    FreeNetwork(&IMAGE);
    return OK;
}

