/**************************************************************************
* cli.c:	The command-line interface for MP.
*		Part of MP, the MIDI Playground.
*
* Author:	Daniel Barrett
* Version:	See the file "version.h".
* Copyright:	None!  This program is in the Public Domain.
*		Please share it with others.
***************************************************************************/

	
#include "mp.h"


/* The main program from the CLI.  Check the command-line arguments, set
 * up the input and output files, and call MIDIPlayground(). */
	
BOOL CommandLineProgram(int argc, char *argv[])
{
	FILE *in, *out;
	char *infile, *outfile;
	FLAGS theFlags[NUM_FLAGS];
	
	InitStuff(theFlags, &in, &out, &infile, &outfile);

	if ((argc == 1)   ||   (argc == 2 && !strcmp(argv[1], "?")))
		Help(argv[0]);
	else if (!HandleOptions(argc, argv, theFlags, &infile, &outfile))
	{
		fprintf(stderr, "There is an error in your options/flags.\n");
		BegForUsage(argv[0]);
	}
	else if (!SetupFiles(infile, outfile, &in, &out))
		;
	else if (optind < argc)
	{
		fprintf(stderr, "You gave me too many arguments.\n");
		BegForUsage(argv[0]);
	}
	else
		(void)MIDIPlayground(theFlags, in, out);

	CloseFiles(in, out, infile, outfile);
}

	
/************************************************************************
* Handling command-line options.
************************************************************************/

BOOL HandleOptions(int argc, char *argv[], FLAGS theFlags[], char **infile,
		   char **outfile)
{
	int c;
	BOOL success = TRUE;
	static char options[] = GETOPT_OPTIONS;
	
	while ((c = getopt(argc, argv, options)) != EOF)
	{
		switch (c)
		{
		  case OPT_INPUT:
		     success &= !theFlags[FLAG_ITYPE];
		     success &= CheckIOType(*optarg, FLAG_ITYPE, theFlags);
		     break;
		  case OPT_OUTPUT:
		     success &= !theFlags[FLAG_OTYPE];
		     success &= CheckIOType(*optarg, FLAG_OTYPE, theFlags);
		     break;
		  case OPT_INFILE:
		     success &= (optarg[0] != '\0');
		     success &= MakeFilename(infile, optarg);
		     break;
		  case OPT_OUTFILE:
		     success &= (optarg[0] != '\0');
		     success &= MakeFilename(outfile, optarg);
		     break;
		  case OPT_SYSEX:
		     success &= !theFlags[FLAG_SYSEX];
		     theFlags[FLAG_SYSEX]++;
		     break;
		  default:
		     success = FALSE;
		     break;
		}
	}
	return(success && CheckFlags(theFlags));
}

	
