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

void main(int argc, char * argv[])
{
    //
    static FILE *mfile, *pfile;
    static char *matrix;
    int const maxpath = 2097152;
    static char path[2097152];
    static int rows, cols;
    int plen;

    if (argc < 3)
    {
	puts ("Usage: test matrixfile pathfile");
	exit (-1);
    }
    if (!openFiles(&mfile, &pfile, argv))
	exit (-2);
    if (!parseMatrix(mfile, &matrix, &rows, &cols))
	exit (-3);
    (void) fclose(mfile);
    dumpMatrix(matrix, rows, cols);
    if ((plen = parsePath(pfile, path, maxpath)) < 2)
    {
	puts ("Path too short");
	exit (-4);
     }
    (void) fclose(pfile);
    printf ("Path = <%s>\nlen = %d\n", path, plen);
}

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

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

int dumpMatrix(char *matrix, int rows, int cols)
{
    int curRow = 0, curCol = 0;
    char *curChar = matrix;

    for (; curRow < rows; curRow++)
    {
	for (curCol = 0; curCol < cols; curCol++)
	{
	    putchar(*curChar);
	    curChar++;
	}
	putchar('\n');
    }
    putchar('\n');
}

int parseMatrix(FILE *mfile, char **matrix, int *rows, int *cols)
{
    char firstline[200] = "no line read";
    char *workPtr;
    int size, size2;
    int conversions;
    int curRow;

    *rows = -1;
    *cols = -1;

    if (!fgets (firstline, 190, mfile))
    {
	puts ("Can't read first line in matrix file");
	return 0;
    }
    if (!index(firstline, '\n'))
    {
	puts ("First line of matrix file too long");
	return 0;
    }
    if ((conversions = sscanf (firstline, "%d%d", cols, rows)) != 2)
    {
	puts ("Error reading cols and rows in matrix file");
	puts (firstline);
	printf ("number of conversions = %d\n", conversions);
	printf ("rows = %d, cols = %d\n", *rows, *cols);
	return 0;
    }
    printf ("rows = %d, cols = %d\n", *rows, *cols);
    size = *cols * *rows;
    if (size < 0 || *rows < 1 || *cols < 1)
    {
	puts ("Error invalid column/row specification");
	return 0;
    }
    *matrix = (char *) malloc(size + 1);
    if (!*matrix)
    {
	puts ("Cant allocate mem for matrix");
	return 0;
    }
    workPtr = *matrix;
    for (curRow = 0; curRow < *rows; curRow++)
    {
	/* add 1 for newline and 1 for null char */
	if (!fgets(workPtr, (*cols)+2, mfile)) 
	{
	    printf ("Error reading row %d of matrix", curRow + 1);
	    return 0;
	}
	workPtr += *cols;
    }
    return 1;
}

int openFiles(FILE **mfile, FILE **pfile, const char *argv[])
{
    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;
}

