#!/usr/bin/python
# -*- coding: utf-8 -*-

# --------------------------------------------------
# File Name: dtw.py
# Purpose:
# Creation Date: 10-03-2017
# Last Modified: Fri, Apr 21, 2017 10:01:08 AM
# Author(s): Mike Stout 
# Copyright 2017 The Author(s) All Rights Reserved
# Credits: 
# --------------------------------------------------


import sys
from mlpy import dtw_subsequence, dtw_std

import numpy as np


import mlpy
import matplotlib.pyplot as plt
import matplotlib.cm as cm

def read(a):
    with open(a) as f:
     #s= f.readlines()
     s= f.read()
    return s

m = int(sys.argv[1])
n = int(sys.argv[2])
f1 = sys.argv[3]
f2 = sys.argv[4]
gapChar = sys.argv[5]

lc = 'abcdefghijklmnopqrstuvwxyz'
lc_lut = [ (a, i) for i,a in enumerate(lc) ] 
uc_lut = [ (a.upper(), i) for a,i in lc_lut ]
lut = dict( lc_lut + uc_lut  ) 

#def encode(c): return ord(c.lower())*200

def encode(c):
    try: val = lut[c.lower()]
    except: val = ord(c)  * 2.
    return val

def zscore(xs):
    xs = np.array(xs) 
    mean = np.mean(xs)
    var = np.var(xs)
    return (xs-mean) / var

x = read(f1)[m:n]
x_ = map(encode, x)
#x_ = zscore(x_)

y = read(f2)[m:n]
y_ = map(encode, y)
#y_ = zscore(y_)

_,__,path = dtw_std(x_ ,y_, dist_only=False) 
#_, __, path = dtw_subsequence(x_ ,y_)


def splits(n, f, xs):
    return [ f+":\t" + xs[i:i+n] for i in range(0, len(xs), n)]

def fix(n, xs, i, path):
    if n==0: 
        if i<len(path)-1 and path[i]==path[i+1]: return gapChar
        else: return xs[path[i]]
    else:
        if i>0 and path[i]==path[i-1]: return gapChar
        else: return xs[path[i]]
    

def recover(xs, path, n):
    return ''.join([ fix(n, xs, i, path[n]) for i in xrange(len(path[n]))]).replace("\n"," ")


x__ = recover(x,path,0)
y__ = recover(y,path,1)

with open("a_",'w') as f:  f.write(x__)
with open("b_",'w') as f:  f.write(y__)

n = 200 
aa = splits(n, f1, x__)
bb = splits(n, f2, y__)

zz = [ "\n"+a+"\n"+b for a,b in zip(aa,bb) ]

for z in zz: print z