#include <stdio.h>
#include <ctype.h>

#define MAX_LINES 60
#define MAX_IN_LINE 60
#define MAX_WORD_LENGTH 100

char layout[ MAX_LINES + 1 ][ MAX_IN_LINE + 1 ];
int   numlines;


int scanword( char* word )
{
    int x;
    int y;
    int c;
    
    if ( *word == ' ' || *word == '\r' || *word == '\n' || *word == 0 )
        return 0;

    if ( isupper( *word ) ) {
        c = '@';
    }
    else {
        c = *word;
    }

    for ( y = 0 ; y < MAX_LINES ; y++ ) {
         for ( x = 0 ; x < MAX_IN_LINE ; x++ ) {
              if ( layout[ y ][ x ] == c )
                  break;
         }
         if ( x < MAX_IN_LINE )
             break;
    }

    if ( y == MAX_LINES )
        return 0;

    if ( ! isupper( *word ) )
        word++;

    while ( *word && *word != ' ' && *word != '\n' ) {
        char c;

        c = tolower( *word );
        if ( 2 < x && layout[ y ][ x - 2 ] == c ) {
            x -= 2;
        }
        else if ( layout[ y ][ x + 2 ] == c ) {
            x += 2;
        }
        else if ( 0 < y && 0 < x && layout[ y - 1 ][ x - 1 ] == c ) {
            x--;
            y--;
        }
        else if ( 0 < y && layout[ y - 1 ][ x + 1 ] == c ) {
            x++;
            y--;
        }
        else if ( layout[ y + 1 ][ x + 1 ] == c ) {
            x++;
            y++;
        }
        else if ( 0 < x && layout[ y + 1 ][ x - 1 ] == c ) {
            x--;
            y++;
        }
        else {
            break;
        }
        
        word++;
    }

    return ! ( *word && *word != ' ' && *word != '\n' );
}


int main( int argc, char** argv )
{
    FILE* l;
    int   i;
    char  word[ MAX_WORD_LENGTH ];

    if ( argc != 2 ) {
        fprintf( stderr, "count layout\n" );
        return 3;
    }

    l = fopen( argv[ 1 ], "r" );

    if ( l == NULL ) {
        fprintf( stderr, "Cannot open %s\n", argv[ 1 ] );
        return 4;
    }

    for ( i = 0 ; i < MAX_LINES ; i++ ) {
         char *p;
         int  j;

         if ( NULL == fgets( layout[ i ], MAX_IN_LINE - 1, l ) )
             break;

         p = layout[ i ];

         while ( *p ) {
             if ( *p == '\n' || *p == '\r' )
                 *p = '_';
             if ( *p == ' ' && !( p[ 1 ] == ' ' && 0 < p - layout[ i ] && p[ -1 ] == ' ' ) )
                 *p = '_';
             p++;
         }

         while ( p - layout[ i ] < MAX_IN_LINE - 1 ) {
             *p++ = '_';
         }
         *p++ = 0;
         fprintf( stderr, "%s\n", layout[ i ] );
    }

    numlines = i;

    fclose( l );

    while ( NULL != gets( word ) ) {
        if ( scanword( word ) )
            puts( word );
    }
}
