def main():
    global behavSession
    global subject
    global tetrode
    global cluster
    global tuningBehavior  #behavior file name of tuning curve
    global tuningEphys  #ephys session name of tuning curve
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global titleText

    print "switch_tuning_block_allfreq_report"
    for cellID in range(0, numOfCells):
        oneCell = allcells.cellDB[cellID]
        try:
            if (behavSession != oneCell.behavSession):

                subject = oneCell.animalName
                behavSession = oneCell.behavSession
                ephysSession = oneCell.ephysSession
                tuningSession = oneCell.tuningSession
                ephysRoot = os.path.join(ephysRootDir, subject)
                tuningBehavior = oneCell.tuningBehavior
                tuningEphys = oneCell.tuningSession

                print behavSession

                # -- Load Behavior Data --
                behaviorFilename = loadbehavior.path_to_behavior_data(
                    subject=subject,
                    paradigm=paradigm,
                    sessionstr=behavSession)
                bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
                #bdata = loadbehavior.BehaviorData(behaviorFilename)
                numberOfTrials = len(bdata['choice'])

                # -- Load event data and convert event timestamps to ms --
                ephysDir = os.path.join(ephysRoot, ephysSession)
                eventFilename = os.path.join(ephysDir, 'all_channels.events')
                events = loadopenephys.Events(
                    eventFilename)  # Load events data
                eventTimes = np.array(
                    events.timestamps
                ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

                soundOnsetEvents = (events.eventID == 1) & (
                    events.eventChannel == soundTriggerChannel)

                eventOnsetTimes = eventTimes[soundOnsetEvents]
                soundOnsetTimeBehav = bdata['timeTarget']

                # Find missing trials
                missingTrials = behavioranalysis.find_missing_trials(
                    eventOnsetTimes, soundOnsetTimeBehav)
                # Remove missing trials
                bdata.remove_trials(missingTrials)
                bdata.find_trials_each_block()

                ###############################################################################################
                centerOutTimes = bdata[
                    'timeCenterOut']  #This is the times that the mouse goes out of the center port
                soundStartTimes = bdata[
                    'timeTarget']  #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
                timeDiff = centerOutTimes - soundStartTimes
                if (len(eventOnsetTimes) < len(timeDiff)):
                    timeDiff = timeDiff[:-1]
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                elif (len(eventOnsetTimes) > len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes[:-1] + timeDiff
                else:
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                ###############################################################################################

            tetrode = oneCell.tetrode
            cluster = oneCell.cluster

            # -- Load Spike Data From Certain Cluster --
            spkData = ephyscore.CellData(oneCell)
            spkTimeStamps = spkData.spikes.timestamps

            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

            (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

            plt.clf()
            if (len(spkTimeStamps) > 0):
                ax1 = plt.subplot2grid((numRows, numCols),
                                       ((numRows - sizeClusterPlot), 0),
                                       colspan=(numCols / 3))
                spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
                ax3 = plt.subplot2grid(
                    (numRows, numCols),
                    ((numRows - sizeClusterPlot), (numCols / 3) * 2),
                    colspan=(numCols / 3))
                spikesorting.plot_events_in_time(spkTimeStamps)
                samples = spkData.spikes.samples.astype(float) - 2**15
                samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples
                ax2 = plt.subplot2grid(
                    (numRows, numCols),
                    ((numRows - sizeClusterPlot), (numCols / 3)),
                    colspan=(numCols / 3))
                spikesorting.plot_waveforms(samples)

            ###############################################################################
            ax4 = plt.subplot2grid((numRows, numCols), (0, 0),
                                   colspan=(numCols / 2),
                                   rowspan=3 * sizeRasters)
            #plt.setp(ax4.get_xticklabels(), visible=False)
            #fig.axes.get_xaxis().set_visible(False)
            raster_tuning(ax4)
            axvline(x=0, ymin=0, ymax=1, color='r')
            plt.gca().set_xlim(tuning_timeRange)

            ax6 = plt.subplot2grid((numRows, numCols), (0, (numCols / 2)),
                                   colspan=(numCols / 2),
                                   rowspan=sizeRasters)
            plt.setp(ax6.get_xticklabels(), visible=False)
            plt.setp(ax6.get_yticklabels(), visible=False)
            raster_sound_block_switching()
            plt.title(
                'sound aligned, Top: middle freq in blocks, Bottom: all freqs')

            ax7 = plt.subplot2grid((numRows, numCols),
                                   (sizeRasters, (numCols / 2)),
                                   colspan=(numCols / 2),
                                   rowspan=sizeHists,
                                   sharex=ax6)
            hist_sound_block_switching(ax7)
            #plt.setp(ax7.get_yticklabels(), visible=False)
            ax7.yaxis.tick_right()
            ax7.yaxis.set_ticks_position('both')
            plt.setp(ax7.get_xticklabels(), visible=False)
            plt.gca().set_xlim(timeRange)

            ax10 = plt.subplot2grid((numRows, numCols),
                                    ((sizeRasters + sizeHists), (numCols / 2)),
                                    colspan=(numCols / 2),
                                    rowspan=sizeRasters)
            plt.setp(ax10.get_xticklabels(), visible=False)
            plt.setp(ax10.get_yticklabels(), visible=False)
            raster_sound_allFreq_switching()

            ax11 = plt.subplot2grid(
                (numRows, numCols),
                ((2 * sizeRasters + sizeHists), (numCols / 2)),
                colspan=(numCols / 2),
                rowspan=sizeHists,
                sharex=ax10)
            hist_sound_allFreq_switching(ax11)
            ax11.yaxis.tick_right()
            ax11.yaxis.set_ticks_position('both')
            ax11.set_xlabel('Time (sec)')
            #plt.setp(ax11.get_yticklabels(), visible=False)
            plt.gca().set_xlim(timeRange)

            ###############################################################################
            #plt.tight_layout()
            modulation_index_switching()
            plt.suptitle(titleText)

            tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
                oneCell.cluster)
            plt.gcf().set_size_inches((8.5, 11))
            figformat = 'png'  #'png' #'pdf' #'svg'
            filename = reportname + '_%s_%s_%s.%s' % (
                subject, behavSession, tetrodeClusterName, figformat)
            fulloutputDir = outputDir + subject + '/'
            fullFileName = os.path.join(fulloutputDir, filename)

            directory = os.path.dirname(fulloutputDir)
            if not os.path.exists(directory):  #makes sure output folder exists
                os.makedirs(directory)
            #print 'saving figure to %s'%fullFileName
            plt.gcf().savefig(fullFileName, format=figformat)

        except:
            if (oneCell.behavSession not in badSessionList):
                badSessionList.append(oneCell.behavSession)

    print 'error with sessions: '
    for badSes in badSessionList:
        print badSes
def main():
    global behavSession
    global subject
    global tetrode
    global cluster
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global titleText

    print "SwitchingReport"
    for cellID in range(0,numOfCells):
        oneCell = allcells.cellDB[cellID]
        if (behavSession != oneCell.behavSession):


            subject = oneCell.animalName
            behavSession = oneCell.behavSession
            ephysSession = oneCell.ephysSession
            ephysRoot = os.path.join(ephysRootDir,subject)

            print behavSession

            # -- Load Behavior Data --
            behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession)
            bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
            #bdata = loadbehavior.BehaviorData(behaviorFilename)
            bdata.find_trials_each_block()
            numberOfTrials = len(bdata['choice'])

            # -- Load event data and convert event timestamps to ms --
            ephysDir = os.path.join(ephysRoot, ephysSession)
            eventFilename=os.path.join(ephysDir, 'all_channels.events')
            events = loadopenephys.Events(eventFilename) # Load events data
            eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

            soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)

            eventOnsetTimes = eventTimes[soundOnsetEvents]

            ###############################################################################################
            centerOutTimes = bdata['timeCenterOut'] #This is the times that the mouse goes out of the center port
            soundStartTimes = bdata['timeTarget'] #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
            timeDiff = centerOutTimes - soundStartTimes
            if (len(eventOnsetTimes) < len(timeDiff)):
                timeDiff = timeDiff[:-1]
            eventOnsetTimesCenter = eventOnsetTimes + timeDiff
            ###############################################################################################


        tetrode = oneCell.tetrode
        cluster = oneCell.cluster


        # -- Load Spike Data From Certain Cluster --
        spkData = ephyscore.CellData(oneCell)
        spkTimeStamps = spkData.spikes.timestamps

        (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
            spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

        (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
            spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)


        plt.clf()
        if (len(spkTimeStamps)>0):
            ax1 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),0), colspan = (numCols/3))
            spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
            ax3 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)*2), colspan = (numCols/3))
            spikesorting.plot_events_in_time(spkTimeStamps)
            samples = spkData.spikes.samples.astype(float)-2**15
            samples = (1000.0/spkData.spikes.gain[0,0]) *samples
            ax2 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)), colspan = (numCols/3))
            spikesorting.plot_waveforms(samples)


        ###############################################################################
        ax4 = plt.subplot2grid((numRows,numCols), (0,0), colspan = (numCols/2), rowspan = sizeRasters)
        raster_sound_block_switching()
        ax5 = plt.subplot2grid((numRows,numCols), (sizeRasters,0), colspan = (numCols/2), rowspan = sizeHists)
        hist_sound_block_switching()
        ax6 = plt.subplot2grid((numRows,numCols), (0,(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters)
        raster_movement_block_switching()
        ax7 = plt.subplot2grid((numRows,numCols), (sizeRasters,(numCols/2)), colspan = (numCols/2), rowspan = sizeHists)
        hist_movement_block_switching()

        ax8 = plt.subplot2grid((numRows,numCols), ((sizeRasters+sizeHists),0), colspan = (numCols/2), rowspan = sizeRasters)
        raster_sound_allFreq_switching()     
        ax9 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),0), colspan = (numCols/2), rowspan = sizeHists)
        hist_sound_allFreq_switching()
        ax10 = plt.subplot2grid((numRows,numCols), ((sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters) 
        raster_sound_switching()
        ax11 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeHists) 
        hist_sound_switching()
        ###############################################################################
        #plt.tight_layout()
        modulation_index_switching()
        plt.suptitle(titleText)

        tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster)
        plt.gcf().set_size_inches((8.5,11))
        figformat = 'png' #'png' #'pdf' #'svg'
        filename = 'report_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,figformat)
        fulloutputDir = outputDir+subject +'/'
        fullFileName = os.path.join(fulloutputDir,filename)

        directory = os.path.dirname(fulloutputDir)
        if not os.path.exists(directory): #makes sure output folder exists
            os.makedirs(directory)
        #print 'saving figure to %s'%fullFileName
        plt.gcf().savefig(fullFileName,format=figformat)
    '''
    meanSpikesEachFrequency = np.empty(len(possibleFreq)) #make empty array of same size as possibleFreq

    # -- This part will be replace by something like behavioranalysis.find_trials_each_type --
    trialsEachFreq = []
    for indf,oneFreq in enumerate(possibleFreq):
        trialsEachFreq.append(np.flatnonzero(freqEachTrial==oneFreq)) #finds indices of each frequency. Appends them to get an array of indices of trials sorted by freq

    # -- Calculate average firing for each freq --
    for indf,oneFreq in enumerate(possibleFreq):
        meanSpikesEachFrequency[indf] = np.mean(nSpikes[trialsEachFreq[indf]])

    clf()
    if (len(spkTimeStamps)>0):
        ax1 = plt.subplot2grid((4,4), (3, 0), colspan=1)
        spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
        ax3 = plt.subplot2grid((4,4), (3, 3), colspan=1)
        spikesorting.plot_events_in_time(spkTimeStamps)
        samples = spkData.spikes.samples.astype(float)-2**15
        samples = (1000.0/spkData.spikes.gain[0,0]) *samples
        ax2 = plt.subplot2grid((4,4), (3, 1), colspan=2)
        spikesorting.plot_waveforms(samples)
    ax4 = plt.subplot2grid((4,4), (0, 0), colspan=3,rowspan = 3)
    plot(spikeTimesFromEventOnset, sortedIndexForEachSpike, '.', ms=3)
    axvline(x=0, ymin=0, ymax=1, color='r')

    #The cumulative sum of the list of specific frequency presentations, 
    #used below for plotting the lines across the figure. 
    numTrials = cumsum(numTrialsEachFreq)

    #Plot the lines across the figure in between each group of sorted trials
def main():
    global behavSession
    global subject
    global tetrode
    global cluster
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global titleText

    print "SwitchingReport"
    for cellID in range(0, numOfCells):
        oneCell = allcells.cellDB[cellID]
        if (behavSession != oneCell.behavSession):

            subject = oneCell.animalName
            behavSession = oneCell.behavSession
            ephysSession = oneCell.ephysSession
            ephysRoot = os.path.join(ephysRootDir, subject)

            print behavSession

            # -- Load Behavior Data --
            behaviorFilename = loadbehavior.path_to_behavior_data(
                subject, experimenter, paradigm, behavSession)
            bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
            #bdata = loadbehavior.BehaviorData(behaviorFilename)
            bdata.find_trials_each_block()
            numberOfTrials = len(bdata['choice'])

            # -- Load event data and convert event timestamps to ms --
            ephysDir = os.path.join(ephysRoot, ephysSession)
            eventFilename = os.path.join(ephysDir, 'all_channels.events')
            events = loadopenephys.Events(eventFilename)  # Load events data
            eventTimes = np.array(
                events.timestamps
            ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

            soundOnsetEvents = (events.eventID == 1) & (events.eventChannel
                                                        == soundTriggerChannel)

            eventOnsetTimes = eventTimes[soundOnsetEvents]

            ###############################################################################################
            centerOutTimes = bdata[
                'timeCenterOut']  #This is the times that the mouse goes out of the center port
            soundStartTimes = bdata[
                'timeTarget']  #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
            timeDiff = centerOutTimes - soundStartTimes
            if (len(eventOnsetTimes) < len(timeDiff)):
                timeDiff = timeDiff[:-1]
            eventOnsetTimesCenter = eventOnsetTimes + timeDiff
            ###############################################################################################

        tetrode = oneCell.tetrode
        cluster = oneCell.cluster

        # -- Load Spike Data From Certain Cluster --
        spkData = ephyscore.CellData(oneCell)
        spkTimeStamps = spkData.spikes.timestamps

        (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
            spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

        (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
            spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

        plt.clf()
        if (len(spkTimeStamps) > 0):
            ax1 = plt.subplot2grid((numRows, numCols),
                                   ((numRows - sizeClusterPlot), 0),
                                   colspan=(numCols / 3))
            spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
            ax3 = plt.subplot2grid(
                (numRows, numCols),
                ((numRows - sizeClusterPlot), (numCols / 3) * 2),
                colspan=(numCols / 3))
            spikesorting.plot_events_in_time(spkTimeStamps)
            samples = spkData.spikes.samples.astype(float) - 2**15
            samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples
            ax2 = plt.subplot2grid(
                (numRows, numCols),
                ((numRows - sizeClusterPlot), (numCols / 3)),
                colspan=(numCols / 3))
            spikesorting.plot_waveforms(samples)

        ###############################################################################
        ax4 = plt.subplot2grid((numRows, numCols), (0, 0),
                               colspan=(numCols / 2),
                               rowspan=sizeRasters)
        raster_sound_block_switching()
        ax5 = plt.subplot2grid((numRows, numCols), (sizeRasters, 0),
                               colspan=(numCols / 2),
                               rowspan=sizeHists)
        hist_sound_block_switching()
        ax6 = plt.subplot2grid((numRows, numCols), (0, (numCols / 2)),
                               colspan=(numCols / 2),
                               rowspan=sizeRasters)
        raster_movement_block_switching()
        ax7 = plt.subplot2grid((numRows, numCols),
                               (sizeRasters, (numCols / 2)),
                               colspan=(numCols / 2),
                               rowspan=sizeHists)
        hist_movement_block_switching()

        ax8 = plt.subplot2grid((numRows, numCols),
                               ((sizeRasters + sizeHists), 0),
                               colspan=(numCols / 2),
                               rowspan=sizeRasters)
        raster_sound_allFreq_switching()
        ax9 = plt.subplot2grid((numRows, numCols),
                               ((2 * sizeRasters + sizeHists), 0),
                               colspan=(numCols / 2),
                               rowspan=sizeHists)
        hist_sound_allFreq_switching()
        ax10 = plt.subplot2grid((numRows, numCols),
                                ((sizeRasters + sizeHists), (numCols / 2)),
                                colspan=(numCols / 2),
                                rowspan=sizeRasters)
        raster_sound_switching()
        ax11 = plt.subplot2grid((numRows, numCols),
                                ((2 * sizeRasters + sizeHists), (numCols / 2)),
                                colspan=(numCols / 2),
                                rowspan=sizeHists)
        hist_sound_switching()
        ###############################################################################
        #plt.tight_layout()
        modulation_index_switching()
        plt.suptitle(titleText)

        tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
            oneCell.cluster)
        plt.gcf().set_size_inches((8.5, 11))
        figformat = 'png'  #'png' #'pdf' #'svg'
        filename = 'report_%s_%s_%s.%s' % (subject, behavSession,
                                           tetrodeClusterName, figformat)
        fulloutputDir = outputDir + subject + '/'
        fullFileName = os.path.join(fulloutputDir, filename)

        directory = os.path.dirname(fulloutputDir)
        if not os.path.exists(directory):  #makes sure output folder exists
            os.makedirs(directory)
        #print 'saving figure to %s'%fullFileName
        plt.gcf().savefig(fullFileName, format=figformat)
def main():
    global behavSession
    global subject
    global ephysSession
    global tetrode
    global cluster
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global tuningBehavior#behavior file name of tuning curve
    global tuningEphys#ephys session name of tuning curve

    print 'psycurve_tuning_report'

    for cellID in range(0,numOfCells):
            oneCell = allcells.cellDB[cellID]##########!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        #try:#######################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if (behavSession != oneCell.behavSession):


                subject = oneCell.animalName
                behavSession = oneCell.behavSession
                ephysSession = oneCell.ephysSession
                ephysRoot = os.path.join(ephysRootDir,subject)
                tuningBehavior = oneCell.tuningBehavior
                tuningEphys = oneCell.tuningSession

                print behavSession

                # -- Load Behavior Data --
                behaviorFilename = loadbehavior.path_to_behavior_data(subject=subject,paradigm=paradigm,sessionstr=behavSession)
                bdata = loadbehavior.BehaviorData(behaviorFilename)
                numberOfTrials = len(bdata['choice'])
                #print 'numberTrials ',numberOfTrials############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                # -- Load event data and convert event timestamps to ms --
                ephysDir = os.path.join(ephysRoot, ephysSession)
                eventFilename=os.path.join(ephysDir, 'all_channels.events')
                events = loadopenephys.Events(eventFilename) # Load events data
                eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

                soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)

                eventOnsetTimes = eventTimes[soundOnsetEvents]
                soundOnsetTimeBehav = bdata['timeTarget']

                # Find missing trials
                missingTrials = behavioranalysis.find_missing_trials(eventOnsetTimes,soundOnsetTimeBehav)
                #print 'missing ',len(missingTrials)############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                # Remove missing trials
                bdata.remove_trials(missingTrials)


                possibleFreq = np.unique(bdata['targetFrequency'])
                numberOfFrequencies = len(possibleFreq)
                centerFrequencies = [(numberOfFrequencies/2-1),numberOfFrequencies/2]

                #################################################################################################
                centerOutTimes = bdata['timeCenterOut'] #This is the times that the mouse goes out of the center port
                soundStartTimes = bdata['timeTarget'] #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
                timeDiff = centerOutTimes - soundStartTimes
                #print 'timeDiff ',len(timeDiff)############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                #print 'eventOnsetTimes ',len(eventOnsetTimes)############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                if (len(eventOnsetTimes) < len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff[:-1]
                elif (len(eventOnsetTimes) > len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes[:-1] + timeDiff
                else:
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                #################################################################################################


            tetrode = oneCell.tetrode
            cluster = oneCell.cluster
            # -- Load Spike Data From Certain Cluster --
            spkData = ephyscore.CellData(oneCell)
            spkTimeStamps = spkData.spikes.timestamps

            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

            (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

            plt.clf()
            if (len(spkTimeStamps)>0):
                ax1 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),0), colspan = (numCols/3))
                spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
                ax3 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)*2), colspan = (numCols/3))
                spikesorting.plot_events_in_time(spkData.spikes.timestamps)
                samples = spkData.spikes.samples.astype(float)-2**15
                samples = (1000.0/spkData.spikes.gain[0,0]) *samples
                ax2 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)), colspan = (numCols/3))
                spikesorting.plot_waveforms(samples)


            ###############################################################################
            ax4 = plt.subplot2grid((numRows,numCols), (0,0), colspan = (numCols/2), rowspan = 3*sizeRasters)
            #plt.setp(ax4.get_xticklabels(), visible=False)
            #raster_sound_psycurve(centerFrequencies[0])
            raster_tuning(ax4)
            axvline(x=0, ymin=0, ymax=1, color='r')
            plt.gca().set_xlim(tuning_timeRange)

            #ax5 = plt.subplot2grid((7,6), (2,0), colspan = 3, sharex=ax4)
            #hist_sound_psycurve(centerFrequencies[0])

            ax6 = plt.subplot2grid((numRows,numCols), (0,(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters)
            plt.setp(ax6.get_xticklabels(), visible=False)
            plt.setp(ax6.get_yticklabels(), visible=False)
            raster_sound_psycurve(centerFrequencies[0])
            plt.title('Frequency Top: '+str(possibleFreq[centerFrequencies[0]])+' Bottom: '+str(possibleFreq[centerFrequencies[1]]))
            
            ax7 = plt.subplot2grid((numRows,numCols), (sizeRasters,(numCols/2)), colspan = (numCols/2), rowspan = sizeHists, sharex=ax6)
            hist_sound_psycurve(centerFrequencies[0])
            ax7.yaxis.tick_right()
            ax7.yaxis.set_ticks_position('both')
            plt.setp(ax7.get_xticklabels(), visible=False)
            plt.gca().set_xlim(timeRange)

            #ax8 = plt.subplot2grid((7,6), (3,0), colspan = 3, rowspan = 2)
            #plt.setp(ax8.get_xticklabels(), visible=False)
            #raster_movement_psycurve(centerFrequencies[0])
            #ax9 = plt.subplot2grid((7,6), (5,0), colspan = 3, sharex=ax8)
            #hist_movement_psycurve(centerFrequencies[0])

            ax10 = plt.subplot2grid((numRows,numCols), ((sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters)
            plt.setp(ax10.get_xticklabels(), visible=False)
            plt.setp(ax10.get_yticklabels(), visible=False)
            raster_sound_psycurve(centerFrequencies[1])

            ax11 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeHists, sharex=ax10)
            hist_sound_psycurve(centerFrequencies[1])
            ax11.yaxis.tick_right()
            ax11.yaxis.set_ticks_position('both')
            #plt.setp(ax11.get_yticklabels(), visible=False)
            plt.gca().set_xlim(timeRange)
            ###############################################################################
            #plt.tight_layout()
            
            modulation_index_psycurve(centerFrequencies)
            plt.suptitle(titleText)

            tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster)
            plt.gcf().set_size_inches((8.5,11))
            figformat = 'png' #'png' #'pdf' #'svg'
            filename = 'report_centerFreq_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,figformat)
            fulloutputDir = outputDir+subject +'/'
            fullFileName = os.path.join(fulloutputDir,filename)

            directory = os.path.dirname(fulloutputDir)
            if not os.path.exists(directory):
                os.makedirs(directory)
            #print 'saving figure to %s'%fullFileName
            plt.gcf().savefig(fullFileName,format=figformat)

            #plt.show()

        #except:##############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        #print "error with session "+oneCell.behavSession
            #if (oneCell.behavSession not in badSessionList):####################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                #badSessionList.append(oneCell.behavSession)#######################!!!!!!!!!!!!!!!!!!!!!!

    print 'error with sessions: '
    for badSes in badSessionList:
        print badSes
    # -- This part will be replace by something like behavioranalysis.find_trials_each_type --
    trialsEachFreq = []
    for indf, oneFreq in enumerate(possibleFreq):
        trialsEachFreq.append(
            np.flatnonzero(freqEachTrial == oneFreq)
        )  #finds indices of each frequency. Appends them to get an array of indices of trials sorted by freq

    # -- Calculate average firing for each freq --
    for indf, oneFreq in enumerate(possibleFreq):
        meanSpikesEachFrequency[indf] = np.mean(nSpikes[trialsEachFreq[indf]])

    clf()
    if (len(spkTimeStamps) > 0):
        ax1 = plt.subplot2grid((4, 4), (3, 0), colspan=1)
        spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
        ax3 = plt.subplot2grid((4, 4), (3, 3), colspan=1)
        spikesorting.plot_events_in_time(spkTimeStamps)
        samples = spkData.spikes.samples.astype(float) - 2**15
        samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples
        ax2 = plt.subplot2grid((4, 4), (3, 1), colspan=2)
        spikesorting.plot_waveforms(samples)
    ax4 = plt.subplot2grid((4, 4), (0, 0), colspan=3, rowspan=3)
    plot(spikeTimesFromEventOnset, sortedIndexForEachSpike, '.', ms=3)
    axvline(x=0, ymin=0, ymax=1, color='r')

    #The cumulative sum of the list of specific frequency presentations,
    #used below for plotting the lines across the figure.
    numTrials = cumsum(numTrialsEachFreq)

    #Plot the lines across the figure in between each group of sorted trials