#     Albert Gural, Grade 11

#     Thomas Jefferson High School for Science and Technology

#     Senior Division

#     Contest#4 2010-2011

#     "ACSL Matrix Encryption"

#     04/10/11

 

def cross(m1,m2):             # Assumes encoding matrix m1 is a 2x2 matrix, and m2 is a 2-array

      return [m1[0][0]*m2[0]+m1[0][1]*m2[1],m1[1][0]*m2[0]+m1[1][1]*m2[1]]

def inv_cross(m1,m2):   # Assumes decoding matrix m1 is a 2x2 matrix, and m2 is a 2-array

      e = (m1[0][0]*m1[1][1]-m1[0][1]*m1[1][0])

      if e == 0: print "Encoding Matrix Not Valid: No inverse matrix."

      a,b,c,d = m1[1][1], -m1[0][1], -m1[1][0], m1[0][0]

      while a % e != 0: a += 27

      while b % e != 0: b += 27

      while c % e != 0: c += 27

      while d % e != 0: d += 27

      return cross([[(a/e),(b/e)],[(c/e),(d/e)]],m2)

def to_int(c):

      if c == ' ': return 27

      else: return ord(c)-64

def to_chr(i):

      i = int(round(i))

      if i % 27 == 0: return ' '

      else: return chr((i % 27)+64)

 

f = open("acsl4.in")   

for line in f:

      try:

            strn,res,act,message,key = "", [], True if (line.split(',')[0]=='E') else False, line.split(',')[1].upper(), [[int(line.split(',')[2]),int(line.split(',')[3])],[int(line.split(',')[4]),int(line.split(',')[5])]]

            if len(message) % 2 == 1: message += ' '

            for i in range(len(message)/2):

                  if act:     res += cross(key,[to_int(message[2*i]),to_int(message[2*i+1])])

                  else: res += inv_cross(key,[to_int(message[2*i]),to_int(message[2*i+1])])

                  strn += to_chr(res[2*i]) + to_chr(res[2*i+1])

            print strn

      except: print "Bad Input or File Not Found.  Please check the file to make sure input is formatted properly.  Note that the encoding matrix must have a valid inverse (a*d != b*c)."