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

/* program to substitution encipher.
   burt rosenberg, 25 aug 2004
*/

#define NUM_LET 26 
int SubKey [NUM_LET] ;
int SubInvKey [NUM_LET] ;
int * key ;

char applySubstitution( char letter ) 
{
  char c ;
  c = letter ;
  if (isalpha(letter)) {
    if (isupper(letter))
       c = key[letter-'A'] + 'A' ;
    else
       c = key[letter-'a'] + 'a' ;
  }
  return (c) ;
}

void initSubstitution( char * keyword, int direction )
{
  char * p ;
  int i ;
  int j ;
  for ( i=0; i<NUM_LET; i++ ) SubInvKey[i] = -1 ;

  p = keyword ;
  i = 0 ;
  while (*p!='\0') {
    if (isalpha(*p)) {
      if (isupper(*p))
        j = *p -'A' ;
      else
        j = *p -'a' ;
      if ( SubInvKey[j]==-1 ) {
        SubInvKey[j] = i ;
        SubKey[i++] = j ;
      }
    }
    p++ ;
  }

  /* fill in rest of key */
  for ( j=0; i<NUM_LET; j++ ) {
    if ( SubInvKey[j]==-1 ) {
       SubInvKey[j] = i ;
       SubKey[i++] = j ;
    }
  }

  if ( direction==1 ) 
    key = SubKey ;
  else
    key = SubInvKey ;

}

int
main( int argc, char * argv[] )
{
  char c ;
  int keyword = 1 ;
  int direction = 1 ; 
                 
  if (argc<2) {
    printf("usage: %s [-e|-d] keyword\n", argv[0] ) ;
    exit(1) ;
  }

  if ( argc>2 && *argv[1]=='-' ) switch ( *(argv[1]+1) ) {
    case 'e':
       direction = 1 ;
       keyword = 2 ;    
       break ;
    case 'd':
       direction = -1 ;
       keyword = 2 ;      
       break ;
    default :
       printf("usage: %s [-e|-d] keyword\n", argv[0] ) ;
       exit(1) ;
  }

  initSubstitution( argv[keyword], direction ) ;

  c = getc(stdin) ;
  while (c!=EOF) {
    putchar(applySubstitution( c )) ;
    c = getc(stdin) ;
  }
               
}
