/****************************************************************************
 *                                                                          *
 *     Loki - Programs for genetic analysis of complex traits using MCMC    *
 *                                                                          *
 *             Simon Heath - University of Washington                       *
 *                                                                          *
 *                       March 1997                                         *
 *                                                                          *
 * prep.c:                                                                  *
 *                                                                          *
 * Data preperation - reading control file, reading datafiles, recoding     *
 * factorial data, and writing out binary datafiles for loki                *
 *                                                                          *
 * Copyright (C) Simon C. Heath 1997, 2000, 2002                            *
 * This is free software.  You can distribute it and/or modify it           *
 * under the terms of the Modified BSD license, see the file COPYING        *
 *                                                                          *
 ****************************************************************************/

#include <config.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#ifdef USE_DMALLOC
#include <dmalloc.h>
#endif
#include <stdio.h>
#include <ctype.h>
#include <errno.h>

#include "version.h"
#include "ranlib.h"
#include "utils.h"
#include "libhdr.h"
#include "scan.h"
#include "control_parse.h"
#include "compat/compat.h"
#include "getopt.h"

unsigned int RunID;
int nrm_flag,strip_vars;
loki_time lt;
static int error_check=1;

static char *LogFile;

void print_version_and_exit(void)
{
	(void)printf("%s\n",PREP_NAME);
	exit(EXIT_SUCCESS);
}

#ifdef FUNC_NAME
#undef FUNC_NAME
#endif
#define FUNC_NAME "process_loki"
static int process_loki(int argc,char *argv[])
{
	FILE *fptr;
	int err,i,c,ec_flag=0;
	
	while((c=getopt(argc,argv,"evX:d:p:"))!=-1) switch(c) {
	 case 'e':
		error_check=0;
		ec_flag=1;
		break;
	 case 'v':
		print_version_and_exit();
		break; /* Previous command never returns */
	 case 'd':
		if((i=set_file_dir(optarg))) {
			fprintf(stderr,"Error setting default file directory: %s\n",i==UTL_BAD_STAT?strerror(errno):utl_error(i));
			exit(EXIT_FAILURE);
		}
		break;
	 case 'p':
		if((i=set_file_prefix(optarg))) {
			fprintf(stderr,"Error setting default file prefix: %s\n",utl_error(i));
			exit(EXIT_FAILURE);
		}
		break;
	 case 'X':
		fputs("-X option must occur as first argument\n",stderr);
		exit(EXIT_FAILURE);
	}
	if(optind>=argc) abt(__FILE__,__LINE__,"No control file specified\n");
	init_stuff(&LogFile);
	if((fptr=fopen(argv[optind],"r"))) err=ReadControl(fptr,argv[optind],&LogFile);
	else {
		(void)printf("Couldn't open '%s' for input as control file\nAborting...\n",argv[optind]);
		exit(EXIT_FAILURE);
	}
	(void)fclose(fptr);
	if(!err) {
		if(getseed("seedfile",0)) init_ranf(135421);
		RunID=(unsigned int)(ranf()*(double)0xffffffffU);
		if(!ec_flag) error_check=syst_var[ERROR_CHECK];
		print_start_time(PREP_NAME,"w",LogFile,&lt);
		if(!scan_error_n) ReadData(LogFile);          /* Read in the datafile(s) and recode (where necessary) */
	}
	return err;
}

#ifdef FUNC_NAME
#undef FUNC_NAME
#endif
#define FUNC_NAME "main"
int main(int argc,char *argv[])
{
	int err,type=LOKI_FORMAT;
	
	lt.start_time=time(0);
	if(argc>1) {
		if(*argv[1]=='-' && argv[1][1]=='X') {
			type=check_format(argv[1]);
			optind=2;
			optreset=1;
		}
	}
	switch(type) {
	 case LOKI_FORMAT:
		err=process_loki(argc,argv);
		break;
	 case QTDT_FORMAT:
		err=process_qtdt(argc,argv,&LogFile,&error_check,&lt);
		break;
	 default:
		fputs("Input type not yet handled\n",stderr);
		exit(EXIT_FAILURE);
	}
	if(err) {
		LogFile=0;
		exit(EXIT_FAILURE);
	}
	if(!pruned_ped_size) {
		(void)printf("Zero size pedigree\nAborting...\n");
		exit(EXIT_FAILURE);
	}
	if(!scan_error_n)	{
		InitFamilies(LogFile);
		count_loops(LogFile);
		check_inbreeding(LogFile);
		check_ymark();
	}
	if(!scan_error_n && (traitlocus || n_markers)) err=Genotype_Elimination(syst_var[CORRECT_ERRORS],LogFile,error_check);
	if(!scan_error_n && !err) nrm_flag=Calculate_NRM(LogFile);
	(void)writeseed("seedfile",1);
	if(family) free(family);
	if(!scan_error_n && !err && nrm_flag>=0) {
		WriteData(LogFile);
/*		WriteXMLData(LogFile); */
		WriteReport(LogFile);
	}
	free_nodes();
	if(scan_error_n) (void)fprintf(stderr,"Errors: %d  ",scan_error_n);
	if(scan_warn_n) (void)fprintf(stderr,"Warnings: %d  ",scan_warn_n);
	if(scan_error_n || scan_warn_n) (void)fprintf(stderr,"\n");
	return sig_caught;
}
