/***************************************** 
** File: amazing.c
** Author: Marie desJardins
** Date: 10/31/06
** E-Mail: mariedj@cs.umbc.edu 
** 
** Contains code for searching a maze.
*****************************************/ 

#include <stdio.h>
#include <stdlib.h>
#include "amazing.h"
#include "2darray.h"

/***************************************** 
 * Function: PrintMaze
 * Usage: PrintMaze (maze, numRows, numCols)
 * 
 * Prints a maze (array of characters) to the screen.
 *
 * Input: a maze (2D array of chars) and its dimensions
 * Output: none
*****************************************/

void PrintMaze (char **maze, int numRows, int numCols) {
  int i, j;

  for ( i=0 ; i < numRows ; i++ ) {
    for ( j=0 ; j < numCols ; j++ ) {
      printf ("%c", maze[i][j]);
    }
    printf ("\n");
  }
  printf ("\n");
}


/***************************************** 
 * Function: InBounds
 * Usage: if ( InBounds (row, col, numRows, numCols) ) ...
 * 
 * Returns TRUE if an row,col position is inside the array
 * bounds for a numRows x numCols array, and FALSE otherwise
 *
 * Input: the position (row, col) and array dimensions (numRows, numCols)
 * Output: an int, TRUE or FALSE
*****************************************/

int InBounds (int row, int col, int numRows, int numCols) {
  return ( ( row >= 0 ) && ( col >= 0 ) &&
	   ( row < numRows ) && ( col < numCols ) );
}


void ReadMaze (char *file, MAZE *maze) {
  FILE *str;
  char junk[100];
  int i, j;

  if ( ! (str = fopen (file, "r") ) ) {
    fprintf (stderr, "Help! No file!\n");
    exit (-1);
  }
  fscanf (str, "%d", &maze->rows);
  fscanf (str, "%d", &maze->cols);
  fscanf (str, "%d %d", &maze->srow, &maze->scol);
  fscanf (str, "%d %d", &maze->erow, &maze->ecol);
  printf ("rows=%d, cols=%d, start=%d,%d, end=%d,%d\n",
	  maze->rows, maze->cols, maze->srow, maze->scol, 
	  maze->erow, maze->ecol);
  fgets (junk, 100, str);  /* throw away the rest of the line */

  /* Allocate space for and read in the maze */
  maze->board = GetTwoDSpace (maze->rows, maze->cols);
  for ( i=0 ; i < maze->rows ; i++ ) {
    for ( j=0 ; j < maze->cols ; j++ ) {
      fscanf (str, "%c", &maze->board[i][j]);
    }
    fgetc (str);
  }
}


int SolveMaze (MAZE *maze, int curRow, int curCol) {
  if ( ! InBounds (curRow, curCol, maze->rows, maze->cols) ) {
    return (FALSE);
  }
  if ( ( maze->board[curRow][curCol] == BLOCKED ) ||
       ( maze->board[curRow][curCol] == PATH ) ) {
    return (FALSE);
  }
  maze->board[curRow][curCol] = PATH;
  
  /* base case */
  if ( ( curRow == maze->erow ) && ( curCol == maze->ecol ) ) {
    return (TRUE);
  }

  /* recursive case */
  if ( SolveMaze (maze, curRow-1, curCol)
       || ( SolveMaze (maze, curRow+1, curCol) )
       || ( SolveMaze (maze, curRow, curCol-1) )
       || ( SolveMaze (maze, curRow, curCol+1) )
       ) {
    return (TRUE);
  }
  maze->board[curRow][curCol] = OPEN;
  return (FALSE);
}

