/*-----------------------------------------------------------------
 *	$Id: x2sys_init.c,v 1.19 2006/04/10 05:47:30 pwessel Exp $
 *
 *      Copyright (c) 1999-2006 by P. Wessel
 *      See COPYING file for copying and redistribution conditions.
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; version 2 of the License.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      Contact info: gmt.soest.hawaii.edu
 *--------------------------------------------------------------------*/
/* x2sys_init will accept command line options to specify track data
 * file formats, region of interest, bin spacing, etc, and a unique
 * system identifier.  It will then initialize the databases associated
 * with this system where information about the tracks and their
 * intersections will be stored.
 *
 * Author:	Paul Wessel
 * Date:	14-JUN-2004
 * Version:	1.1, based on the spirit of the old mgg/s_system code
 *
 */

#include "x2sys.h"

int main (int argc, char **argv)
{
	char *sfile = CNULL, *TAG = CNULL, *suffix = NULL;
	time_t right_now;
	struct X2SYS_INFO *s;
#ifndef WIN32
	struct passwd *pw;
#endif
	char tag_file[BUFSIZ], track_file[BUFSIZ], bin_file[BUFSIZ], path[BUFSIZ];

	BOOLEAN error = FALSE, geographic = FALSE, force = FALSE;

	FILE *fp = NULL;

	int n_tags = 0, i, n_found = 0, geodetic = 0, r_entry, i_entry, d_entry;
	int e_entry,  g_entry, m_entry, wd_entry, wt_entry;

	double x_min = 0.0, x_max = 0.0, y_min = 0.0, y_max = 0.0, bin_x = 0.0, bin_y = 0.0;

	r_entry = i_entry = d_entry = e_entry = g_entry = m_entry = wd_entry = wt_entry = 0;

	argc = GMT_begin (argc, argv);
	
	for (i = strlen(argv[0]); i >= 0 && argv[0][i] != '/'; i--);
	X2SYS_program = &argv[0][i+1];	/* Name without full path */

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
				/* Common parameters */

				case 'R':
					r_entry = i;
				case 'H':
				case 'V':
				case '\0':
					error += GMT_parse_common_options (argv[i], &x_min, &x_max, &y_min, &y_max);
					break;

				/* Supplemental parameters */

				case 'D':
					sfile = &argv[i][2];
					d_entry = i;
					break;
				case 'E':
					suffix = &argv[i][2];
					e_entry = i;
					break;
				case 'G':	/* Geographical coordinates, set discontinuity */
					geographic = TRUE;
					geodetic = 0;
					if (argv[i][2] == 'd') geodetic = 2;
					g_entry = i;
					break;
				case 'F':
					force = TRUE;
					break;
				case 'I':
					if (argv[i][2]) GMT_getinc (&argv[i][2], &bin_x, &bin_y);
					i_entry = i;
					break;
				case 'M':
					m_entry = i;
					break;
				case 'W':
					switch (argv[i][2]) {
						case 't':	/* Get new timegap */
							wt_entry = i;
							break;
						case 'd':	/* Get new distgap */
							wd_entry = i;
							break;
						default:
							fprintf (stderr, "%s: Syntax Error: -Wt|d<width>\n", GMT_program);
							error++;
							break;
					}
					break;
				default:
					error = TRUE;
					break;
			}
		}
		else {
			TAG = argv[i];
			n_tags++;
		}
	}

	if (argc == 1 || error || GMT_give_synopsis_and_exit) {
		fprintf (stderr, "x2sys_init %s - Initialize a new track system database\n\n", X2SYS_VERSION);
		fprintf (stderr, "usage: x2sys_init <SYSTEM> [-D<deffile>] [-E<suffix>] [-F] [-G[d/g]] [-I[<binsize>]]\n");
		fprintf (stderr, "\t[%s] [%s] [-V] [-Wt|d|n<gap>]\n\n", GMT_M_OPT, GMT_Rgeo_OPT);
		fprintf (stderr, "\t<SYSTEM> is the unique system identifier\n");

		if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);

		fprintf (stderr, "\n\tOPTIONS:\n");
		fprintf (stderr, "	-D definition file for the track data set\n");
		fprintf (stderr, "	   [Default is %s%cx2sys.def\n", X2SYS_HOME, DIR_DELIM);
		fprintf (stderr, "	-E Extension (suffix) for these data files\n");
		fprintf (stderr, "	   [Default equals the prefix for the definition file]\n");
		fprintf (stderr,"	-F Force creating new files if old ones are present [Default will abort if old files are found]\n");
		fprintf (stderr,"	-G for geographical coordinates.  Append g for discontinuity at Greenwich (output 0/360 [Default])\n");
		fprintf (stderr,"	   and append d for discontinuity at Dateline (output -180/+180)\n");
		fprintf (stderr, "	-I sets bin size for track bin index output [1/1]\n");
		GMT_explain_option ('M');
		GMT_explain_option ('R');
		fprintf (stderr, "	   [Default region is 0/360/-90/90]\n");
		GMT_explain_option ('V');
		fprintf (stderr,"	-W Set maximum gaps allowed at crossover.  Option may be repeated.\n");
		fprintf (stderr,"	   -Wt sets maximum time gap (in user units) [Default is infinite]\n");
		fprintf (stderr,"	   -Wd sets maximum distance gap (in user units) [Default is infinite]\n");
		exit (EXIT_FAILURE);
	}

	if (n_tags == 0) {
		fprintf (stderr, "%s: No system tag given!\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	if (n_tags > 1) {
		fprintf (stderr, "%s: Only give one system tag!\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	if (r_entry && (x_min >= x_max || y_min >= y_max)) {
		fprintf (stderr, "%s: -R given inconsistant values!\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	if (i_entry && (bin_x <= 0.0 || bin_y <= 0.0)) {
		fprintf (stderr, "%s: -Idx/dy must be positive!\n", GMT_program);
		exit (EXIT_FAILURE);
	}
	s = x2sys_initialize (sfile, &GMT_io);	/* Initialize X2SYS and info structure */

	if (geographic) {
		s->geographic = TRUE;
		s->geodetic = geodetic;	/* Override setting */
	}

	/* Initialize the system TAG file in X2SYS_HOME */

	sprintf (tag_file, "%s.tag", TAG);
	sprintf (track_file, "%s_tracks.d", TAG);
	sprintf (bin_file, "%s_index.b", TAG);

	if (!x2sys_access (tag_file, R_OK)) {
		fprintf (stderr,"%s: File exists: %s\n", GMT_program, tag_file);
		x2sys_path (tag_file, path);
		if (force) {
			if (remove (path))
				fprintf (stderr,"%s: Unable to remove %s\n", GMT_program, path);
			else
				fprintf (stderr,"%s: Removed file %s\n", GMT_program, path);
		}
		else 
			n_found++;
	}
	if (!x2sys_access (track_file, R_OK)) {
		fprintf (stderr,"%s: File exists: %s\n", GMT_program, track_file);
		x2sys_path (track_file, path);
		if (force) {
			if (remove (path))
				fprintf (stderr,"%s: Unable to remove %s\n", GMT_program, path);
			else
				fprintf (stderr,"%s: Removed file %s\n", GMT_program, path);
		}
		else 
			n_found++;
	}
	if (!x2sys_access (bin_file, R_OK)) {
		fprintf (stderr,"%s: File exists: %s\n", GMT_program, bin_file);
		x2sys_path (bin_file, path);
		if (force) {
			if (remove (path))
				fprintf (stderr,"%s: Unable to remove %s\n", GMT_program, path);
			else
				fprintf (stderr,"%s: Removed file %s\n", GMT_program, path);
		}
		else 
			n_found++;
	}
	if (n_found) {
		fprintf (stderr,"%s: Remove/rename old files or use -F to overwrite\n", GMT_program);
		exit (EXIT_FAILURE);
	}


	if (gmtdefs.verbose) fprintf (stderr, "%s: Initialize %s\n", GMT_program, tag_file);
	if ((fp = x2sys_fopen (tag_file, "w")) == NULL) {
		fprintf (stderr,"%s: Could not open file %s\n", GMT_program, tag_file);
		exit (EXIT_FAILURE);
	}

        right_now = time ((time_t *)0);
	fprintf (fp, "# TAG file for system: %s\n", TAG);
	fprintf (fp, "#\n# Initialized on: %s", ctime (&right_now));
#ifndef WIN32
	if ((pw = getpwuid (getuid ())) != NULL)
		fprintf (fp, "# Initialized by: %s\n#\n", pw->pw_name);
	else
#endif
		fprintf (fp, "# Initialized by: unknown\n#\n");
	(d_entry) ? fprintf (fp, "%s", argv[d_entry]) : fprintf (fp, "-Dx2sys");
	if (e_entry) fprintf (fp, " %s", argv[e_entry]);
	if (g_entry) fprintf (fp, " %s", argv[g_entry]);
	if (m_entry) fprintf (fp, " %s", argv[m_entry]);
	if (wt_entry) fprintf (fp, " %s", argv[wt_entry]);
	if (wd_entry) fprintf (fp, " %s", argv[wd_entry]);
	(i_entry) ? fprintf (fp, " %s", argv[i_entry]) : fprintf (fp, " -I1/1");
	(r_entry) ? fprintf (fp, " %s", argv[r_entry]) : fprintf (fp, " -R0/360/-90/90");
	fprintf (fp, "\n");
	x2sys_fclose (tag_file, fp);

	/* Initialize the system's tracks data base  */

	if (gmtdefs.verbose) fprintf (stderr, "%s: Initialize %s\n", GMT_program, track_file);
	if ((fp = x2sys_fopen (track_file, "w")) == NULL) {
		fprintf (stderr, "%s: Could not find %s\n", GMT_program, track_file);
		exit (EXIT_FAILURE);
	}
	x2sys_fclose (track_file, fp);

	/* Initialize the system's index data base  */

	if (gmtdefs.verbose) fprintf (stderr, "%s: Initialize %s\n", GMT_program, bin_file);
	if ((fp = x2sys_fopen (bin_file, "wb")) == NULL) {
		fprintf (stderr,"%s: Could not open %s\n", GMT_program, bin_file);
		exit (EXIT_FAILURE);
	}
	x2sys_fclose (bin_file, fp);

	/* Initialize the system's crossover data base  */

	if (gmtdefs.verbose) fprintf (stderr, "%s: Crossover data base initialization not implemented yet\n", GMT_program);
	/* NOT IMPLEMENTED YET */

	if (gmtdefs.verbose) fprintf (stderr, "%s completed successfully\n", GMT_program);

	GMT_end (argc, argv);

	exit (EXIT_SUCCESS);
}
