# -*- coding: utf-8 -*-
"""
Created on Sun 2/21/2021
Splits Alex files, but fakes PSM by putting the ALEX
stripe in the FRET position and all the real Sensitized emission
at the end

@author: yeg
"""
import numpy as np
#import matplotlib.pyplot as plt
import os
#from PIL import Image, ImageSequence, TiffImagePlugin
from PIL import Image
import sys

#path = r"D:\Dropbox\Crew\Arpan\PeptideRelease"
#path = r"D:\Dropbox\Crew\Arpan\Tiffs"
#path = r"D:\Dropbox\Crew\Arpan\Nd2, tiff and Rw files\Tiff files"       
#path = r"D:\Dropbox\Crew\Clark\DDX3\Duplex RNA alone"  
#path = r"D:\Dropbox\Crew\Clark\DDX3\Duplex RNA with DDX3X"
#path = r"D:\Dropbox\Crew\Clark\DDX3\wrError"
path = r"D:\Basic_Analysis_Guide\Low_FRET_Analysis"


###########################           
            
def gfn():       # Get file names from directory
    file_list=os.listdir(path)
#    print (file_list)
    return file_list

##########################
    
#plt.close('all')

file_list = gfn()
print ("Files: ", len(file_list))

tflist = []

for fn in file_list:
    if "tif" in fn:
#        print ("filename = ", fn)
        if (("csv" in fn) or ("-rw" in fn) or 
              ("-ca" in fn) or ("-av" in fn) or ("txt" in fn)):
            print ("Don't process ", fn,)
        else:
            tflist.append(fn)
        
print ("# of tiff files: ", len(tflist))
print (tflist) 

for kf in range(len(tflist)):

    fullfn = path + "\\" + tflist[kf]
    print ("\nInput filename: ", fullfn)
           
    dataset = Image.open(fullfn)
    w,h = dataset.size
    hw = int(w/2)
    
#    print (w,h, dataset.n_frames, dataset.mode)
    
    even = (np.zeros((h,w)))
    odds = (np.zeros((h,w)))
    frst = (np.zeros((h,w)))
    
    print ("Number offrames in = ", dataset.n_frames)
    frameData = np.zeros((h,w,dataset.n_frames))
    oe = dataset.n_frames%2     #odd or even # of frames
    print ("oe: ", oe)    
 
    k = 5
    dataset.seek(k)      
    frameData[:,:,k] = np.array(dataset)       

    avL = np.mean(frameData[:, 0:hw-1, k])
    avR = np.mean(frameData[:, hw:w-1, k])            
    lrRatio = avL/avR
#    print (avL, avR, lrRatio)
    
#    sys.exit()
    if (lrRatio > 1):
        print ("Frame " + str(k) + " is red")
        sf = 5     #starting frame
    else:
        print ("Frame " + str(k) + " is green")
        sf = 4     #starting frame
    
    
    ko = 0
#    print ("oe = ", oe)
    
    for k in range(sf,dataset.n_frames,2):
        dataset.seek(k)      
        frameData[:,:,ko] = np.array(dataset)       
        frameData[0,0,ko] = k       
        ko=ko+1
        if ((ko % 50) == 0):
            print ('\r', ko, end = " ", flush=True)
                
    for k in range(sf-1,dataset.n_frames-1,2):
        dataset.seek(k)    
        frameData[:,:,ko] = np.array(dataset)
        frameData[0,0,ko] = k       
        ko=ko+1
        if ((ko % 50) == 0):
            print ('\r', ko, end = " ", flush=True)
            
    hnFo = int(ko/2)
    nFo = 2*hnFo
    print ("\nNumber of frames out = ", nFo)        
    
    swpD = False
    swpD = True               #whether to swap ALEX data or not
    if (swpD):

        for k in range(hnFo):
            RHS = frameData[:,hw:w,k].copy()     #right hand side (sens emiss) of green frames 
            frameData[:,hw:w,k] = frameData[:,hw:w,k+hnFo]
            frameData[:,hw:w,k+hnFo] = RHS
#            sys.exit()
            if ((k % 50) == 0):
                print ('\r', k, end = " ", flush=True)
                
        '''   
        for k in range(sf,dataset.n_frames,2):
            dataset.seek(k)    
            frameData[:,hw:w,ko] = np.array(dataset)[:,hw:w]
            frameData[0,hw,ko] = k       
            ko=ko+1
            if ((ko % 50) == 0):
                print ('\r', ko, end = " ", flush=True)
        '''




#    dataset.seek(3)
#    frst[:,:] = np.array(dataset)
#    im0 = Image.fromarray(np.uint16(frst))
    im0 =  Image.fromarray(np.uint16(frameData[:,:,0]))

    imList = []

    for k in range(1,nFo):
        imList.append(Image.fromarray(np.uint16(frameData[:,:,k])))
        if ((k % 50) == 0):
            print ('\r', ko, end = " ", flush=True)
            
          
    outpath = path + "\\wr"
    print ("\nOutput directory: ", outpath)
#    print (' ')
#    sys.exit(1)
     
    try:
        os.mkdir(outpath)
    except:
        print ('Folder ' + outpath + ' already exists')
    
#    print (' ')
    
    outfile = outpath + "\\" + tflist[kf][:-5] + '-wr.tiff'        
    print ("Saving ", outfile)
    
    im0.save(outfile, format="tiff", append_images=imList, save_all=True)
    
    dataset.close()
