% LFP Up-Down State Analyser : UpDownStateAnalyser(2012) - version 2013g
%
% - This GUI is part of the LFP analysis suite of programmes (2007/2009/2012) -
% 
%       Once your data has been read in you can select one of the analysis      % 
%       options from the drop down menu                                         % 
%                                                                               % 
%                                                                               % 
%  This Software is distributed under the GNU General Public Licence           % 
%  a copy of this licence sould be accompany this software.                    % 
%                                                                               % 
% Copyright (C) 2012-2013  Dominic KEOGH                              %
%                                                                               %  
% This program is free software; you can redistribute it and/or modify          %
% it under the terms of the GNU General Public License as published by          %
% the Free Software Foundation; either version 2 of the License, or             %
% (at your option) any later version.                                           %
%                                                                               % 
% This program is distributed in the hope that it will be useful,               %
% but WITHOUT ANY WARRANTY; without even the implied warranty of                %
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                 %
% GNU General Public License for more details.                                  %
%                                                                               %  
% You should have received a copy of the GNU General Public License             %
% along with this program; if not, write to the Free Software                   %
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA %
%                                                                               % 
%                                                                               
%  For further information contact Dominic Keogh at:
%  dominickeogh@hotmail.com
%  or Dr Rob Mason (project supervisor) rob.mason@notingham.ac.uk
%  lab web site: www.nottingham.ac.uk\neuronal-networks
%
%  if used in any research publications please cite .....


% SCRIPT NOTES:
% LFP UpDownStateAnalyser(2012-13)script: suggested by Dr Rob Mason, written by Dominic KEOGH (April-July 2012 as part of MSci Physics project)
% References:  give papers here i.e.  Author(s) (DATE); ....
% NOTE: data (*.mat) file must be contained within this script folder
% Run script - answer GUI prompts (right panels): DATA file to input;% THRESHOLD level: ....etc ... 
% export to EXCEL (Y/N)
% select data time frame to analyse; i.e. start time (s) / end time (s) 

% Results PLOTS available:
% (plot #1-3): raw LFP signal (Fig 1); Threshold plot (Fig 2); computed UP (=1) & DOWN (=0) state time-line; ....
% (plot #2): histogram(s) of number of UP/DOWN states; UP/DOWN state durations; .... 
% export processed data to EXCEL??
% set TimeFrame for Analysis - start time (s) / end time (s)

% script DEFAULT VALUES: frequency range (1-100Hz); Threshold (0.003); minimum 'distance' between UP states (0.04s); 
% LFP recording sampling rate = 1kHz (i.e. default Plexon recording system)


function experimentGUI

global SignalFile
SignalFile = [];
SelectedVar = [];
length_SelectedVar = [];
Frequency= [];
FourierSignal=[];
FrequencyFilteredSignal=[];
MinimumFrequency = 1;  
MaximumFrequency = 100;
time = [];
t1=[];
AcentuatedSignal=[];
SmoothedSignal=[];
ThresholdValue = 0.003;
ThresholdLine = [];
q = [];
StateSeperationDistance =0.04;
wb = [];
SelectedStartTime = [];
SelectedFinishTime = [];
definedSelectedVar = [];
SelectedVar1 = [];
SelectedTime = [];




%Create the main figure that the various panels and axes will be in
MainFigure = figure('Units','characters','MenuBar','none','Name',...
    'LFP Up-Down State Analyser (2012e)','NumberTitle','off','Units','characters','Position',[25 3 260 63],'ReSize',...
    'on','Visible','on');

%Insert a title for the main figure
MainFigureTitle = uicontrol('Parent',MainFigure,'Style','text','String',...
     'LFP Up-Down State Analyser (2012e)','Units','normalized','Position',...
     [0.45 0.96 0.20 0.04],'fontsize',11,'fontweight','bold'); 

%Create a panel to plot the original data signal
MainPlotPanel1 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[2 37 180 24],'Title','Raw LFP data');

%Create a panel underneath the first plot panel to plot the processed
%signal
MainPlotPanel2 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[2 16 180 20],'Title','Threshold Plot');

%Create a panel to the plot classified up and dopwn states
MainPlotPanel3 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[2 1.5 180 13.5],'Title','computed UP- & DOWN-states');

%Create panel to to place tools to load data files
MainLoadFilePanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[185 51 37 4],'Title','Load data file');

%Create a push button inside the load file panel to load data
MainLoadFileButton = uicontrol('Parent',MainLoadFilePanel,...
    'Style','pushbutton','String','Open File','Callback',...
    {@MainLoadFileButton_Callback},'Units','normalized', 'Position',...
    [0.1 0.1 0.7 0.8]);

%Create a panel to place tools to allow the selection of various reference
%panels
MainRefSelectPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[185 30 37 19.5],'Title','2. Select Channel to Analyse');

%Create a listbox to show the different reference channels
MainVariablesBox = uicontrol('Parent',MainRefSelectPanel,'Style','listbox',...
    'Units', 'normalized','Position',[0.1 0.15 0.8 0.8],'Callback',{@update_listbox},...
    'Value',1,'String',[]);

%Create a push button under reference channel listbox to slect the required
%channel
SelectChannelButton = uicontrol('Parent', MainRefSelectPanel,'Callback',...
    {@SelectChannelButton_Callback},...
    'String', 'Select Analysis Channel',...
    'Units','normalized', 'Position',[0.05 0.02 0.9 0.1]);

%Create sample rate input box
SampleRateInputPanel = uipanel('Parent', MainFigure,'Units','characters',...
    'Position',[185 25.5 37 4],'Title','Sample Rate');

%Create box to enter Sample rate
SampleRateInputBox = uicontrol('Parent',SampleRateInputPanel,'Style',...
    'edit','String','1000','Units','normalized','Position',...
    [0.22 0.3 0.5 0.5],'Callback',{@Input_Frequency});
%Put in string to give units of frequency
SampleRateBoxText = uicontrol('Parent',SampleRateInputPanel,'Style','text',...
    'String','Hz','Units','Normalized','Position',[0.72 0.4 0.2 0.35]);

%Create frequency filter box
    FrequencyFilterPanel = uipanel('Parent',MainFigure,'Units','characters',...
        'Position',[185 18.5 37 6],'Title','Frequency Filter Selection');
    %Create box to input minimum frequency value for filter
    MinimumFrequencyFilterInputBox = uicontrol('Parent',FrequencyFilterPanel,...
        'Style','edit','Units','normalized','Position',[0.32 0.6 0.2 0.28],...
        'String','1','Callback',{@InputMinimumFrequency});
   %Minimum frequency label
    MinimumFrequencyFilterLabel = uicontrol('Parent',FrequencyFilterPanel,...
        'Style','text','String','Min. Freq:','Units','normalized',...
        'Position',[0.02 0.6 0.3 0.28]);
    %Minimum frequency units
    MinimumFrequencyFilterUnits = uicontrol('Parent',FrequencyFilterPanel,...
        'Style','text','String','Hz','Units','normalized',...
        'Position',[0.52 0.6 0.3 0.28]);
    
    %Maximum frequency input box    
    MaximumFrequencyFilterInputBox = uicontrol('Parent',FrequencyFilterPanel,...
        'Style','edit','Units','normalized','Position',[0.32 0.1 0.2 0.28],...
        'String','100','Callback',{@InputMaximumFrequency});
    %Max frequency label
    MinimumFrequencyFilterLabel = uicontrol('Parent',FrequencyFilterPanel,...
        'Style','text','String','Max. Freq:','Units','normalized',...
        'Position',[0.02 0.1 0.3 0.28]);
    %Max frequency units
    MinimumFrequencyFilterUnits = uicontrol('Parent',FrequencyFilterPanel,...
        'Style','text','String','Hz','Units','normalized',...
        'Position',[0.52 0.1 0.3 0.28]);
    
    %Panel to put the seperation distance input box
    StateSeperationValueInputPanel = uipanel('Parent', MainFigure,'Units','characters',...
    'Position',[223 25.5 34 4],'Title','State Separation Distance');
    
    %Input box for seperation distance/time
    StateSeperationInputBox = uicontrol('Parent', StateSeperationValueInputPanel,...
        'Style','edit','Units','normalized','Position',[0.22 0.3 0.5 0.5],...
        'String','40','Callback',{@InputStateSeperationDistance});
    %Units for seperation of Up states, in thi case miliseconds
    StateSeperationUnits = uicontrol('Parent',StateSeperationValueInputPanel,...
        'Style','text','String','ms','Units','normalized',...
        'Position',[0.72 0.4 0.2 0.35]);



    

%Create axes in the first plot panel to plot the original data signal
MainPlotAxes1 = axes('Parent',MainPlotPanel1,'Units','pixels',...
    'Units','normalized','Position',[0.08,0.15,0.9,0.75]);
%Create a axes in the second plot panel to plot the processed signal
MainPlotAxes2 = axes('Parent',MainPlotPanel2,'Units','pixels',...
    'Units','normalized','Position',[0.08,0.15,0.9,0.75]);
MainPlotAxes3 = axes('Parent',MainPlotPanel3,'Units','pixels',...
    'Units','normalized','Position',[0.08,0.22,0.9,0.7]);


%Push button to process signal
 ProcessSignalButton = uicontrol('Parent',MainFigure,'Units','characters',...
     'Position',[185 15 25 2],'String','Process Signal','Callback',...
     {@Process_Signal});
 %panel to control the threshold value
 ThresholdValuePanel = uipanel('Parent',MainFigure,'Units','characters',...
     'Position',[185 9 37 5],'Title','Threshold Value');
 %Input box to allow user to type in desired threshold value
 ThresholdInputBox = uicontrol('Parent',ThresholdValuePanel,'Style','edit',...
     'String','Enter threshold value','Units','normalized','Position',...
     [0.1 0.4 0.8 0.4],'Callback',{@InputThresholdValue});

 %Slider to allow user to manually control threshold value ref line
 ThresholdSlider = uicontrol('Parent',MainFigure,'Style','Slider',...
     'Units','Characters','Position',[223 8 4 6],'SliderStep',...
     [0.001,0.01],'CallBack',{@plotThresholdLine});
 
  %Push button to classify states 
 ClassifyStatesButton = uicontrol('Parent',MainFigure,'Units','characters',...
     'Position',[185 4 25 2],'String','Classify States','Callback',...
     {@ClassifyStates});
    
    
 % Button that calls function to plot histogram   
 DownStateDurationHistogramButton = uicontrol('Parent',MainFigure,'Style','pushbutton',...
     'Units','Characters','Position',[227 3 30 4],'String','DOWN-State Duration Plot',...
     'Callback',{@IntervalsHistogram});
  %Button that calls function to plot histogram     
UPStateDurationHistogramButton = uicontrol('Parent',MainFigure,'Style','pushbutton',...
     'Units','Characters','Position',[227 8 30 4],'String','UP-State Duration Plot',...
    'Callback',{@UpStateDurationHistogram});

%Button to call function to display graphs in new figures
ExternalPlotButton = uicontrol('Parent',MainFigure,...
    'Style','pushbutton','String','LFP & U/D-States Plot','Callback',...
    {@externalplot},'Units','Characters','Position',[227 14 30 4]);


TimeFrameSelectionPanel =uipanel('Parent', MainFigure,'Units','characters',...
    'Position',[223 18.5 34 6],'Title','Analysis Time Frame');

StartTimeInputBox = uicontrol('Parent',TimeFrameSelectionPanel,...
        'Style','edit','Units','normalized','Position',[0.32 0.6 0.2 0.28],...
        'String','0','Callback',{@InputStartTime_Callback});
   %Minimum frequency label
    StartTimeLabel = uicontrol('Parent',TimeFrameSelectionPanel,...
        'Style','text','String','START Time:','Units','normalized',...
        'Position',[0.02 0.6 0.3 0.28]);
    %Minimum frequency units
    StartTimeUnits = uicontrol('Parent',TimeFrameSelectionPanel,...
        'Style','text','String','s','Units','normalized',...
        'Position',[0.52 0.6 0.3 0.28]);
    
    %Maximum frequency input box    
    FinishTimeInputBox = uicontrol('Parent',TimeFrameSelectionPanel,...
        'Style','edit','Units','normalized','Position',[0.32 0.1 0.2 0.28],...
        'Callback',{@InputFinishTime_Callback});
    %Max frequency label
    FinishTimeLabel = uicontrol('Parent',TimeFrameSelectionPanel,...
        'Style','text','String','END Time:','Units','normalized',...
        'Position',[0.02 0.1 0.3 0.28]);
    %Max frequency units
    FinishTimeUnits = uicontrol('Parent',TimeFrameSelectionPanel,...
        'Style','text','String','s','Units','normalized',...
        'Position',[0.52 0.1 0.3 0.28]);

    SelectTimeFrameButtonOK = uicontrol('Parent',TimeFrameSelectionPanel,...
        'String','OK','Units','normalized',...
        'Position',[0.72 0.23 0.25 0.5],'Callback',...
        {@SelectTimeFrameButtonOK_Callback});


%This function operates when the 'Open File' pushbutton is pressed,
    %function opens a user interface box to allow a data file to be
    %selected
    function MainLoadFileButton_Callback (hObject, eventdata)
             [filename pathname] = uigetfile('*.mat',pwd);
             SignalFile = fullfile(pathname,filename);
             %Signal file is the name assigned to the selected data file
             loadfile();
             %Runs the function load file
    end


    %The function loadfile will load the file selcted by the user into the
    %matlab workspace
    function loadfile
        
        evalin('base', ['load (''' SignalFile ''')']);
        % the function evalin allows a fuinction to be carried out in the
        % matlab workspace

        update_listbox()
        %run function listbox
    end


    %This function displays the different variables from the selcted data
    %file in to the reference channel listbox in the GUI
    function update_listbox(hObject,eventdata)
    vars = evalin('base','who');
    %varibale vars is an array of all the various data sets or variable
    %from the selected data file
    set(MainVariablesBox,'String',vars);
    %displays the variables in the listbox
    end



    %This function operates when the 'Select REference channle' button is
    %pressed.
    function SelectChannelButton_Callback(hObject, eventdata)
        SelectedVarValue = get(MainVariablesBox,'Value');
        %This gets the variable that is selected by the user in the listbox
        SelectedVarStrings = get(MainVariablesBox,'String');
        SelectedVar = SelectedVarStrings{SelectedVarValue};
        plot_selected_channel()
        %Runs ths function plot_selected_channel
    end

SampleRate = 1000;
    function Input_Frequency(hObject,eventdata)
        SampleRate = str2double(get(hObject,'String'));
        plot_selected_channel()
    end

    %This function operates once a variable is selected
    function plot_selected_channel(hObject,eventdata)
        length_SelectedVar = length(evalin('base',SelectedVar));
        %Finds the number of pieces of data
        time=(0:1/SampleRate:((length_SelectedVar)/SampleRate)-1/SampleRate)';
        %Defines the time duration of the signal recording 
        plot(MainPlotAxes1,time,(evalin('base',SelectedVar)))
        %plots the selceted reference channel agianst time and dispays it
        %in the first axes
        axes(MainPlotAxes1);
        % title('LFP Raw data');
        xlabel('Time (s)');
        ylabel('LFP Amplitude (mV)');
        axis tight;
        SelectedVar1 = evalin('base',SelectedVar);
        
        %The section below involves setting default values
        %for the Analysis time frame tool since now the time duration of
        %the sample is known
        
        set(FinishTimeInputBox,'String',num2str(max(time)));
        %Default values are set for analysis time frame
        SelectedFinishTime = max(time);
        SelectedStartTime = 0;
    end

    %function to convert frequency string inputted by user into value
    function InputMinimumFrequency(hObject,eventdata)
        MinimumFrequency = str2double(get(hObject,'String'));
        %Re run process signal function with new frequency value
        Process_Signal()
    end
%function to convert frequency string inputted by user into value
function InputMaximumFrequency(hObject,eventdata)
        MaximumFrequency = str2double(get(hObject,'String'));
        %Re run process signal function with new frequency value
        Process_Signal()
    end


    %function runs runs continually other functions to process signal
    function Process_Signal(hObject,eventdata)
        wb= waitbar2a(0.1, 'Please wait...');
        FourierTransform();
        SelectFrequencyBand()
        InverseFourierTransform()
        AcentuateSignal()
        SmoothSignal() 
        %plotThresholdLine()
        
    end

        %function does a fourier transform on original signal
        function FourierTransform(hObject,eventdata)
                 
            FourierSignal = (fft(SelectedVar1));
            FourierSignal = fftshift(FourierSignal);
           
            Frequency = [linspace(-(SampleRate)/2,(SampleRate)/2,...
           length(FourierSignal))];
            %waitbar2a updates the progress box to 20% complete 
           waitbar2a(0.2, wb);
        end

            %function filters out required frequencies
            function SelectFrequencyBand 
            for k = 1:(length(Frequency));
               if Frequency(k)<MinimumFrequency;
                Frequency(k) = 0;
                FourierSignal(k) = 0;
               elseif Frequency(k)>MaximumFrequency;
                Frequency(k) = 0;
                FourierSignal(k) = 0;
               end
            end
            waitbar2a(0.4, wb);
           
            end

        %function does inverse fourier transform to go back to time domain
        function InverseFourierTransform
        FrequencyFilteredSignal = ifftshift(FourierSignal);
        FrequencyFilteredSignal = abs(ifft(FourierSignal));
        
        waitbar2a(0.6, wb);
        end
    
    %function does a standard deviation in a running frame
    function AcentuateSignal
        for k =1:length(FrequencyFilteredSignal)-4;
        i = k;
        u = [FrequencyFilteredSignal(i) FrequencyFilteredSignal(i+1)...
            FrequencyFilteredSignal(i+2) FrequencyFilteredSignal(i+3)...
            FrequencyFilteredSignal(i+4)];
        AcentuatedSignal(k) = std(u);
        end
        for k = 1:length(AcentuatedSignal);
        t1(k) =time(k);
        end
        waitbar2a(0.8, wb);
    end

    %function smooths signal using matlabs 'filter' function
    function SmoothSignal
        windowSize = 750 ;
        SmoothedSignal = filter(ones(1,windowSize)/windowSize,1,...
            AcentuatedSignal);
        for k = 1:length(AcentuatedSignal);
        t1(k) =time(k);
        end
        waitbar2a(1, wb);
        close(wb);
        %plot processed signal
        SmoothedSignalPlot = plot(MainPlotAxes2,t1,SmoothedSignal);
        
        
        % these parameters need to be set for the threshold value slider
        set(ThresholdSlider,'Max',0.1);
        set(ThresholdSlider,'Min',0);
        set(ThresholdSlider,'Value',mean(SmoothedSignal));
        ThresholdLine = [];
        axes(MainPlotAxes2);
        axis tight;
        %plots reference hreshold value line
        ThresholdLine = graph2d.constantline(ThresholdValue, 'Color','r');
        ylabel('Processed Signal');
        xlabel('Time (s)');
    end
        
    %get threshold value from slider control
    function plotThresholdLine(hObject,eventdata)
        ThresholdValue =(get(hObject,'Value'));
        set(ThresholdInputBox,'String',[num2str(ThresholdValue)]);
        plotline()
    end

    %
    function InputThresholdValue(hObject,eventdata)
       
                
        ThresholdValue = str2double(get(hObject,'String'));
        
                
        plotline()
    end
    
    %plot ref threshold line
    function plotline
            hold(MainPlotAxes2);
            delete(ThresholdLine);
            
            axes(MainPlotAxes2);
            ThresholdLine = graph2d.constantline(ThresholdValue, 'Color','r');
            

    end


    %function called on pressing of classify states button,
    %classifies states and implements minimum value for down state
    function ClassifyStates(hObject,eventdata)
        
        for k = 1:length(SmoothedSignal);
            if SmoothedSignal(k) <= ThresholdValue;
            q(k) = 0;
            elseif SmoothedSignal(k)>ThresholdValue;
            q(k)= 1;
            end
        end
        


start_times_pos = ((find(diff(q)==1)));
finish_times_pos = ((find(diff(q) == -1)));

start_times = t1(start_times_pos);
finish_times = t1(finish_times_pos);


if q(1) ==0 && q(length(q))==0;

for k = 1:length(start_times);
duration_upstate(k) = (finish_times(k))- (start_times(k));
end


for k = 2:length(start_times);
    
    state_interval(1) = (start_times(1));
    
     
    
    state_interval(k) = (start_times(k))-(finish_times(k-1));
    
    state_interval(length(start_times)+1) = (length(t1))-(finish_times(length(finish_times)));
end

elseif q(1) ==1 && q(length(q))==1;
         
    for k = 2:length(start_times);
    duration_upstate(1) =(finish_times(1));
    duration_upstate(k) = (finish_times(k))-(start_times(k-1));
    duration_upstate(length(start_times)+1) = (length(t1))-(start_times(length(finish_times)));
    end
    
    for k = 1:length(start_times);
        state_interval(k) = (start_times(k))-(finish_times(k));
    end
    
elseif q(1) == 1 && q(length(q)) == 0;
    
    for k = 2:length(finish_times);
    duration_upstate(1) = (finish_times(1));
    duration_upstate(k) = (finish_times(k))-(start_times(k-1));
    end
    
    for k = 1:length(start_times);
        state_interval(k) = (start_times(k))-(finish_times(k));
        
        state_interval(length(start_times)+1) = (length(t1))-(finish_times(length(finish_times)));
    end
    
elseif q(1) == 0 && q(length(q)) == 1;
    for k = 1:length(finish_times);
        duration_upstate(k) = (finish_times(k))-(start_times(k));
        
        duration_upstate(length(start_times)) = (length(t1))-(start_times(length(start_times)));
    end
    
    for k = 2:length(start_times);
        state_interval(1) = (start_times(1));
        state_interval(k) = (start_times(k))-(finish_times(k-1));
    end
 
   
end





for k = 1:length(start_times);
if state_interval(k) <=StateSeperationDistance;
    if k-1 >= 1
    
    v = start_times(k-1);
    w = start_times(k);
      
    for k = 1:length(t1);
        if t1(k) >= v && t1(k) <= w;
        q(k) = 1;
        end
    end
    end
end
end

for k = 1:length(finish_times);
if state_interval(k) <=StateSeperationDistance;
    %if k-1 > 0
    
    v = finish_times(k);
    w = start_times(k);
      
    for k = 1:length(t1);
        if t1(k) >= v && t1(k) <= w;
        q(k) = 1;
        end
    %end
    end
end
end
        
        
 
        
        
        
        
        axes(MainPlotAxes3);
        plot(MainPlotAxes3,t1,q);
        axis([min(t1) max(t1) 0 2]);
       % title('computed Up-/Down-States');
        xlabel('Time (s)');
        ylabel('Up-State = 1');
        set(gca,'YTick',[0 1]);
        
    end
    
    % runs if user changes value of state seperation distance
    function InputStateSeperationDistance(hObject,eventdata)
        StateSeperationDistance = (str2double(get(hObject,'String')))/1000;
        ClassifyStates();
    end




    %plots histogram in new figure
 function IntervalsHistogram(hObject,eventdata)

IntervalsHistogramFigure = figure('Units','Characters','Position',[25 3 200 55],...
    'Name','Interval Time Histogram');
HistogramAxes = axes('Parent',IntervalsHistogramFigure,'Units','Normalized',...
    'Position',[0.05 0.05 0.6 0.9]);
DataDisplayTable = uitable('Parent',IntervalsHistogramFigure,'Units','Normalized',...
    'Position',[0.68 0.05 0.095 0.9],'ColumnName',{'Duration (s)'});

start_times_pos = ((find(diff(q)==1)));
finish_times_pos = ((find(diff(q) == -1)));

start_times = t1(start_times_pos);
finish_times = t1(finish_times_pos);


if q(1) ==0 && q(length(q))==0;

for k = 1:length(start_times);
duration_upstate(k) = (finish_times(k))- (start_times(k));
end


for k = 2:length(start_times);
    
    state_interval(1) = (start_times(1));
    
     
    
    state_interval(k) = (start_times(k))-(finish_times(k-1));
    
    
end

elseif q(1) ==1 && q(length(q))==1;
         
    for k = 2:length(start_times);
    duration_upstate(1) =(finish_times(1));
    duration_upstate(k) = (finish_times(k))-(start_times(k-1));
    duration_upstate(length(start_times)+1) = (length(t1))-(start_times(length(finish_times)));
    end
    
    for k = 1:length(start_times);
        state_interval(k) = (start_times(k))-(finish_times(k));
    end
    
elseif q(1) == 1 && q(length(q)) == 0;
    
    for k = 2:length(finish_times);
    duration_upstate(1) = (finish_times(1));
    duration_upstate(k) = (finish_times(k))-(start_times(k-1));
    end
    
    for k = 1:length(start_times);
        state_interval(k) = (start_times(k))-(finish_times(k));
        
        state_interval(length(start_times)+1) = (length(t1))-(finish_times(length(finish_times)));
    end
    
elseif q(1) == 0 && q(length(q)) == 1;
    for k = 1:length(finish_times);
        duration_upstate(k) = (finish_times(k))-(start_times(k));
        
        duration_upstate(length(start_times)) = (length(t1))-(start_times(length(start_times)));
    end
    
    for k = 2:length(start_times);
        state_interval(1) = (start_times(1));
        state_interval(k) = (start_times(k))-(finish_times(k-1));
    end
 
   
end

data = state_interval';
set(DataDisplayTable,'Data',data);

for k = 1:length(state_interval);
        if state_interval(k) < 10;
        filtered_state_interval(k) = state_interval(k);
        end    

end

hist(filtered_state_interval,10);
title('Down-State Duration');
ylabel('No. of Down States');
xlabel('Time (s)');

 end

    %plots Up-state time duration histogram in new figure
function UpStateDurationHistogram(hObject,eventdata)


UpStateDurationHistogramFigure = figure('Units','Characters','Position',[25 3 200 55],...
    'Name','Up State time Histogram');
HistogramAxes = axes('Parent',UpStateDurationHistogramFigure,'Units','Normalized',...
    'Position',[0.05 0.05 0.6 0.9]);
DataDisplayTable = uitable('Parent',UpStateDurationHistogramFigure,'Units','Normalized',...
    'Position',[0.68 0.05 0.095 0.9],'ColumnName',{'Duration (s)'});
NumberStatesText = uicontrol('Parent',UpStateDurationHistogramFigure,'Style',...
    'text','Units','Normalized','Position',[0.78 0.9 0.2 0.03]);
UpStateRateText = uicontrol('Parent',UpStateDurationHistogramFigure,'Style',...
    'text','Units','Normalized','Position',[0.78 0.85 0.2 0.03]);
MeanUpStateTimeText = uicontrol('Parent',UpStateDurationHistogramFigure,'Style',...
    'text','Units','Normalized','Position',[0.78 0.7 0.2 0.03]);
UpStateTimeStandardDeviationText = uicontrol('Parent',UpStateDurationHistogramFigure,'Style',...
    'text','Units','Normalized','Position',[0.78 0.65 0.2 0.03]);

start_times_pos = ((find(diff(q)==1)));
finish_times_pos = ((find(diff(q) == -1)));

start_times = t1(start_times_pos);
finish_times = t1(finish_times_pos);


if q(1) ==0 && q(length(q))==0;

for k = 1:length(start_times);
duration_upstate(k) = (finish_times(k))- (start_times(k));
end


for k = 2:length(start_times);
    
    state_interval(1) = (start_times(1));
    
     
    
    state_interval(k) = (start_times(k))-(finish_times(k-1));
    
    state_interval(length(start_times)+1) = (length(t1))-(finish_times(length(finish_times)));
end

elseif q(1) ==1 && q(length(q))==1;
         
    for k = 2:length(start_times);
    duration_upstate(1) =(finish_times(1));
    duration_upstate(k) = (finish_times(k))-(start_times(k-1));
    duration_upstate(length(start_times)+1) = (length(t1))-(start_times(length(finish_times)));
    end
    
    for k = 1:length(start_times);
        state_interval(k) = (start_times(k))-(finish_times(k));
    end
    
elseif q(1) == 1 && q(length(q)) == 0;
    
    for k = 2:length(finish_times);
    duration_upstate(1) = (finish_times(1));
    duration_upstate(k) = (finish_times(k))-(start_times(k-1));
    end
    
    for k = 1:length(start_times);
        state_interval(k) = (start_times(k))-(finish_times(k));
        
        state_interval(length(start_times)+1) = (length(t1))-(finish_times(length(finish_times)));
    end
    
elseif q(1) == 0 && q(length(q)) == 1;
    for k = 1:length(finish_times);
        duration_upstate(k) = (finish_times(k))-(start_times(k));
        
        duration_upstate(length(start_times)) = (length(t1))-(start_times(length(start_times)));
    end
    
    for k = 2:length(start_times);
        state_interval(1) = (start_times(1));
        state_interval(k) = (start_times(k))-(finish_times(k-1));
    end
 
   
end

data = duration_upstate';
set(DataDisplayTable,'Data',data);


for k = 1:length(duration_upstate);
        if duration_upstate(k) < 10;
        filtered_duration_upstate(k) = duration_upstate(k);
        end    

end


set(NumberStatesText,'String',['Number of Up-States = ',num2str(length(duration_upstate))]);

UpStateRate = (length(duration_upstate))/(max(t1));
set(UpStateRateText,'String',['UP-State Rate = ',num2str(UpStateRate),' /s']);

MeanUpStateTime = mean(duration_upstate);
set(MeanUpStateTimeText,'String',['Mean Up-State Time = ',num2str(MeanUpStateTime),' /s']);

UpStateTimeStandardDeviation = std(duration_upstate);
set(UpStateTimeStandardDeviationText,'String',['Standard Deviation = ',num2str(UpStateTimeStandardDeviation),' /s']);


hist(filtered_duration_upstate,10);
title('Up-State Duration ');
ylabel('No. of Up States');
xlabel('Time (s)');

end


    %function called to display plots in new figures
    function externalplot(hObject,eventdata)
        
        figure;
        subplot(211);
        plot(time,SelectedVar1);
        title('LFP Raw Signal');
        ylabel('Voltage (mV)');
        xlabel('Time (s)');
        subplot(212);
        plot(t1,q);
        title('computed Up-/Down-States');
        xlabel('Time (s)');
        ylabel('1 = Up State 0 = Down State')
        ylim([0 2]);
        set(gca,'YTick',[0 1]);
        
        figure;
        plot(t1,q);
        title('computed Up-/Down-States');
        xlabel('Time (s)');
        ylabel('1 = Up State 0 = Down State')
        ylim([0 2]);
        set(gca,'YTick',[0 1]);
    end




    function InputStartTime_Callback(hObject,eventdata)
        SelectedStartTime = str2double(get(hObject,'String'));
    end

    function InputFinishTime_Callback(hObject,eventdata)
        SelectedFinishTime = str2double(get(hObject,'String'));
    end

    function SelectTimeFrameButtonOK_Callback(hObject,eventdata)
        SelectedTime = SelectedStartTime:1/SampleRate:SelectedFinishTime;
        
        
        SelectedStartTime_Pos = find(time == SelectedStartTime);
        SelectedFinishTime_Pos = find(time == SelectedFinishTime);
    
        
        % Locates the indices of the segment within the channel signal
            segment_indices = [SelectedStartTime*SampleRate+1, SelectedFinishTime*SampleRate+1];
            
            % Extracts the segment from the channel signal
            SelectedVar1 = evalin('base',sprintf('%s(%d:%d)',...
                SelectedVar,segment_indices(1),segment_indices(...
                2)));
        plot(MainPlotAxes1,SelectedTime,SelectedVar1);
        time = SelectedTime;
    end

end






