/* Problem 2:  Barry Peterson's Sentence Spiral
   This program reads in a sentence and prints it out in a
   counterclockwise spiral. */

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

int main (int argc, char **argv);

FILE *in, *out;

int main (int argc, char **argv) {

  char Grid[10][10], Direction, S[102];
  /* Grid is the square matrix, Direction is the direction we are
     moving, S is the input string. */
  int x, y, i, n, l; /* x and y are coordinates in the matrix */
  /* n is the dimension of the matrix */
  /* i is a loop counter, and l is the length of the input string */

 in = fopen ("prob2.in","r");
 out = fopen ("prob2.out","w");
 while (1) {
  fscanf (in,"%d ",&n);   /* get dimension of matrix */
  if (n==0) break;
  memset (Grid,0,sizeof Grid);  /* initialize */
  memset (S,' ',sizeof S); 
  fgets (S,101,in);  /* get input string */
  l = strlen (S);
  S[l] = S[l-1] = ' ';  /* make sure S is padded with spaces */
  x = n-1; y = 0; Direction = 'E';
  for (i = 0; i < n*n; i++) {  /* move through the matrix adding */
   Grid[x][y] = S[i];          /* characters, changing direction */
   switch (Direction) {        /* when we hit a boundary or part */
                               /* already used */
     case 'E': if (y==n-1 || Grid[x][y+1]!=0) {Direction = 'N'; x--;}
               else y++; break;
     case 'W': if (y==0 || Grid[x][y-1]!=0) {Direction = 'S'; x++;}
               else y--; break;
     case 'N': if (x==0 || Grid[x-1][y]!=0) {Direction = 'W'; y--;}
               else x--; break;
     case 'S': if (x==n-1 || Grid[x+1][y]!=0) {Direction = 'E'; y++;}
               else x++;
   }
  }
  for (i = 0; i < n; i++) fprintf (out,"%.*s\n",n,Grid[i]);
  fprintf (out,"\n");  /* print out the strings */
 }  
 fclose (in);
 fclose (out);
 return EXIT_SUCCESS;
}
