/*--------------------------------------------------------------------
 *	$Id: mgd77info.c,v 1.3 2004/08/27 21:14:39 pwessel Exp $
 *
 *    Copyright (c) 2004 by P. Wessel
 *    See README file for copying and redistribution conditions.
 *--------------------------------------------------------------------*/
/*
 * mgd77info reads one or more MGD77 files and report on the extent of
 * the file, number of data points etc.  Alternatively, it can just
 * echo out the entire MGD77 header section.
 *
 * Author:	Paul Wessel
 * Date:	26-AUG-2004
 * Version:	1.0 Based somewhat on the old gmtinfo.c
 *
 *
 */
 
#include "mgd77.h"

void count_observables (unsigned int pattern, int counter[]);

main (int argc, char **argv)
{
	int i, rec, argno, n_cruises = 0, counter[32];
	
	BOOLEAN error = FALSE, greenwich = FALSE, quick_summary = FALSE, full_summary = FALSE;
	
	char file[BUFSIZ];

	double this_dist, this_lon, this_lat, last_lon, last_lat, dx, dy, dlon, ds;
	double xmin, xmax, xmin1, xmin2, xmax1, xmax2, ymin, ymax;
	
	struct MGD77_CONTROL M;
	struct MGD77_HEADER_RECORD H;
	struct MGD77_DATA_RECORD D;
	
	FILE *fp;
	
	argc = GMT_begin (argc, argv);		/* Initialize GMT Machinery */
	
	/* Initialize MGD77 output order and other parameters*/
	
	MGD77_Init (&M, TRUE);			/* Initialize MGD77 Machinery */

	for (i =1; !error && i < argc; i++) {	/* Process input options */
		if (argv[i][0] == '-') {
			switch(argv[i][1]) {
			
				case 'V':
				case '\0':
					error += GMT_get_common_args (argv[i], NULL, NULL, NULL, NULL);
					break;
										
				case 'I':	/* Get the short list [Default] */
					quick_summary = TRUE;
					break;
					
				case 'L':	/* Get the long list */
					full_summary = TRUE;
					break;
					
				default:		/* Options not recognized */
					error = TRUE;
					break;
			}
		}
		else
			n_cruises++;
	}
	
	/* Check that the options selected are mutually consistent */
	
	if (!(full_summary + quick_summary) == 1) {
		fprintf(stderr, "%s: ERROR: Specify one of -I or -L\n", GMT_program);
		exit (EXIT_FAILURE);
	}

	if (GMT_quick || argc == 1) {	/* Display usage */
		fprintf(stderr,"usage: mgd77info <cruise(s)> [-I] [-L]] [-V]\n\n");
         
		if (GMT_quick) exit (EXIT_FAILURE);
              
		fprintf(stderr,"	<cruises> is one or more MGD77 legnames, e.g., 01010083 etc.\n");
		fprintf(stderr,"	OPTIONS:\n\n");
		fprintf(stderr,"	-I Give the information summary of each cruise\n");
		fprintf(stderr,"	-L Display full MGD77 header records\n");
		fprintf(stderr,"	-V verbose, report progress\n");
		exit(EXIT_FAILURE);
	}

	if (n_cruises == 0) {
		fprintf(stderr, "%s: ERROR: No cruises given\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	
	GMT_io.out_col_type[0] = GMT_IS_LON;	GMT_io.out_col_type[1] = GMT_IS_LAT;	
	if (quick_summary) printf ("#Cruise:%sID%sWest%sEast%sSouth%sNorth%sStartDate%sEndDate%sDist%snRec%stwt%sdepth%smtf1%smtf2%smag%sgobs%sfaa\n",
		gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter,
		gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter,
		gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter,
		gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter, gmtdefs.field_delimiter);

	for (argno = 1; argno < argc; argno++) {	/* Loop over all the files */
	
		if (argv[argno][0] == '-') continue;
  		if (MGD77_Get_Path (file, argv[argno], &M)) {
   			fprintf (stderr, "%s : Cannot find leg %s\n", argv[argno], GMT_program);
     			continue;
  		}
		if ((fp = GMT_fopen (file, "r")) == NULL) {
			fprintf (stderr, "%s: Could not open %s\n", file, GMT_program);
			continue;
		}

		if (gmtdefs.verbose) fprintf (stderr, "%s: Now processing cruise %s\n", GMT_program, argv[argno]);
		
		if (!MGD77_Read_Header_Record (fp, &H)) {
			fprintf (stderr, "%s: Error reading header sequence for cruise %s\n", GMT_program, argv[argno]);
			exit (EXIT_FAILURE);
		}
		if (full_summary) {
			for (i = 0; i < 31; i++) putchar ('-');
			printf (" Cruise: %8s ", argv[argno]);
			for (i = 0; i < 31; i++) putchar ('-');
			putchar ('\n');
			MGD77_Write_Header_Record_Orig (GMT_stdout, &H);
		}
		
		this_dist = this_lon = this_lat = ds = 0.0;
		xmin1 = xmin2 = 360.0;
		xmax1 = xmax2 = -360.0;
		ymin = 180.0;
		ymax = -180.0;
		rec = 0;
		greenwich = FALSE;
		memset ((void *) counter, 0, (size_t)(32 * sizeof (int)));
	
		/* Start reading data from file */
	
		while (MGD77_Read_Data_Record (fp, &D)) {		/* While able to read a data record */
		
			/* Compute accumulated distance along track (Flat Earth) */
		
			last_lon  = this_lon;
			last_lat  = this_lat;
			this_lon  = D.number[MGD77_LONGITUDE];
			this_lat  = D.number[MGD77_LATITUDE];
			if (this_lon < 0.0) this_lon += 360.0;	/* Start off with everything in 0-360 range */
			if (rec > 0) {	/* Need a previous point to calculate distance, speed, and heading */
				dlon = this_lon - last_lon;
				if (fabs (dlon) > 180.0) {
					greenwich = TRUE;
					dlon = copysign ((360.0 - fabs (dlon)), dlon);
				}
				dx = dlon * cosd (0.5 * (this_lat + last_lat));
				dy = this_lat - last_lat;
				ds = DEG2KM * hypot (dx, dy);
				this_dist += ds;
			}
			if (this_lon < 180.0) {
				xmin1 = MIN (this_lon, xmin1);
				xmax1 = MAX (this_lon, xmax1);
			}
			else {
				xmin2 = MIN (this_lon, xmin2);
				xmax2 = MAX (this_lon, xmax2);
			}
			ymin = MIN (this_lat, ymin);
			ymax = MAX (this_lat, ymax);
			
			/* COunt the number of geophysical observations, incl the residuals */
			
			count_observables (D.bit_pattern & MGD77_GEOPHYSICAL_BITS, counter);
			rec++;
		}
		GMT_fclose (fp);
		if (greenwich) {
			xmin = MAX (xmin1, xmin2);
			xmax = MIN (xmax1, xmax2);
		}
		else {
			xmin = MIN (xmin1, xmin2);
			xmax = MAX (xmax1, xmax2);
		}
		if (xmin > xmax) xmin -= 360.0;
		if (quick_summary) {
			printf ("%8s%s%8s\t", argv[argno], gmtdefs.field_delimiter, H.Cruise_Identifier);
			GMT_ascii_output_one (GMT_stdout, xmin, 0);	fprintf (GMT_stdout, "%s", gmtdefs.field_delimiter);
			GMT_ascii_output_one (GMT_stdout, xmax, 0);	fprintf (GMT_stdout, "%s", gmtdefs.field_delimiter);
			GMT_ascii_output_one (GMT_stdout, ymin, 1);	fprintf (GMT_stdout, "%s", gmtdefs.field_delimiter);
			GMT_ascii_output_one (GMT_stdout, ymax, 1);	fprintf (GMT_stdout, "%s", gmtdefs.field_delimiter);
			printf ("%4d-%2.2d-%2.2d%s%4d-%2.2d-%2.2d%s%d%s%d%s%d%s%d%s%d%s%d%s%d%s%d%s%d\n",
				H.Survey_Departure_Year, H.Survey_Departure_Month, H.Survey_Departure_Day, gmtdefs.field_delimiter,
				H.Survey_Arrival_Year, H.Survey_Arrival_Month, H.Survey_Arrival_Day, gmtdefs.field_delimiter, irint (this_dist), gmtdefs.field_delimiter, rec,
				gmtdefs.field_delimiter, counter[10], gmtdefs.field_delimiter, counter[11], gmtdefs.field_delimiter,
				counter[14], gmtdefs.field_delimiter, counter[15], gmtdefs.field_delimiter,
				counter[16], gmtdefs.field_delimiter, counter[20], gmtdefs.field_delimiter, counter[22]);
		}
	}
	if (full_summary) {
		for (i = 0; i < 80; i++) putchar ('-');
		putchar ('\n');
	}
		
	exit (EXIT_SUCCESS);
}

void count_observables (unsigned int pattern, int counter[])
{
	int i;
	unsigned bit;
	
	for (i = 0; i < 32; i++) {
		bit = 1 << i;
		if (pattern & bit) counter[i]++;
	}
}

