# -*- coding: utf-8 -*-
"""
Created on Fri Jan  233 07:02:58 2020

@author: yeg
"""
import numpy as np
#import matplotlib.pyplot as plt
import os
#from PIL import Image, ImageSequence, TiffImagePlugin
from PIL import Image
from pims import ND2_Reader
import pims_nd2             #sometime needs this and sometimes not
#from pims import ND2_Reader
#from nd2reader import ND2Reader
#import nd2reader
#import nd2reader
#path = r"D:\Dropbox\Crew\Arpan\PeptideRelease"
path = r"D:\Dropbox\Crew\Arpan\Tiffs"
path = r"D:\Dropbox\Crew\Clark\ND2_Files"
#path = r"D:\Dropbox\Crew\Jiabei\ND2_Files"
#path = r"D:\Dropbox\Crew\Arpan\ND2_Files"  
#path = r"D:\Dropbox\Crew\Arpan\ND2_Files\01.23.20"  
path = r"E:\Data\test3"  
   
###########################           
            
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 "nd2" in fn:
#        print ("filename = ", fn)
        if (("csv" in fn) or ("-rw" in fn) or ("tif" in fn) or 
              ("-ca" in fn) or ("-av" in fn) or ("txt" in fn)):
#            print "Don't process ", fn
            print ("Don't process ", fn)
        else:
            tflist.append(fn)
        
print ("# of native nd2 files: ", len(tflist))
print (tflist) 

frames = ND2_Reader(path + "\\" + tflist[0])
frames[0]  # display frame 82
#frames.close()

for kf in range(len(tflist)):

    fullfn = path + "\\" + tflist[kf]
#    print (fullfn)
        
    '''
    #reads whole file into array
    from skimage import io
    im = io.imread(fullfn)
    print (im.shape)
    print (im[0].shape)
    '''
    
#    dataset = Image.open(fullfn)
    frames = ND2_Reader(fullfn)
#    print (frames.frame_shape)
#    fr = frames[0]
    print (' ')
    print("Pixels: ", frames.frame_shape[0], frames.frame_shape[1])
#    print (frames.frame_shape["t"])
    w = frames.frame_shape[0]
    h = frames.frame_shape[1]
#    print w, h
#    print ("Pixels: ", w, h)
#    print (frames.sizes['t'])
#    print (w,h, dataset.n_frames, dataset.mode)
    
    frst = (np.zeros((w,h)))
    
    n_frames = frames.sizes['t']
#    print "number of frames = ", n_frames
    print ("Number of frames: ", n_frames)

    
#    frameData = np.zeros((w,h,n_frames))
    frameData = np.zeros((w,h))
        
    outfile = path + "\\" + tflist[kf][:-4] + '-rw.tiff'
    
#    print (outfile)
    
    ko = 0
    imList = []
    oe = n_frames%2     #odd or even # of frames
#    print ("oe = ", oe)
#    Z = frames[0][1]
#    print Z
    for k in range(3,n_frames,2):
        dataset = frames[k]
        frameData[:,:] = np.array(dataset)
        imList.append(Image.fromarray(np.uint16(frameData[:,:])))
        ko=ko+1
        if ((ko % 50) == 0):
            print ('\r', ko, end = " ", flush=True)
#            print '\r', ko,
#            print ('\r', ko),
              
    for k in range(4,n_frames-1,2):
        dataset = frames[k]
        frameData[:,:] = np.array(dataset)
        imList.append(Image.fromarray(np.uint16(frameData[:,:])))
        ko=ko+1
        if ((ko % 50) == 0):
            print ('\r', ko, end = " ", flush=True)
#            print '\r', ko,
#            print ('\r', ko),
   
    print (" ")
    print ("saving ", outfile)
    
    imList[0].save(outfile, format="tiff", append_images=imList[1:-1], save_all=True)
    
    frames.close()
