#include "utility.h"
#include <stdio.h>


void printUsage()
{ 
	printf("Usage is -n ncov -l listFile -tt testThreshold -o outputPrefix\n");
	printf("\t-n Number of Covariates (default: 1, range from 1 to 5)\n" );
	printf("\t-i Input File List (default )\n");
	printf("\t-tt Statistics Test Threshold (default: 30.0)\n");
	printf("\t-o Output File's Prefix (default:"")");
	printf("Example : \n");
	printf("\tGBOOST2 -n .\\filenamelist.txt -tt 40 -o output \n\n");
}


int main(int argc, char **argv)
{
	char* inputfilename = "filenamelist.txt";
	bool validInputFile = false;

	char* outputfileprefix = "";
	bool validOutputfileprefix = false;

	int numofCov = 1;
	bool validNumofCov = false;

	float testThreshold = 30.0;
	bool validTestThreshold = false;

	printf("\n");


	for (int i = 1; i < argc; i++) {
		if (i + 1 != argc) // Check that we haven't finished parsing already
		{
			// Check for input list file
			if (strcmp(argv[i], "-i") == 0) {
				if (i + 1 != argc) {
					inputfilename = argv[i + 1];
					if (fopen(inputfilename, "r+") != NULL) {
						validInputFile = true;
					}
					else {
						printf("Unable to open the file : %s\n\n", inputfilename);
					}
				}
				else {
					printf("No input file\n\n");
				}
			}

			//check for number of covariate
			//parse the number of covariate
			if (strcmp(argv[i], "-n") == 0) {
				if (i + 1 != argc) {
					if (EOF == sscanf(argv[i + 1], "%d", &numofCov))
					{
						// parse error 
					}
					else {
						if (numofCov<=5 && numofCov>=1)
							validNumofCov = true;
					}
				}
			}
		}
	}

	if (!(validInputFile && validNumofCov)) {
		printUsage();
		exit(0);
	}

	for (int i = 1; i < argc; i++) {
		if (i + 1 != argc) // Check that we haven't finished parsing already
		{

			// Parse the test threshold value
			if (strcmp(argv[i], "-tt") == 0) {
				if (i + 1 != argc) {
					if (EOF == sscanf(argv[i + 1], "%f", &testThreshold))
					{
						// parse error 
					}
					else {
						validTestThreshold = true;
					}
				}

				if (!validTestThreshold) {
					printf("Unable to parse test threshold value. Using %f as the default screen threshold value\n\n", testThreshold);
				}
			}

			
			// Parse output prefix
			if (strcmp(argv[i], "-o") == 0) {
				if (i + 1 != argc) {
					outputfileprefix = argv[i + 1];
				}
				else {
					printf("Unable to parse outputPrefix. Outputs files without prefixs.\n\n");
				}
			}
		}
	}

	printf("Input File List: %s\n", inputfilename);
	printf("Number of Covariates: %d\n", numofCov);
	printf("Test Threshold: %f\n", testThreshold);
	printf("Output Prefix: %s\n\n", outputfileprefix);

	fflush(stdout);
	
	return GBOOST2(inputfilename, outputfileprefix, numofCov, testThreshold);
}