/****************************************************************************/
/*                                                                          */
/*                              KIR_to_IAGA.c                               */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/* This is a filter program that reads a KIR-format data file and writes    */
/* out the same data in IAGA format.                                        */
/*                                                                          */
/* Usage:                                                                   */
/*    KIR_to_IAGA [-s] [-e | -h] [-o] KIR_file > IAGA_file                  */
/*      [-s YYMMDDHH]       Time of the first record included. If missing   */
/*                          then start of file is assumed.                  */
/*      [-e YYMMDDHH]       Time of the record not included anymore. If     */
/*                          missing then end of file is assumed.            */
/*      [-h HH]             Number of hours included. Either -e or -h can   */
/*                          be specified, not both.                         */
/*      [-o 'StationID']    Three letter station ID. If missing then KIR    */
/*                          is assumed. Note that there is no information   */
/*                          about the station name inside the data file.    */
/*      KIR_file            Name of KIR-format file. Cannot read from stdin */
/*      IAGA_file           Name of IAGA-format file.                       */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/*                            Lasse Hakkinen                                */
/*                    Finnish Meteorological Institute                      */
/*                        Department of Geophysics                          */
/*                              P.O.Box 503                                 */
/*                      FIN-00101, Helsinki, Finland                        */
/*                      e-mail: Lasse.Hakkinen@fmi.fi                       */
/*                      phone : (+358)-9-19294634                           */
/*                      fax   : (+358)-9-19294634                           */
/*                                                                          */
/*                      version 1.04        19.10.1999                      */
/****************************************************************************/
/****************************************************************************/
/*  Version history:                                                        */
/*                                                                          */
/*  1.04 19.10.1999 Fixed a bug in KIR.h where binary numbers were          */
/*                  incorrectly handled in little-endian processors.        */
/*  1.03 09.09.1999 Fixed a Y2K bug in NewTime.h file which resulted in     */
/*                  incorrect year in date strings if year >= 2000.         */
/*  1.02 04.05 1999 Re-fixed a bug in handling data lines where the         */
/*                  difference in times is not the fixed TimeStep.          */
/*  1.01 02.02.1999 Fixed a timing bug where the times of the data blocks   */
/*                  were not at fixed intervals.                            */
/*                  Also added the -d option (= Sample step)                */
/*  1.0  29.09.1997 First official release                                  */
/****************************************************************************/

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

char *version = "1.04";
char *date = "19.10.1999";

#define HeaderLineCount 3
#define UsageLineCount 16

char *HeaderText[HeaderLineCount] = {
"**************************************************************************",
"This program converts magnetometer data from KIR format into IAGA format.",
"**************************************************************************",
};

char *UsageText[UsageLineCount] = {
" [-s] [-e | -h] [-o]   KIR_file > IAGA_file",
"      [-s YYMMDDHH]        Time of the first record included. If missing  ",
"                           then start of file is assumed.                 ",
"      [-e YYMMDDHH]        Time of the record not included anymore.       ",
"                           If missing then end of file is assumed.        ",
"      [-h HH]              Number of hours included. Either -e or -h can  ",
"                           be specified, not both.                        ",
"      [-o StationID]       Three letter station ID. If missing then KIR is",
"                           assumed. Note that there is no information     ",
"                           about the station name inside the data file.   ",
"      [-d SampleStep]      Sample step used in the file. If this is not   ",
"                           defined then the program tries to read it from ",
"                           the data file.                                 ",
"      KIR_file             Name of KIR-format file. This must be given.   ",
"                           Cannot read from stdin.                        ",
"      IAGA_file            Name of IAGA-format file.                      ",
};


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

int main(int argc, char *argv[])
{
    long params;
    long status = 0;
    long FileCount = 0;
    long HourCount = 0;
    char FileName[100]    = "";
    char StartTimeStr[14] = "";
    char EndTimeStr[14]   = "";
    char StationStr[50]   = "KIR";
    Time_sec SampleStep   = 0;
    Network_struct NETWORK;
    
    
    /*==========================*/
    /* 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' : strcpy(StartTimeStr,argv[++params]); break;
                case 'e' : strcpy(EndTimeStr,argv[++params]);   break;
                case 'h' : HourCount = atol(argv[++params]);    break;
                case 'o' : strcpy(StationStr,argv[++params]);   break;
                case 'd' : SampleStep = 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;
    }
    if ((HourCount != 0) && (strlen(EndTimeStr) > 0)) {
        PrintUsage(argv[0],1,HeaderLineCount,UsageLineCount);
        return FAIL;
    }
    if ((HourCount != 0) && (strlen(StartTimeStr) == 0)) {
        PrintUsage(argv[0],1,HeaderLineCount,UsageLineCount);
        return FAIL;
    }
    if (HourCount != 0) {
        SecsToStr(StrToSecs(StartTimeStr,0)+3600*HourCount,EndTimeStr);
    }


    /*==================================================*/
    /* Read the data from a KIR format file into memory */
    /*==================================================*/

    status = ReadKIR(FileName,&NETWORK,StartTimeStr,EndTimeStr,StationStr,SampleStep);

    if (status != 0) {
        if (status == FileError)
            fprintf(stderr,"Error in reading KIR 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 a KIR format file\n",FileName);
        return FAIL;
    }

    /*==============================================*/
    /* Write the data in IAGA format into stdout    */
    /*==============================================*/

    WriteIAGA(NULL,&NETWORK,NULL,NULL,NULL);

    FreeNetwork(&NETWORK);
    return OK;
}

