/* Problem 7--Maze Checking and Visualization
   The code that reads in the input data can be cannibalized from
   Problem 3.  This was pretty straightforward, though it is important
   to double check to make sure the maze is drawn exactly correctly.
   It is important to observe, as well, that the sample input and sample
   output data given in the problem do not match each other! */

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv);
void Initialize (void);
void Process (void);

FILE *in, *out;
int r, c, M[20][20], mct=0;

int main (int argc, char **argv) {

 in = fopen ("prob7.in","r");
 out = fopen ("prob7.out","w");
 while (1) {
  fscanf (in,"%d %d",&r,&c);
  if (r==0 && c==0) break;
  Initialize ();
  Process ();
 }
 fclose (in);
 fclose (out);
 return EXIT_SUCCESS;
}

/* Initialize reads in the maze information, converting the hex numbers
   into integers. */
void Initialize (void) {

  int i, j;
  char ch;

 mct++;
 for (i = 0; i < r; i++)
  for (j = 0; j < c; j++) {
   fscanf (in," %c",&ch);  /*Read the char skipping prev whitespace */
   if (ch >= '0' && ch <= '9') M[i][j] = ch-'0';
   else M[i][j] = ch-'A'+10; /*converting letters to numbers*/
  }
}

/* Process draws the maze. */
void Process (void) {

  int i, j;

 fprintf (out,"Maze %d:\n\n",mct);
 for (j = 0; j < c; j++)
  fprintf (out,M[0][j]%2 ? "+   " : "+---"); /* top row */
 fprintf (out,"+\n");
 for (i = 0; i < r; i++) {
  fprintf (out,(M[i][0]>>3)%2 ? "    " : "|   ");
  for (j=0; j < c-1; j++)
   if ((M[i][j]>>1)%2 == (M[i][j+1]>>3)%2)
    fprintf (out,(M[i][j]>>1)%2 ? "    " : "|   "); /* good col */
   else
    fprintf (out,"X   ");  /* bad col */
  fprintf (out,(M[i][c-1]>>1)%2 ? " \n" : "|\n");
  for (j=0; j < c; j++)
   if (i==r-1 || (M[i][j]>>2)%2 == (M[i+1][j]%2))
    fprintf (out,(M[i][j]>>2)%2 ? "+   " : "+---"); /* good row */
   else
    fprintf (out,"+xxx");  /* bad row */
  fprintf (out,"+\n");
 }
 fprintf (out,"\n");
}
