def runOnDirectory(directory, geoTJ, geoTJ2=None, fpsSpecial=[]):
    listFolders=os.listdir(directory)
    indexDelet=[]
    for i in range(len(listFolders)):
        if os.path.isfile(directory+listFolders[i]):
            indexDelet.append(i)

    for i in range(len(indexDelet)-1, -1, -1):
        del listFolders[indexDelet[i]]
    listFolders.sort()
    foldersThatWorked=[]
    foldersDidntWorked=[]
    q=[]
    ss=[]
    fps=[]
    filename=[]
    maxWidthAt=[]
    for f in listFolders:     
        try:
            sp1=f.rfind('mlPmin')
            sp2 = f[:sp1].rfind('-')
            if sp2 == -1:
                sp2 = f[:sp1].rfind('_')
                
            sp3=f.find('FPS')
            sp4=f[:sp1].rfind('_')
            if sp4 == -1 or (len(f[:sp3]) - sp4 ) > 5:
                sp4=f[:sp3].rfind('-')
    
            FPSString=float(f[sp4+1:sp3]) 
    #            print('print sp1 = %d, sp2 = %d, %s' %(sp1, sp2, f[sp2+1:sp1]))
            
            geo = geoTJ
            if geoTJ2 != None:
                if FPSString in fpsSpecial:
                    geo = geoTJ2
                
            
            print('\n Starting \t %s \n' %f)
            path=directory + f + '\\Outlines\\'
            ssIndex = runSym(path = path, geoTJ = geo, plot= False, show=False)
            ss.append(ssIndex)
            q.append(float(f[sp2+1:sp1]))
            fps.append(FPSString)
            filename.append(f)
            foldersThatWorked.append(f)
            
            #get other measurments
            centroid_x, centroid_y, _, _, _, width1, _, _ = rof.readResultsFile(directory + f + '\\') 
            index=np.arange(len(width1))
            widthShort1=width1[int(0.2*len(width1)):int(0.8*len(width1))]
            indexShort=index[int(0.2*len(width1)):int(0.8*len(width1))]
            
            maxwidth1=np.max(widthShort1)            
            indS = np.argmax(widthShort1)
            indexMaxWidth = indexShort[indS]
            maxWidthAt.append(indexMaxWidth)
#            find_max_extend(directory+f)
        except Exception, err:
            print('Didnt work for \t %s (%s)' %(f, err))
            foldersDidntWorked.append(f)
def findSymmetryByCentreline(path, geoTJ, plot=False, show=False):
    '''
    Evaluate the point when capsule has reached a steady state from distance of
    centroid from centreline of daugther channel.
    
    The centreline is found from top and bottom of daugther channel, stored in 
    geoTJ. 
    
    -Input-
    path        path to folder with result file from run (folder that stores images)
    geoTJ       4 int values in pixels, related to the geometry: 
                    -top daugther channel
                    -bottom daugther channel
                    -left side of main channel
                    -right side of main channel
    
    plot        plot results
    show        show plots
    
    -Output-
    framesToSS      number of frames from max width to steady state
    distanceToSS    distance (in pixelse) from max width to steady state
    frameMaxWidth   Frame on which max width was reached
    frameSS         Frame on which steady state was reached
    
    
    TODO: This still assumes that there are no gaps in capsules tracking. This
    can be checked using the array "number". 
    
    '''
    #Constants
    SMOOTHING_WINDOW=11
    CUTOFF_LEFT = 0.2
    CUTOFF_RIGHT = 0.8
    #look a differential and define threshold above which capsule is not in Steady state
    THRESH_SS_LOST=0.1 #TODO: adjust this to take into account units?
    
    
    daugtherChannelMiddel = (geoTJ[0]+ geoTJ[1]+ 0.0)/2.0
    
    
    
    centroid_x_fromFile, centroid_y_fromFile, _, _, _, width1, _, _ = rof.readResultsFile(path) 
    
    readCentroidsFromOutlines = True
    #check whether file centroid positions contains only whole numbers
    for ii in range(len(centroid_x_fromFile)):
        if not np.equal(np.mod(centroid_x_fromFile[ii], 1), 0) or not np.equal(np.mod(centroid_y_fromFile[ii], 1), 0):
            readCentroidsFromOutlines=False
            centroid_x, centroid_y = centroid_x_fromFile, centroid_y_fromFile
            break;
            
    if readCentroidsFromOutlines:
        #Older versions of the script analysising the images (track_capsule_TJ)
        #rounded centroid positions to an integer, so need to find centroid position from
        #re-anaylising contour. For new result files, this is unnessecary and centroid 
        #position can be read from the results file
        centroid_x,centroid_y, number = findCentroidFromOutline(path)
            
    #find the point of maximum widht of capsule
    index=np.arange(len(width1))
    widthShort1=width1[int(CUTOFF_LEFT*len(width1)):int(CUTOFF_RIGHT*len(width1))]
    indexShort=index[int(CUTOFF_LEFT*len(width1)):int(CUTOFF_RIGHT*len(width1))]
    #TODO: ensure its that last index where max width is reached!
    maxwidth1=np.max(widthShort1)            
    indS = np.argmax(widthShort1)
    indexMaxWidth = indexShort[indS]    
    
    dx2, count = centralDifferenc(centroid_y - daugtherChannelMiddel)

    smooth_centdx2 = tr.smooth((dx2),window_len=SMOOTHING_WINDOW,window='hanning')

    endIndex=np.where(smooth_centdx2[:-SMOOTHING_WINDOW] > THRESH_SS_LOST)
    if not endIndex: #if condition is never satisfied
        endIndex = ERROR_CODE-1
    
    steadyStateReachedOnFrame =endIndex[0][-1] +1
    s = "Steady state reached on frame %d" %(steadyStateReachedOnFrame)
    
    #distance traveled to reach SS
    distanceToSS = np.sqrt( (centroid_x[steadyStateReachedOnFrame] - centroid_x[indexMaxWidth])**2 + (centroid_y[steadyStateReachedOnFrame] - centroid_y[indexMaxWidth])**2 )
    
    if plot:  #mainly for testing purposes
        xarr = range(len(centroid_y))
        fig = plt.figure(figsize=(8, 6), dpi=200,); ax = fig.add_subplot(111)
        plt.plot(xarr, centroid_y - daugtherChannelMiddel, 'or', linestyle='None')
        smooth_cent = tr.smooth(np.array(centroid_y - daugtherChannelMiddel).flatten(),window_len=11,window='hanning')
        plt.plot(xarr, smooth_cent[:-1], 'b', linestyle='--')
        plt.xlabel('Picture #')
        plt.ylabel('Difference Centreline and y-centroid')
        plt.xlim([0, 220])
        
        fig = plt.figure(figsize=(8, 6), dpi=200,); ax = fig.add_subplot(111)
        plt.plot(xarr, dx2, 'sb', linestyle='None', label='Result Central Difference')
        plt.plot(xarr, smooth_centdx2[:-1], 'r',linewidth=3, linestyle='--', label = 'Smoothed Central Difference')
    
#        xmin, xmax = plt.xlim(); dif = xmax - steadyStateReachedOnFrame; plt.xlim([int(xmax - 2.5* dif), xmax])
        plt.xlim([0, 220])
        
        ymin, ymax = plt.ylim()
    #    plt.ylim([-0.2, ymax])
        plt.plot([steadyStateReachedOnFrame, steadyStateReachedOnFrame], [-0.2, ymax], 'y',linewidth=2, linestyle='-', label = 'SS reached (on # %d)' %steadyStateReachedOnFrame)
        
        plt.xlabel('Picture #')
        plt.ylabel('Gradient of Difference Centreline and y-centroid')
        plt.legend(loc='best')
        
        ax.text(0.05, 0.2, s, fontsize=12, horizontalalignment='left', verticalalignment='center', transform = ax.transAxes)
        
        if show:
            plt.show()
        else:
            plt.close(fig)
    #framesToSS, distanceToSS, frameMaxWidth, frameSS         
    return steadyStateReachedOnFrame - indexMaxWidth +0.0, distanceToSS, indexMaxWidth, steadyStateReachedOnFrame