#!/usr/bin/perl

if (2 != (scalar @ARGV) and 1 != scalar @ARGV) {
  print STDERR "Usage: showgrid.pl <grid> <answers>\n";
  print STDERR "Usage: showgrid.pl <grid> (answers from STDIN)\n";
  print STDERR "Usage: search.pl <words> <grid> | showgrid.pl <grid>\n";
  exit;
}

$grid_file = $ARGV[0];

open GRID, "<$grid_file";
@grid = <GRID>;
close GRID;
chomp @grid;

if (2 == scalar @ARGV) {

  $data_file = $ARGV[1];

  open DATA, "<$data_file";
  @datalist = <DATA>;
  close DATA;
} else {
  @datalist = <STDIN>;

}

chomp @datalist;

%southlink;
%eastlink;
%southeastlink;
%crosslink;
%value;
%used;

$row = 0;
$width = 0;
foreach (@grid) {
  $col = 0;
  foreach (split('')) {
    $value{$row}{$col} = lc $_;
    $col++;
    $width = $col if ($col > $width);
  }
  $row++;
}
$height = $row;

foreach (@datalist) {
  substr($_,0,1) = '' if (substr($_,0,1) eq ' ');
  ($dir,$r,$c,$text) = split(/ +/);
  --$r;
  --$c;
  for (1..(length $text)) {
    $used{$r}{$c} = 1;
    if ($dir eq 'SE') {
      $southeastlink{$r}{$c} = 1 if ($_ != length $text);
      ++$r;
      ++$c;
    } elsif ($dir eq 'NW') {
      --$r;
      --$c;
      $southeastlink{$r}{$c} = 1 if ($_ != length $text);
    } elsif ($dir eq 'SW') {
      ++$r;
      --$c;
      $crosslink{$r-1}{$c} = 1 if ($_ != length $text);
    } elsif ($dir eq 'NE') {
      --$r;
      ++$c;
      $crosslink{$r}{$c-1} = 1 if ($_ != length $text);
    } elsif ($dir eq 'S') {
      $southlink{$r}{$c} = 1 if ($_ != length $text);
      ++$r;
    } elsif ($dir eq 'N') {
      --$r;
      $southlink{$r}{$c} = 1 if ($_ != length $text);
    } elsif ($dir eq 'E') {
      $eastlink{$r}{$c} = 1 if ($_ != length $text);
      ++$c;
    } elsif ($dir eq 'W') {
      --$c;
      $eastlink{$r}{$c} = 1 if ($_ != length $text);
    }
  }
}

foreach $row (0..($height-1)) {
  foreach $col (0..($width-1)) {
    print (($value{$row}{$col} eq '') ? ' ' :
           ($used{$row}{$col}) ? (uc $value{$row}{$col}) : 
                                   $value{$row}{$col}) ;
    print (($eastlink{$row}{$col}) ? '-' : ' ');
  }
  print "\n";
  foreach $col (0..($width-1)) {
    print (($southlink{$row}{$col}) ? '|' : ' ');
    if ($southeastlink{$row}{$col}) {
      if ($crosslink{$row}{$col}) {
        print 'X';
      } else {
        print '\\';
      }
    } else {
      if ($crosslink{$row}{$col}) {
        print '/';
      } else {
        print ' ';
      }
    }
  }
  print "\n";
}
print "\n";

