# Robert Cooper
# 9-15-2017
# This script removes residual distortion from a strip-registered dataset.
# It requires:
#    * A *functioning* MATLAB runtime, that has been set up to link to Python (optional).
#    * The .dmp file output from Alfredo Dubra's Demotion software suite. **I realize this makes it VERY specific-
#      I do not promise any amazing things happening as result of using this software!**
#    * The 'mat' file corresponding to the grid calibration- also using Alf Dubra's script.
#    * The dataset you wish to put through the temporal analysis pipeline.
#
#

try:
    import matlab.engine # This needs to be imported first for some stupid reason.
except:
    import Tkinter as tk
    import Tkconstants, tkFileDialog, tkMessageBox
    import os, sys, ctypes
    import subprocess
    import socket
    
    options = {}
    options['title'] = 'Please select your [MATLABROOT]\extern\engines\python folder to link to MATLAB.'
    matlab_folder_path = tkFileDialog.askdirectory(**options)

    ctypes.windll.shell32.ShellExecuteW(None, u"runas",  unicode("C:\\Python27\\python.exe"), u"setup.py install", unicode(matlab_folder_path), 1)   

    try:
        import matlab.engine
    except:
        tkMessageBox.showerror("Linking (should be) successful!", "If the console did not display any errors, then linking successful! Please restart this script.")
        sys.exit(0)

import os, pickle
import Tkinter as tk
import Tkconstants, tkFileDialog, tkMessageBox
import numpy as np

root = tk.Tk()

try:
    mat_engi = matlab.engine.start_matlab()
except:
    tkMessageBox.showerror("Unable to start MATLAB! Ensure you have a valid copy of MATLAB installed AND it has been linked with python.")
    quit(1)


options = {}
options['title'] = 'Select the DESINUSOID FILE:'
options['parent'] = root
options['filetypes'] = [("MAT File", ".mat")]

desinsoid_file = tkFileDialog.askopenfilename(**options)

static_distortion = mat_engi.Static_Distortion_Repair(desinsoid_file)

just_the_dir = os.path.split(desinsoid_file)[0]

options = {}
options['title'] = 'Select the folder containing the DMP files:'
options['parent'] = root
options['initialdir'] = just_the_dir

dmp_folder_path = tkFileDialog.askdirectory(**options)

options = {}
options['title'] = 'Select the folder containing the IMAGE or MOVIE files:'
options['parent'] = root
options['initialdir'] = dmp_folder_path

image_folder_path = tkFileDialog.askdirectory(**options)

stimend = 38
stimbegin = 3

# progo = ttk.Progressbar(root, length=len(os.listdir(dmp_folder_path)))
# progo.pack()
fixed_images = []
THEpath = ""

for thisfile in os.listdir(dmp_folder_path):
    if thisfile.endswith(".dmp"):

        try:
            pickle_path = os.path.join(dmp_folder_path, thisfile)

            # Fix the fact that it was done originally in Windows...
            pickle_file = open(pickle_path, 'rb')
            text = pickle_file.read().replace('\r\n', '\n')
            pickle_file.close()

            pickle_file = open(pickle_path, 'wb')
            pickle_file.write(text)
            pickle_file.close()

            pickle_file = open(pickle_path, 'r')