/****************************************************************************/
/*                                                                          */
/*                              IAGA_cat.c                                  */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/* This program catenates two or more IAGA-format files into a single IAGA	*/
/* file. 																	*/
/*                                                                          */
/* Usage:                                                                   */
/*    IAGA_cat IAGAFile1 ... IAGAFileN > NewIAGAFile                		*/
/*      IAGAFile1           Name of first IAGA-format file.                 */
/*      IAGAFileN           Name of last IAGA-format file.                  */
/*      NewIAGAFile         Name of new 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        22.10.2010                       */
/****************************************************************************/
/****************************************************************************/
/*  Version history:                                                        */
/*                                                                          */
/*  1.0  22.10.2010 First official release                                  */
/****************************************************************************/

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

#define OK   0              /* Return value for successfull completion      */
#define FAIL 1              /* Return value for failed operation            */
#define MaxFileCount 50		/* Maximum number of IAGA files					*/

char *version = "1.0";
char *date = "22.10.2010";

#define HeaderLineCount 4
#define UsageLineCount  4

char *HeaderText[HeaderLineCount] = {
"**************************************************************************",
"This program catenates two or more IAGA format files into a single IAGA   ",
"file.                                                                     ",
"**************************************************************************",
};

char *UsageText[UsageLineCount] = {
" IAGAFile1 ... IAGAFileN > NewIAGAFile",
"      IAGAFile1            Name of first IAGA-format file.                ",
"      IAGAFileN            Name of last IAGA-format file.                 ",
"      NewIAGAFile          Name of new IAGA-format file.                  ",
};



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

int main(int argc, char *argv[])
{
    long    i,j;                        /* Dummy indices                    */
    long    params;
    long    status;
    long    FileCount = 0;              /* Number of IAGA files             */
    char    *FileName[MaxFileCount];    /* Names of the data files          */
    FILE    *IAGAFile[MaxFileCount];    /* File pointers to IAGA files      */
    StationInfoPtr p;               	/* Pointer to StationInfoStruct		*/
                                    	/* defined in StatInfo.h file.      */
    Network_struct IMAGE;          		/* Structure containing the data	*/
                                   		/* for all stations.             	*/
    Network_struct TEMP;
    StationPtr s,v;


    /*==========================*/
    /* 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] != '-') {
            FileName[FileCount++] = argv[params];
        } else {
            switch (*(argv[params]+1)) {
                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 (FileCount > MaxFileCount) {
        fprintf(stderr,"###  Too many files : %d\n",FileCount);
        fprintf(stderr,"###  Maximum allowed: %d\n",MaxFileCount);
        return FAIL;
    }


	/*====================================================================*/
	/* Read the data from the first IAGA format file into IMAGE structure */
	/*====================================================================*/

	status = ReadIAGA(FileName[0],&IMAGE,"","","");

	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;
	}


    /*==================================================*/
    /* Read one data file at a time and catenate its	*/
    /* content to the IMAGE structure.					*/
    /*==================================================*/

	for (i = 1; i < FileCount; i++) {

		// Read the IAGA format file into TEMP structure
		status = ReadIAGA(FileName[i],&TEMP,"","","");
		if (status != 0) {
			if (status == FileError)
				fprintf(stderr,"Error in reading file %s\n",FileName);
			if (status == FileFormatError)
				fprintf(stderr,"%s is not an IAGA format file\n",FileName);
			return FAIL;
		}

		// Go through stations in TEMP and check that they exist in
		// IMAGE. If not then create the station with missing data.
		s = TEMP.StationList;

		while (s != NULL) {
			if (FindStation(&IMAGE,s->StationID) == NULL) {	// Station not found, add station to IMAGE
				NewStation(&IMAGE, FindStationInfo(s->StationID), 0, 0, 0, 0);
			}
			s = s->Next;
		}

		// Go through stations in IMAGE and add all station data from TEMP into it.
		// If the station is not found in TEMP then fill the space with missing data.
		s = IMAGE.StationList;
		while (s != NULL) {
			v = FindStation(&TEMP,s->StationID);
			if (v == NULL) {	// Station not found, extend its data area
				ExtendDataArea(s,TEMP.StationList->StartTime,TEMP.StationList->EndTime);
			} else {
				ExtendDataArea(s,v->StartTime,v->EndTime);
				CopyAllMagnData(v,s,v->StartTime,v->EndTime,0);
			}
			s = s->Next;
		}

		FreeNetwork(&TEMP);
	}


	WriteIAGA(NULL,&IMAGE,NULL,NULL,NULL);
	FreeNetwork(&IMAGE);
    return OK;
}

