#!/bin/dev/python
# --*--coding:UTF-8--*--

from decimal import Decimal
import re

def verifMatrix(inv):
# verif : (ad-bc) %2 == 1 and pas multiple de 13
	res = False
	if (inv %2) == 1 :
		if (inv %13) != 0 :
			res = True
	return res

def inverse(k,mod):
    l=[i for i in range(mod) if i%2==1 and i!=13]
    res = 0
    for i in l:
        r=(k*i)%mod
        if r == 1:
            res = i
    return res

## coef pour inverser matrice
def dett(m):
	inversible = ((m[0][0]*m[1][1])-(m[0][1]*m[1][0]))
	return inversible

def strToList(string,step):
    return [string[w:w+step] if len(string[w:w+step])==step else string[w:w+step]+"X"*(step-len(string[w:w+step])) for w in range(0,len(string),step)]

def lettre(dico,id):
    return dico.keys()[dico.values().index(id)]

## matrice inverse
def minv(m, inv):
	a,b,c,d=m[0][0],m[0][1],m[1][0],m[1][1]
	res=[[(d*inv)%26,(-b*inv)%26],[(-c*inv)%26,(a*inv)%26]]
	return res

### declaration des variables ########################
alpha=list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
dico={"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26}

cipher1="QEGQE YWAU EZDM KQWPVQWY IWLBGFF JU DHXLY JFM NTUQDJX PJ AZC FZ WS LTP CQC" # 0.54 jlhq
######## comme quoi avec quelques efforts on finit par toucher au but ne me dis pas
cipher2="QEGQ"
cipher7="DO OVWE MV RK EPGW OVWE WF WNCORWIIER KFTOPO KP AO OVOS MSKNKTEE MSIVGPKNCZWHB IMFXZ WF IX JAMRKMGWEE" # 0.07 vtzc
######## au fait tu as bien fait de poursuivre jusque la il faut inverser invinoveritas avant de le concatener

m1=[[9,11],[7,16]]
m7=[[21,19],[25,2]]

########## main ###################################
cipher=strToList(cipher2.replace(" ",""),2)
m=m1
mod=26
det=dett(m)
invers=inverse(det,mod)
if (verifMatrix(det) and (invers != 0)) :
	phrase=""
        phrase2=""
	matrixInv=minv(m,invers)
	a1,b1,c1,d1=matrixInv[0][0],matrixInv[0][1],matrixInv[1][0],matrixInv[1][1]
	for i in cipher:
		bm=i
		l0=ord(bm[0])-65 ## A=0
                n0=dico[bm[0]]-1
		l1=ord(bm[1])-65 ## A=0
                n1=dico[bm[1]]-1
		#l0=ord(bm[0])-64 ## A=1
		#l1=ord(bm[1])-64 ## A=1
		lettre1=(a1*l0+b1*l1)%mod
		lettre2=(c1*l0+d1*l1)%mod
                nettre1=(a1*n0+b1*n1)%mod
                nettre2=(c1*n0+d1*n1)%mod
		phrase=phrase+chr(lettre1+97)+chr(lettre2+97) ## A=0
                phrase2+=lettre(dico,nettre1+1)+lettre(dico,nettre2+1) ## A=0
	#	phrase=phrase+chr(lettre1+96)+chr(lettre2+96) ## A=1
	print matrixInv
	print chr(a1+64)+chr(b1+64)+chr(c1+64)+chr(d1+64)
	print phrase
        print phrase2