/****************************************************************************/
/*                                                                          */
/*                              Find_average.c                              */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/* This program reads IAGA, GADF, Dump or WDC format data files containing  */
/* magnetometer data, computes average values and maximum - minimum values  */
/* for each component over the whole period and writes results into         */
/* standard output                                                          */
/*                                                                          */
/* Usage:                                                                   */
/*    Find_average [-f] File1 ... FileN                                     */
/*      [-f Dataformat]     Format of the data file. Possible values for    */
/*                          Dataformat are IAGA (default),GADF,Dump or WDC. */
/*         File*            Names of data files.                            */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/*                            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-19294603                           */
/*                                                                          */
/*                      version 1.02        02.07.1999                      */
/****************************************************************************/
/****************************************************************************/
/*  Version history:                                                        */
/*                                                                          */
/*  1.02 02.07.1999 Fixed a Y2K bug in NewTime.h file which resulted in     */
/*                  incorrect year in date strings if year >= 2000.         */
/*  1.01 21.10.1998 Accommodated to the changes in Dump.h (0.1 nT to        */
/*                  0.01 nT resolution).                                    */
/*  1.0  27.10.1997 First official release                                  */
/****************************************************************************/

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

char *version = "1.02";
char *date = "02.07.1999";

#define HeaderLineCount 4
#define UsageLineCount  4

char *HeaderText[HeaderLineCount] = {
"**************************************************************************",
"This program computes average values and max-min values of all components ",
"for given data files. Results are into standard output.                   ",
"**************************************************************************",
};

char *UsageText[UsageLineCount] = {
" [-f] File1 ... FileN                                                      ",
"       [-f Dataformat]     Format of the data file. Possible values for    ",
"                           Dataformat are IAGA (default),GADF,Dump or WDC. ",
"      File*                Names of data files.",
};



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

int main(int argc, char *argv[])
{
    long    params,i;
    long    status = 0;
    long    FileCount = 0;
    long    FileNbr;
    char    FileName[100];
    Network_struct NETWORK;             /* Structure containing the data    */
                                        /* for all stations.                */
    StationPtr  Station;                /* Pointer to the current station   */
    char FormatStr[10]      = "IAGA";   /* Format of magnetometer data file */
    char StartTimeStr[20];
    char EndTimeStr[20];
    char Comp;
    long Average,Max,Min;

    /*==========================*/
    /* 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] != '-') {
            argv[FileCount++] = argv[params];
        } else {
            switch (*(argv[params]+1)) {
                case 'f' : strcpy(FormatStr,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 == 0)
    {
        PrintUsage(argv[0],1,HeaderLineCount,UsageLineCount);
        return FAIL;
    }

    /*=================================================*/
    /* Go through all files listed in the command line */
    /*=================================================*/

    for (FileNbr = 0; FileNbr < FileCount; FileNbr++) {
        strcpy(FileName,argv[FileNbr]);

        /*======================================*/
        /* Read data from data file into memory */
        /*======================================*/

        if (!strcmp(FormatStr,"IAGA")) {
            status = ReadIAGA(FileName,&NETWORK,NULL,NULL,NULL);
        } else
        if (!strcmp(FormatStr,"GADF")) {
            status = ReadGADF(FileName,&NETWORK,NULL,NULL,NULL);
        } else
        if (!strcmp(FormatStr,"Dump")) {
            status = ReadDump(FileName,&NETWORK,NULL,NULL,NULL);
        } else
        if (!strcmp(FormatStr,"WDC")) {
            status = ReadWDC(FileName,&NETWORK,NULL,NULL,NULL);
        } else {
            fprintf(stderr,"Illegal format type: %s\n",FormatStr);
            return FAIL;
        }
    
        if (status != 0) {
            if (status == FileError)
                fprintf(stderr,"### Error in opening data file ");
            if (status == OutOfMemory)
                fprintf(stderr,"### Out of memory while reading data file");
            if (status == FileFormatError)
                fprintf(stderr,"### Wrong file format in input file ");
            fprintf(stderr,"%s\n",FileName);
        }
        
        if (!strcmp(FormatStr,"Dump"))
            ChangeUnitsDOWN(&NETWORK);



        /*======================================*/
        /* Go through all stations in NETWORK   */
        /*======================================*/

        Station = NETWORK.StationList;
        while(Station != NULL) {
            
            for (Comp='X';Comp <= 'Z';Comp++) {
                Average = ComputeAverage(Station,Comp,Station->StartTime,
                                    Station->EndTime - Station->StartTime);
                FindMaxMin(Station,Comp,Station->StartTime,
                    Station->EndTime - Station->StartTime,&Max,&Min);
                printf("%7.1f   %7.1f   ",
                                Average/10.0,(Max-Min)/10.0);
            }
            printf("\n");
            Station = Station->Next;
        }                               /* End of Station Loop */

        FreeNetwork(&NETWORK);
    }                                   /* End of File loop */

    return OK;
}

