#include <stdio.h>
#include <strings.h> 
#include <stdlib.h>
#include "minfo.h"

int main(int argc, char * argv[])
{
    static FILE *mfile, *pfile;
    struct minfo theMatrix; // ha ha

    static char path[P_MAX];
    int plen;
    int score = -999999;

    if (argc < 3)
    {
	(void) puts ("Usage: test matrixfile pathfile");
	exit (-1);
    }
    if (!openFiles(&mfile, &pfile, argv))
	exit (-2);
    if (!parseMatrix(mfile, &theMatrix))
	exit (-3);
    (void) fclose(mfile);
    dumpMatrix(&theMatrix);
    if ((plen = parsePath(pfile, path)) < 2)
    {
	puts ("Path too short");
	exit (-4);
     }
    (void) fclose(pfile);
    (void) printf ("Path = <%s>\nlen = %d\n", path, plen);
    fflush (stdout);
    buildMinfo(&theMatrix, 1);
    score = checkPath(&theMatrix, path, plen, 1);
    (void) printf ("The score is %d\n", score);
    exit(0);
    return -1; // should never get here but gcc complains
}

int parsePath( FILE *pfile, char path[])
{
    int pathlen = 0;
    char workChar;

    while ((workChar = getc(pfile)) != EOF && pathlen < P_MAX)
	switch (workChar)
	{
	    case 'N':
	    case 'S':
	    case 'E':
	    case 'W':
		path[pathlen++] = workChar;
	}
    return pathlen;
}

int openFiles(FILE **mfile, FILE **pfile, const char *argv[])
{
    if (strcmp(argv[1], "-") == 0)
    {
	printf ("using stdin %s\n", argv[1]);
	fflush(stdout);
	*mfile = stdin;
    }
    else
    {
	printf ("Opening %s\n", argv[1]);
	*mfile = fopen (argv[1], "r");
    }
    printf ("Opening %s\n", argv[2]);
    *pfile = fopen (argv[2], "r");

    if (!*mfile || !*pfile)
    {
	puts ("Error opening files");
	if (mfile)
	    fclose (*mfile);
	if (pfile)
	    fclose (*pfile);
	return 0;
    }
    return 1;
}
