#!/usr/bin/env python

def templatematches(a, b):
  aseen = {}
  bseen = {}
  for n, c in enumerate(a):
    d = b[n]
    if c in aseen:
      if not d == b[aseen[c]]:
        return False
    else:
      if d in bseen:
        return False
    aseen[c] = n
    bseen[d] = n
  return True

def makemapping(a, b, mappedsofar):
  mapping = mappedsofar.copy()
  for n, c in enumerate(a):
    if c in mapping:
      if mapping[c] != b[n]:
        return None
    else:
      mapping[c] = b[n]
  return mapping

def recurseoptions(matchwords, alloptions, mappedletters={}):
  cryptword = matchwords[0]
  options = alloptions[0]
  mappingsfound = []
  for plainword in options:
    mapping = makemapping(cryptword, plainword, mappedletters)
    if mapping is not None:
      if len(matchwords) > 1:
        pmappings = recurseoptions(matchwords[1:], alloptions[1:], mapping)
      else:
        pmappings = [mapping]
      if pmappings is not None:
        mappingsfound.extend(pmappings)
  if mappingsfound:
    return mappingsfound
  else:
    return None

if __name__ == "__main__":
  import sys
  teststring = "jkdf ertjgdd wer k opogl ssfd"
  testwords = teststring.split()
  testwordlens = {}
  for word in testwords:
    testwordlens[len(word)] = True
  dictwords = [line.strip().lower() for line in open(sys.argv[1], 'r').readlines()]
  dictwords.append('a')
  dictwords.append('i')
  dictwordlens = dict([(wordlen, filter(lambda word: len(word) == wordlen, dictwords)) for wordlen in testwordlens])
  possiblewords = {}
  for wordnum, cryptword in enumerate(testwords):
    possiblewords[wordnum] = []
    for plainword in dictwordlens[len(cryptword)]:
      if templatematches(cryptword, plainword):
        possiblewords[wordnum].append(plainword)
  optioncount = [(len(possiblewords[wordnum]), wordnum) for wordnum in range(len(testwords))]
  optioncount.sort()
  options = [possiblewords[wordnum] for wordcount, wordnum in optioncount]
  cryptwords = [testwords[wordnum] for wordcount, wordnum in optioncount]
  mappingsfound = recurseoptions(cryptwords, options)
  if not mappingsfound:
    print "impossible"
  else:
    for mapping in mappingsfound:
      umapping = dict([(ord(unicode(a)), unicode(b)) for a, b in mapping.iteritems()])
      print unicode(teststring).translate(umapping)

