/****************************************************************************/
/*                                                                          */
/*                              XYZ_to_HDZ.c                                */
/*                                                                          */
/****************************************************************************/
/****************************************************************************/
/* This program converts an IAGA format data file in XYZ representation     */
/* into HDZ representation. All stations in the file will be converted.     */
/* The data may may be read either from a file or from stdin. Results are   */
/* written to standard output.                                              */
/*                                                                          */
/* Usage:                                                                   */
/*    XYZ_to_HDZ -p [<] IAGAFileXYZ > IAGAFileHDZ                           */
/*          -p                  This flag prevents the display of program   */
/*                              info. It is usually used when reading data  */
/*                              from unix pipe.                             */
/*          IAGAFile            Name of IAGA-format file.                   */
/*          NewIAGAFile         Name of generated 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-19294603                           */
/*                                                                          */
/*                      version 1.01            9.9.1999                    */
/****************************************************************************/
/****************************************************************************/
/*  Version history:                                                        */
/*                                                                          */
/*  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  23.10.1998 First official release                                  */
/****************************************************************************/

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

#define BuffSize 1440               /* Size of one block in an IAGA file */

char *version = "1.01";
char *date = "9.9.1999";

#define HeaderLineCount 4
#define UsageLineCount  6

char *HeaderText[HeaderLineCount] = {
"**************************************************************************",
"This program converts an IAGA format data file in XYZ representation into ",
"HDZ representation. All stations in the file will be converted.           ",
"**************************************************************************",
};

char *UsageText[UsageLineCount] = {
"  [-p] [<] IAGAFileXYZ > IAGAFileHDZ",
"      [-p ]                This flag prevents the display of program info.",
"                           It is usually used when reading data from pipe",
"                           line.",
"      IAGAFileXYZ          Name of IAGA-format file in XYZ representation.",
"      IAGAFileHDZ          Name of new IAGA-format file (HDZ).",
};



/*--------------------------------------------------------------------------*/
/*  Convert data from XYZ representation into HDZ representation.           */
/*  H is in units 0.1 nT and D in 0.1 arcminutes.                           */
/*--------------------------------------------------------------------------*/

void Convert_XYZ_to_HDZ(char *Buffer)
{
    char *Xptr = Buffer+IAGA_Data;
    char *Yptr = Buffer+IAGA_Data+7;
    long i;
    long H,D;
    long X,Y;
    double coeff = 34377.468; /* = (180*60*10)/Pi */
    char XYstr[30];
    
    /*** 60 data points ***/
    for (i=0;i<60;i++) {
        X = GetIAGAFieldValue(Xptr);
        Y = GetIAGAFieldValue(Yptr);
        if ((X == MissingValue) || (Y == MissingValue)) {
            memcpy(Xptr," 999999 999999",14);
        }
        else {
            H = RoundFloat(sqrt(((double) X)*((double) X) + ((double) Y)*((double) Y)));
            D = RoundFloat(coeff*atan2(Y,X));
            sprintf(XYstr,"% 07d% 07d",H,D);
            memcpy(Xptr,XYstr,14);
        }
        Xptr += 21;
        Yptr += 21;
    }
    
    /*** Hour average ***/
    X = GetIAGAFieldValue(Xptr);
    Y = GetIAGAFieldValue(Yptr);
    if ((X == MissingValue) || (Y == MissingValue)) {
        memcpy(Xptr," 999999 999999",14);
    }
    else if ((X == 0) && (Y == 0)) {
        memcpy(Xptr," 000000 000000",14);   
    }
    else {
        H = RoundFloat(sqrt(((double) X)*((double) X) + ((double) Y)*((double) Y)));
        D = RoundFloat(coeff*atan2(Y,X));
        sprintf(XYstr,"% 07d% 07d",H,D);
        memcpy(Xptr,XYstr,14);
    }

    /*** Update the component marker ***/
    Buffer[IAGA_Components] = '2';
}


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

int main(int argc, char *argv[])
{
    long    params;
    long    status = 0;
    long    FileCount = 0;
    char    FileName[100] = ""; /* Name of the original data file           */
    char    Buffer[BuffSize];   /* Buffer for one data block                */
    FILE    *IAGAFile;          /* IAGA format data 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 'p' :  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;
        }
    }

    /*===================================*/
    /* Extract proper data from the file */
    /*===================================*/

    while (ReadIAGABlock(IAGAFile,Buffer))
    {
        if (Buffer[IAGA_Components] == 2) {
            fprintf(stderr,"\n### File %s already in HDZ format\n",FileName);
            break;
        }
        Convert_XYZ_to_HDZ(Buffer);
        WriteIAGABlock(stdout,Buffer);
    }

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

