#!/usr/bin/env python

import glob  
import os.path  
import os 
import sys

inputImgDate = sys.argv[1]
execfile(inputImgDate)
inputValidImg = sys.argv[2]
execfile(inputValidImg)
masterImg = sys.argv[3]

def getDisplacements(dirs, ext):
    for directory in dirs:
        os.system('cp '+ directory + '/*' + ext + ' .')
getDisplacements(["../../disp2D_registration_master_"+masterImg+"_n_n*"], ".float")
getDisplacements(["../../disp2D_registration_master_"+masterImg+"_n_n*"], ".float.hdr")

def listdirectory(path, ext):  
    fichier=[]  
    l = glob.glob(path+'/*'+ext)  
    for i in l:  
#        if os.path.isdir(i): fichier.extend(listdirectory(i))  
#        else: 
        fichier.append(i)  
    return fichier

def convert_num2date(filename, ext):
    filename = filename.replace("/",".")
    filename = filename.replace("-",".")
    filename_tab = filename.split(".")
    new_name=[]
    for i, part in enumerate(filename_tab) :
        if (imgDate.has_key(part[1:])):
            new_name.append(imgDate[part[1:]])
            if(len(new_name) == 1):
                new_name.append("-")
    new_name.append("_pre_inv"+ext)
    return "".join(new_name)
            
def converFileNames():
    fileNames = listdirectory(".", ".float")
    for name in fileNames:
        os.rename(name, convert_num2date(name, ""))
        os.rename(name+".hdr", convert_num2date(name, ".hdr"))
converFileNames() 
   

def genRSC():
    os.system('for i in *_pre_inv; do echo "FILE_LENGTH 2520" > $i.unw.rsc; echo "WIDTH 3776">> $i.unw.rsc; done');
genRSC()

def genDXDY():
    cplxFiles = listdirectory(".", "_inv")
    for name in cplxFiles:
        os.system("cal_slc --input " + name + ".hdr --output ../DX/LN_DATA/" + name + ".unw --processing 4")
        os.system("cal_slc --input " + name + ".hdr --output ../DY/LN_DATA/" + name + ".unw --processing 5")
        os.system("cp " + name + ".unw.rsc ../DX/LN_DATA/") 
        os.system("cp " + name + ".unw.rsc ../DY/LN_DATA/") 
genDXDY()

def genInput_inv_send():
    text = "\
0.01  %  smoothing coefficient (threshold = 0.0001) \n \
1   %   remove points with large RMS misclosure  (y=0;n=1) \n \
2 %  threshold on RMS misclosure (in rad) ? \n \
2  % range and azimuth sampling ? \n \
1 % one iteration to correct unwrapping errors ? (y:0,n:1) \n \
1 % one iteration to weight interferograms with large residual? (y:0,n:1) \n \
1    %   elimination of outliers by the median ? (y=0,n=1) \n \
list_image_inv.txt \n \
0    % sort by date (0) ou by another variable (1) ? \n \
list_interfero.txt \n \
3100.   %  include interferograms with bperp lower than maximal baseline  \n \
0   % use of corrected interferograms (y:0, n:1) ? Obsolete, use 0 \n \
1   % location of interferograms (data:1, data5 :2)  Obsolete, use 1 \n \
1   % location of remaining interferograms (data:1, data5:2, or 0) Obsolete, use 1 \n \
1   %   minimal number of interferams using each image   \n \
1     % interferograms weighting so that the weight per image is the same (y=0;n=1) \n \
0.5 % maximum fraction of discarded interferograms \n \
0 %  Would you like to restrict the area of inversion ?(y=1,n=0) \n \
1 735 1500 1585  %Give four corners, lower, left, top, right in file pixel coord \n \
1  %    referencing of interferograms by bands (1) or corners (2) ? (More or less obsolete) \n \
5  %     band NW -SW(1), band SW- SE (2), band NW-NE (3), or average of three bands (4) or no referencement (5) ? \n \
1   %   Weigthing by image quality (y:0,n:1) ? (then read quality in the list of input images - colone 5, intervient dans le lissage temporel) \n \
1   %  Weigthing by interferogram variance (y:0,n:1) ? (More or less obsolete, intervient dans le r<E9>seau) \n \
1    % use of covariance (y:0,n:1) ? (Obsolete) \n \
0   % include a baseline term in inversion ? (y:1;n:0) Require to use smoothing option (smoothing coefficient) ! \n \
1   % smoothing by Laplacian, computed with a scheme at 3pts (0) or 5pts (1) ? \n \
2   % weigthed smoothing by the average time step (y :0 ; n : 1, int : 2) ? \n \
1    % put the first derivative to zero (y :0 ; n : 1)? \n \
"

    f=open("../DX/input_inv_send.txt", "w")
    f.write(text.encode('ascii'))
    f.close()

    f=open("../DY/input_inv_send.txt", "w")
    f.write(text.encode('ascii'))
    f.close()

genInput_inv_send()

ValidDate = []
from datetime import datetime
def genList_image_inv():
    fdx = open("../DX/list_image_inv.txt", "w")
    fdy = open("../DY/list_image_inv.txt", "w")


    all_dates = imgDate.values()
    dates_set  = set(all_dates)
    dates = list(dates_set)
    dates.sort()
    
    date_format="%Y%m%d"
    yearBefore = int(dates[0][0:4])-1
    initDate = datetime.strptime(str(yearBefore) + '1231', date_format)

    for i, date in enumerate(dates):

        lastDayOfYear = datetime.strptime(date[0:4] + '1231', date_format)
        nbDaysInTheYear = (lastDayOfYear-initDate).days

        curentDate = datetime.strptime(date, date_format)

        delta = curentDate - initDate
        fractionOfYear = float(delta.days)/nbDaysInTheYear

        if(M_validImage[i] == 1):
            ValidDate.append(date[0:4])
            fdx.write(date + " " + date[0:4] + ("{0:.7f}".format(fractionOfYear))[1:] + " " + "{0:.7f}".format(fractionOfYear) + " 0\n")
            fdy.write(date + " " + date[0:4] + ("{0:.7f}".format(fractionOfYear))[1:] + " " + "{0:.7f}".format(fractionOfYear) + " 0\n")
        
    fdx.close()
    fdy.close()
    
genList_image_inv()

def genList_interfero():
    fdx = open("../DX/list_interfero.txt", "w")
    fdy = open("../DY/list_interfero.txt", "w")

    cplxFiles = listdirectory(".", "_inv")
    for name in cplxFiles:
        name = name.replace("_","-")
        name = name.replace("/","-")
        name_tap = name.split("-")
        if((name_tap[1] in ValidDate) and (name_tap[2] in ValidDate)):
            fdx.write(name_tap[1] + " " + name_tap[2] + "\n")
            fdy.write(name_tap[1] + " " + name_tap[2] + "\n")

    fdx.close()
    fdy.close()
    
genList_interfero()
