/****************************************************************************/
/*																			*/
/*								IAGA_reorder.c								*/
/*																			*/
/****************************************************************************/
/****************************************************************************/
/* This program reorders the stations in a single IAGA file.				*/
/*                                                                          */
/* Usage:                                                                   */
/*    IAGA_reorder [-o | -m] [-p] [<] IAGAFile > NewIAGAFile				*/
/*		 -o StationList		Defines how the stations are ordered in the		*/
/*							final IAGA file. e.g. 'SOR MAS KEV'.			*/
/*							Stations which are not mentioned in StationList */
/*							will NOT be written into final data file.		*/
/*		 -m					Orders the stations according to geomagnetic	*/
/*							(CGM) latitudes. Either -o or -m may be used,	*/
/*							not both.										*/
/*		[-p] 				Prevents usage-text from appearing. Useful when	*/
/*							reading data from standard input.				*/
/*		IAGAFile 			Name of 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.09 		2.7.2008						*/
/****************************************************************************/
/****************************************************************************/
/*	Version history:														*/
/*																			*/
/*	1.10 13.01.2010	Added JCK station to the default list.					*/
/*	1.09 02.07.2008	Added DON station to the default list.					*/
/*	1.08 27.10.2007	Added NOR and SOL stations to the default list.			*/
/*	1.07 12.11.2004	Added MEK station to the default list.		    		*/
/*	1.06 30.03.2004	Added BER and KAR stations to the default list.		    */
/*	1.05 13.11.2002	Added -m option.									    */
/*	1.04 22.11.2001	Added JAN station to the default list				    */
/*	1.03 18.09.2001	Added TAR station to the default list				    */
/*	1.02 24.05.2001	Added IVA station to the default list				    */
/*	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  02.06.1998	First official release									*/
/****************************************************************************/

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

#define MaxStationCount 50	/* Maximum number of stations in input file		*/
#define BuffSize 1440		/* Size of one data block in an IAGA file 		*/

char *IMAGEStationList = "NAL LYR HOR HOP BJN JAN TRO AND LEK ABK KIR LOZ NOR SOR ALT MAS KAU KEV KIL IVA MUO PEL SOD JCK DON RVK LYC OUJ MEK HAN DOB SOL BER KAR NUR UPS TAR";
char *IMAGECGMLat      = "NAL LYR HOR HOP BJN NOR JAN SOR TRO ALT AND KEV MAS KIL LEK ABK KAU IVA MUO KIR LOZ SOD PEL JCK DON RVK LYC OUJ DOB SOL MEK HAN BER KAR NUR UPS TAR";


char *version = "1.10";
char *date = "13.1.2010";

#define HeaderLineCount 3
#define UsageLineCount 14


char *HeaderText[HeaderLineCount] = {
"**************************************************************************",
"This program reorders stations within a single IAGA file.                 ",
"**************************************************************************",
};

char *UsageText[UsageLineCount] = {
"  [-o | -m] [-p] [<] IAGAFile > NewIAGAFile                              ",
"       -o StationList      Defines how the stations are ordered in the   ",
"                           final data file. e.g. 'SOR MAS KEV'.          ",
"                           Stations which are not mentioned are NOT      ",
"                           included in the final data file.              ",
"       -m                  Reorders the stations according to geomagnetic",
"                           (CGM) latitudes. This option will work only   ",
"                           for IMAGE stations. Either -o or -m may be    ",
"                           used not both. If neither one is defined then ",
"                           a default ordering will be used.              ",
"       -p                  Prevents usage text from appearing. Useful    ",
"                           when reading from standard input.             ",
"      IAGAFile1            Name of 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,status;
	long	BlockNbr;
	long	FileCount = 0;				/* Number of IAGA files				*/
	long	StationCount;				/* Number of stations in IAGA file 	*/
	long	TotalStationCount;			/* Total number of stations			*/
	long	GeoMagOrdering = 0;			/* Use geomagnetic latitudes		*/
	char	StationStr[200] = "";		/* List of stations					*/
	char	Block[MaxStationCount][BuffSize];	/* IAGA data blocks			*/
	char	FileName[100];				/* Name of the original data file	*/
	FILE	*IAGAFile;					/* IAGA file to be processed		*/


	/*==========================*/
	/* 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 'o' : strcpy(StationStr,argv[++params]);   break;
				case 'm' : GeoMagOrdering = 1;					break;
				case 'p' : /* Do nothing */						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;
	}
	
	/*===========================*/
	/* Try to open the IAGA file */
	/*===========================*/

	if (FileCount == 0) IAGAFile = stdin;
	else {
		if ((IAGAFile = fopen(FileName, "r")) == NULL) {
			fprintf(stderr,"\n### %s - Unable to open file: %s\n",argv[0],FileName);
			return FAIL;
		}
	}

	/*==================================================*/
	/* Determine which ordering is used.				*/
	/*==================================================*/

	if (strlen(StationStr) == 0) {
		if (GeoMagOrdering == 1)
			strcpy(StationStr,IMAGECGMLat);
		else
			strcpy(StationStr,IMAGEStationList);
	}

	/*==================================================*/
	/* Read data blocks and write them in proper order. */
	/* This must be done in a bit awkward manner since  */
	/* we may be reading from stdin.				    */
	/*==================================================*/

	status = ReadIAGABlock(IAGAFile,Block[0]);
	while (status != 0) {
		BlockNbr = 0;
		do {
			status = ReadIAGABlock(IAGAFile,Block[++BlockNbr]);
		} while ((status != 0) && (strncmp(Block[BlockNbr]+12,Block[0]+12,3) != 0));

		/*** Write data blocks in proper order ***/
		
		for (i=0;i<strlen(StationStr);i += 4) {	/* Go through StationStr */
			for (j=0;j<BlockNbr;j++) {
				if (strncmp(StationStr+i,Block[j]+12,3) == 0) {
					WriteIAGABlock(stdout,Block[j]);
					break;		/* Station found, so exit from the loop	*/
				}
			}
		}
		
		/*** We have already read the next data block of the first	***/
		/*** station so copy data from last block to first block	***/
		
		if (status != 0) memcpy(Block[0],Block[BlockNbr],BuffSize);
	}
	

	if (FileCount == 1) fclose(IAGAFile);
	return OK;
}

