/*--------------------------------------------------------------------
 *	$Id: mgd77togmt.c,v 1.1.1.1.4.2 2002/02/27 17:41:10 pwessel Exp $
 *
 *    Copyright (c) 1991-2002 by P. Wessel and W. H. F. Smith
 *    See README file for copying and redistribution conditions.
 *--------------------------------------------------------------------*/
/*
 * mgd77togmt reads a mgd77 tape file from NGDC and creates
 * a gmt file directly.  If no time is provided, a fake time is
 * issued based on a year and a time increment. We set year = 0 for
 * these cruises and estimate the time_inc based on the distance
 * between 2 nav points and an assumed velocity.
 *
 * Author:	Paul Wessel
 * Date:	9-SEP-1989
 *
 * Modified by WHFS 21 July 1993:
 *	Fixed usage message to be consistent with actual run for -H.
 *	Added carter table correction routines for depth.  Now uses
 *	twt if present, and then if not uses corr depth if present.
 * Modified by PW 19 February 1999:
 *	The 3 binary Carter tables have been replaced by a single ASCII
 *	table carter.d which makes it simpler to port this program.
 * Modified by PW 21 June 1999:
 *	The new MGD77 format is now Y2K compliant.  Added support for
 *	the new format, plus Y2K kludge for older files based on the
 *	NGDC-provided fact that the oldest cruise in the database is
 *	from 1939.  Hence, all 2-digit years from 0 to 38 are inter-
 *	preted to mean 20xx.  This fix will fail in 2039 if there will
 *	be fools then that make old-style MGD77 files.
 *	Also, removed the effect of the -H switch since we can check
 *	the first column for what type of record it is.  Left -H in
 * 	for backward compatibility.
 *	If no -A is given, agency is set equal to the legname.
 *	Placed all the Carter table initialization parameters in a
 *	separate include file (carter.h).
 */

#include "gmt.h"
#include "gmt_mgg.h"

struct GMTMGG_TIME *gmt;
struct GMTMGG_REC *record;

char *LIBDIR;

main (int argc, char **argv)
{
	int i, rec, n_records, n_read, n_files = 0, n_alloc = GMT_CHUNK, leg_year = 0, len, *year;
	int T_INC = 60, fake_running_time = 0;
	BOOLEAN use_list = FALSE, set_agency = FALSE;
	int t_flag = FALSE, error = FALSE;
	char file[80], *mfile, *list, agency[10], *legfname, line[BUFSIZ], **mgd77, **prefix;
	FILE *fp = NULL, *fpo;
	
	if ((LIBDIR = getenv ("GMTHOME")) == (char *)NULL) {
		fprintf (stderr, "mgd77togmt: Environment variable GMTHOME not set!\n");
		exit (EXIT_FAILURE);
	}

	legfname = list = mfile = CNULL;
	memset ((void *)agency, 0, (size_t)10);
	
	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
				case 'Y':
					leg_year = atoi (&argv[i][2]);
					break;
				case 'I':	/* No time in data file, specify time increment between points */
					T_INC = atoi (&argv[i][2]);
					t_flag = TRUE;	/* fake time starts at 1/1/2000 @ 00:00:00 hr */
					break;
				case 'H':	/* No longer used, kept for nostalgic reasons */
					break;
				case 'F':
					legfname = &argv[i][2];
					break;
				case 'L':
					list = &argv[i][2];
					use_list = TRUE;
					break;
				case 'A':
					strcpy (agency, &argv[i][2]);
					break;
				case 'V':
					gmtdefs.verbose = TRUE;
					break;
				default:
					fprintf (stderr, "SYNTAX ERROR:  Unrecognized option -%c\n", argv[i][1]);
					error = TRUE;
					break;
			}
		}
		else
			mfile = argv[i];
	}
	
	if (use_list && !list) {
		fprintf (stderr, "SYNTAX ERROR -L option:  Must specify list file\n");
		error = TRUE;
	}
	if (use_list && (legfname || leg_year != 0)) {
		fprintf (stderr, "SYNTAX ERROR -L option:  Specify -L or the combination -F, -Y\n");
		error = TRUE;
	}
	
	if (argc == 1 || error) {
		fprintf (stderr, "usage: mgd77togmt [mgd77file] -F<filename> -Y<leg_year> OR -L<leglist> [-A<10 char agency name>] [NGDC-file -I<time_increment>] [-V]\n");
		fprintf (stderr, "	-F sets gmtfilename prefix (e.g., without path or .gmt)\n");
		fprintf (stderr, "	-Y sets start year\n");
		fprintf (stderr, "	-L gives name of a list with several records of <mgd77file> <gmtprefix> <leg_year>\n");
		fprintf (stderr,"\n\tOPTIONS:\n");
		fprintf(stderr,"	-A sets optional 10 char info for gmt header.\n");
		fprintf (stderr, "	-I sets fake timeincrement for files without time information\n");
		fprintf(stderr,"	-V runs in verbose mode.\n");
		
		exit (EXIT_FAILURE);
	}

	if (agency[0]) set_agency = TRUE;

	if (use_list) {
	
		mgd77 = (char **) GMT_memory (VNULL, (size_t)n_alloc, sizeof (char *), "mgd77togmt");
		prefix = (char **) GMT_memory (VNULL, (size_t)n_alloc, sizeof (char *), "mgd77togmt");
		year = (int *) GMT_memory (VNULL, (size_t)n_alloc, sizeof (int), "mgd77togmt");
		if ((fp = fopen (list, "r")) == NULL) {
			fprintf (stderr, "mgd77togmt: Cannot open file %s!\n", list);
			exit (EXIT_FAILURE);
		}
		n_read = 0;
		while (fgets (line, BUFSIZ, fp)) {
			mgd77[n_read]  = (char *) GMT_memory (VNULL, (size_t)80, sizeof (char), "mgd77togmt");
			prefix[n_read] = (char *) GMT_memory (VNULL, (size_t)80, sizeof (char), "mgd77togmt");
			if ((sscanf (line, "%s %s %d", mgd77[n_read], prefix[n_read], &year[n_read]) != (size_t)3)) {
				fprintf (stderr, "mgd77togmt: Trouble reading cecord # %d in list %s\n", n_read, list);
				exit (EXIT_FAILURE);
			}
			n_read++;
			if (n_read == n_alloc) {
				n_alloc += GMT_CHUNK;
				mgd77 = (char **) GMT_memory ((void *)mgd77, (size_t)n_alloc, sizeof (char *), "mgd77togmt");
				prefix = (char **) GMT_memory ((void *)prefix, (size_t)n_alloc, sizeof (char *), "mgd77togmt");
				year = (int *) GMT_memory ((void *)year, (size_t)n_alloc, sizeof (int), "mgd77togmt");
			}
		}
		n_files = n_read;
		fclose (fp);
		mgd77  = (char **) GMT_memory ((void *)mgd77, (size_t)n_files, sizeof (char *), "mgd77togmt");
		prefix = (char **) GMT_memory ((void *)prefix, (size_t)n_files, sizeof (char *), "mgd77togmt");
		year = (int *) GMT_memory ((void *)year, (size_t)n_files, sizeof (int), "mgd77togmt");
	}
	else {
		mgd77  = (char **) GMT_memory (VNULL, (size_t)1, sizeof (char *), "mgd77togmt");
		prefix = (char **) GMT_memory (VNULL, (size_t)1, sizeof (char *), "mgd77togmt");
		year = (int *) GMT_memory (VNULL, (size_t)1, sizeof (int), "mgd77togmt");
		mgd77[0]  = (char *) GMT_memory (VNULL, (size_t)80, sizeof (char), "mgd77togmt");
		prefix[0] = (char *) GMT_memory (VNULL, (size_t)80, sizeof (char), "mgd77togmt");
		strcpy (mgd77[0], mfile);
		strcpy (prefix[0], legfname);
		year[0] = leg_year;
		n_files = 1;
	}
	
	n_alloc = GMT_CHUNK;
	
	for (i = 0; i < n_files; i++) {
	
		if (gmtdefs.verbose) fprintf (stderr, "mgd77togmt: Processing file %s\n", mgd77[i]);
		
		if (mgd77[i][0] == 0) {
			fp = stdin;
		}
		else if ((fp = fopen (mgd77[i], "r")) == NULL) {
			fprintf (stderr, "mgd77togmt: Unable to open file %s - skipping\n", mgd77[i]);
			GMT_free ((void *)mgd77[i]);
			GMT_free ((void *)prefix[i]);
			continue;
		}

		if (!set_agency) {	/* Use legname as agency string */
			strncpy ((void *)agency, prefix[i], (size_t)10);
			if (gmtdefs.verbose) fprintf (stderr, "mgd77togmt: Agency string set to %s\n", prefix[i]);
		}

		gmt = gmtmgg_init (year[i]);

		record = (struct GMTMGG_REC *) GMT_memory (VNULL, (size_t)n_alloc, sizeof (struct GMTMGG_REC), "mgd77togmt");

		rec = n_read = 0;
		while (fgets (line, BUFSIZ, fp)) {
			n_read++;
			if (!(line[0] == '3' || line[0] == '5')) continue;	/* Only process data records */
			if ((len = (int)strlen(line)) != 121) {
				fprintf (stderr, "mgd77togmt: Record # %d has incorrect length (%d), skipped\n", n_read, len);
				continue;
			}
			if (!gmtmgg_decode_MGD77 (line, t_flag, &record[rec], &gmt)) {
				if (t_flag) record[rec].time = (fake_running_time += T_INC);
				rec++;
			}
			else
				fprintf (stderr, "mgd77togmt: Trouble decoding record # %d (skipped)\n", n_read);
			if (rec == n_alloc) {
				n_alloc += GMT_CHUNK;
				record = (struct GMTMGG_REC *) GMT_memory ((void *)record, (size_t)n_alloc, sizeof (struct GMTMGG_REC), "mgd77togmt");
			}
		}
		if (fp != stdin) fclose (fp);
		GMT_free ((void *)gmt);
		n_records = rec;
	
		sprintf (file, "%s.gmt", prefix[i]);
		if ((fpo = fopen (file, "wb")) == NULL) {
			fprintf (stderr, "mgd77togmt: Could not create file %s\n", file);
			exit (EXIT_FAILURE);
		}
	
		if (fwrite ((void *)(&year[i]), (size_t)4, (size_t)1, fpo) != (size_t)1) {
			fprintf (stderr,"mgd77togmt: Error while writing first year\n");
			exit (EXIT_FAILURE);
		}
		if (fwrite ((void *)(&n_records), (size_t)4, (size_t)1, fpo) != (size_t)1) {
			fprintf (stderr,"mgd77togmt: Error while writing no of records\n");
			exit (EXIT_FAILURE);
		}
		if (fwrite ((void *)agency, (size_t)10, (size_t)1, fpo) != (size_t)1) {

			fprintf (stderr,"mgd77togmt: Error while writing info-header\n");
			exit (EXIT_FAILURE);
		}
		for (rec = 0; rec < n_records; rec++) {
			if (fwrite ((void *)(&record[rec]), (size_t)18, (size_t)1, fpo) != (size_t)1) {
				fprintf (stderr,"mgd77togmt: Error writing data record no %d\n",rec);
				exit (EXIT_FAILURE);
			}
		}
		fclose (fpo);
	
		GMT_free ((void *)record);
		
		GMT_free ((void *)mgd77[i]);
		GMT_free ((void *)prefix[i]);
	}
	
	GMT_free ((void *)mgd77);
	GMT_free ((void *)prefix);
	GMT_free ((void *)year);
	
	exit (EXIT_SUCCESS);
}
