function varargout = interPSD(varargin)
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%     G U I   H E L P   I N F O R M A T I O N                                   % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% interPSD m-file for interPSD.fig                                              % 
%                                                                               % 
%       The GUI is part of the LFP Analysis Package 2006 and is to be           %     
%       Launched from the Fron_Panel Window of the Package                      %
%                                                                               % 
%       The software is designed to provide the user with the ability to        %
%       generate Power Spectral Densities with custom options whenever          %
%       possible. It then launches PSD.fig.                                     %
%                                                                               % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 

%  This Software is distributed under the GNU General Public Liscence           % 
%  a copy of this liscence sould be accompany this software.                    % 
%                                                                               % 
% Copyright (C) 2006  Richard Peter                                             %
%                                                                               %  
% 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 Richard Peter at                             % 
%  infinitybeckon@hotmail.com                                                   % 
%                                                                               %   
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 


% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @interPSD_OpeningFcn, ...
                   'gui_OutputFcn',  @interPSD_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before interPSD is made visible.
function interPSD_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to interPSD (see VARARGIN)

% Choose default command line output for interPSD
handles.output = hObject;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Refresh the window, ie reset to default selections
refresh_window(handles);

%%%%%%%%%%%%%%%%
%Userdata

%Read in the variables that have been passed to it from the front panel
%window
handles.userdata = varargin{1};
handles.user_start = varargin{2};
handles.user_end = varargin{3};
handles.tstep = varargin{4};

%or enter them manually for debug mode: 
% handles.userdata = evalin('base', 'AD01(1:1000)');
% handles.user_start = 0;
% handles.user_end = 999;
% handles.tstep = 1000;
%%%%%%%%%%%%%%%%%


%Initialise other variables
handles.CustomBands = [];
handles.Wdow = [];
handles.NotchVals = [];
%Populate teh Custom Window List
set(handles.OwnWdowList,'String',evalin('base','who'))

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes interPSD wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = interPSD_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in SetNotchTgl. calls NotchSet to specify
% the limits of the notch filters and stores the result as an m x 1 array
% in  handles.NotchVals
function SetNotchTgl_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of SetNotchTgl

if(get(hObject,'Value') == get(hObject,'Max'))
    % We first check whether the toggle button has been turned on, 
    %Next we create an empty vector of Notch limits
    %Now we launch the NotchSet GUI
    [handles.NotchVals, Y] = NotchSet(handles);
    set(handles.SetNotchTgl, 'Value', Y);
end %End if

%Save the handles structure
guidata(hObject, handles);
% End of Function

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
%                                                                         %
% --- Executes on button press in GoBtn.                                  %
% Upon pressing this button, the data is PSD'd then sent to PSD.m to be   %
% plotted and the PSD Analysed.                                           %
%                                                                         %
% The Algorithm follows the following Pseudo Code...                      %
% Filter Data using Notch Filters and store result                        %
% Input User specified Data/Options into the selected PSD method's function
% send the result to PSD.m                                                %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function GoBtn_Callback(hObject, eventdata, handles)
% hObject    handle to GoBtn (see GCBO)

% Notch Filter stuff
if get(handles.SetNotchTgl, 'Value')
    %The user wants to use filters
    Coeffs = fir1(1000, [handles.NotchVals]/handles.tstep*2, 'stop');
    handles.userdata = filtfilt(Coeffs, 1,  handles.userdata);
end




% Generate User's Window if desired.                                      
% % % % % % % % % % % % % % % % % % % 
if  get(handles.DfaultWdowBtn, 'Value')==0
    %If the user has selected SOMETHING from the workspace (may not be a
    %window!) (Assume not!)
    window = get_var_names(handles.OwnWdowList);
    handles.Wdow = evalin('base', window);
    if size(handles.Wdow, 2)>1
        handles.Wdow = handles.Wdow';
        if size(handles.Wdow, 2)>1
            %If its still the wrong size, then tell them its not a valid
            %window and must be a vector!
                errordlg('Your Window must be a vector. [m x 1] or [1 x m]',...
            'Incorrect Selection','modal')
        return %Leave the function Now.
        end %if
    end %if  
else
    handles.Wdow = []; %We'll assign this in GeneratePSD
end %if
%The User's window is now stored in handles.Wdow;


% Now the PSD Bit                                                         
% % % % % % % % % % % % % % % % %

[Pxx, handles.f, handles.Hpsd] = GeneratePSD(handles);
%Initialise some varaibles to pass to the PSD window
handles.method = get(handles.MethodDrpDwn, 'Value');
if handles.method ==3 
    %if its a taper method tehn the Pxx contains estimate info
    handles.Pxxc = Pxx{2};
    handles.Pxx  = Pxx{1};
else
    handles.Pxx = Pxx;
end %if

handles.FreqAx = get(handles.PlotFreq, 'Value'); %Boolean for x axis in Hz
%finally, call the next window...
PSD(handles);



% --- Executes on button press in DeltaBtn.
function DeltaBtn_Callback(hObject, eventdata, handles)
% hObject    handle to DeltaBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of DeltaBtn


% --- Executes on button press in ThetaBtn.
function ThetaBtn_Callback(hObject, eventdata, handles)
% hObject    handle to ThetaBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of ThetaBtn


% --- Executes on button press in AlphaBtn.
function AlphaBtn_Callback(hObject, eventdata, handles)
% hObject    handle to AlphaBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of AlphaBtn


% --- Executes on button press in BetaBtn.
function BetaBtn_Callback(hObject, eventdata, handles)
% hObject    handle to BetaBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of BetaBtn


% --- Executes on button press in GamLBtn.
function GamLBtn_Callback(hObject, eventdata, handles)
% hObject    handle to GamLBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of GamLBtn


% --- Executes on button press in GamHBtn.
function GamHBtn_Callback(hObject, eventdata, handles)
% hObject    handle to GamHBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of GamHBtn





% --- Executes on button press in GamVHBtn.
function GamVHBtn_Callback(hObject, eventdata, handles)
% hObject    handle to GamVHBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of GamVHBtn


% --- Executes on button press in SelectAllCQ.
function SelectAllCQ_Callback(hObject, eventdata, handles)
if(get(hObject,'Value') == get(hObject,'Max'))
    % Then checkbox is checked- select all defalut frequency bands
    set(handles.AlphaBtn,'Value',1);
    set(handles.BetaBtn,'Value',1);
    set(handles.DeltaBtn,'Value',1);
    set(handles.ThetaBtn,'Value',1);
    set(handles.GamLBtn,'Value',1);
    set(handles.GamHBtn,'Value',1);
    set(handles.GamVHBtn,'Value',1);
else 
    % The user wants top deselect all Frequency Bands
    set(handles.AlphaBtn,'Value',0);
    set(handles.BetaBtn,'Value',0);
    set(handles.DeltaBtn,'Value',0);
    set(handles.ThetaBtn,'Value',0);
    set(handles.GamLBtn,'Value',0);
    set(handles.GamHBtn,'Value',0);
    set(handles.GamVHBtn,'Value',0);
end %End If

% save the handles structure 
guidata(hObject, handles);
% End of Function            

% --- Executes on button press in JoinAdjBnds.
function JoinAdjBnds_Callback(hObject, eventdata, handles)
% hObject    handle to JoinAdjBnds (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of JoinAdjBnds


% --- Executes on button press in CustomBndTgl.
function CustomBndTgl_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of CustomBndTgl
if(get(hObject,'Value') == 1)
    % We first check whether the toggle button has been turned on, 
       % Then get the user's bands
    [handles.CustomBands, Y] = CustomFilters(handles);
    set(hObject, 'Value', Y);
    handles;
end %End if


% Update handles structure
guidata(hObject, handles);


% --- Executes on button press in PlotOrigSig.
function PlotOrigSig_Callback(hObject, eventdata, handles)
% hObject    handle to PlotOrigSig (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of PlotOrigSig


% --- Executes on button press in DfaultWdowBtn.
function DfaultWdowBtn_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of DfaultWdowBtn
if get(hObject, 'Value') 
    %If the user wants a default and the Method default is selected
 set(handles.ViewWdowBtn, 'Enable', 'on');
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowList, 'Enable', 'on');
    set(handles.OwnWdowList, 'Enable', 'off');
    set(handles.OwnWdowBtn, 'Value', 0);
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowOlap, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.WdowLengthBtn, 'Enable', 'on');
    set(handles.WdowOlapBtn, 'Value', 0);
    set(handles.WdowLengthBtn, 'Value', 0);
    if get(handles.MethodDrpDwn, 'Value')==1
        %If the user doesn't want a scalogram
        set(handles.WdowOlapBtn, 'Enable', 'off');
        set(handles.WdowLengthBtn, 'Enable', 'off');
    end %if
else
    %The user does not want a default window...change to own window
    set(handles.OwnWdowBtn, 'Value', 1);
    set(handles.WdowList, 'Enable', 'off');
    set(handles.OwnWdowList, 'Enable', 'on');
    set(handles.ViewWdowBtn, 'Enable', 'on');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Value', 0);
    set(handles.WdowOlap, 'Enable', 'off');
    set(handles.WdowLengthBtn, 'Enable', 'on');
    set(handles.WdowLengthBtn, 'Value', 0);
    set(handles.WdowLength, 'Enable', 'off');
    if get(handles.MethodDrpDwn, 'Value')==1
        %If the user does want a scalogram
        set(handles.WdowOlapBtn, 'Enable', 'off');
        set(handles.WdowLengthBtn, 'Enable', 'off');
    end %if
end %if

% --- Executes on selection change in OwnWdowList.
function OwnWdowList_Callback(hObject, eventdata, handles)
% hObject    handle to OwnWdowList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns OwnWdowList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from OwnWdowList


% --- Executes during object creation, after setting all properties.
function OwnWdowList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to OwnWdowList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in OwnWdowBtn.
function OwnWdowBtn_Callback(hObject, eventdata, handles)
% hObject    handle to OwnWdowBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(get(hObject, 'Value'))
    set(handles.ViewWdowBtn, 'Enable', 'on');
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowList, 'Enable', 'off');
    set(handles.OwnWdowList, 'Enable', 'on');
    set(handles.DfaultWdowBtn, 'Value', 0);
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowOlap, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.WdowLengthBtn, 'Enable', 'on');
        set(handles.WdowOlapBtn, 'Value', 0);
    set(handles.WdowLengthBtn, 'Value', 0);
    if get(handles.MethodDrpDwn, 'Value')==1
        %If the user doesn't want a scalogram
        set(handles.WdowOlapBtn, 'Enable', 'off');
        set(handles.WdowLengthBtn, 'Enable', 'off');
    end %if
else
    %The user does not want a custom window...change to default window
    set(handles.DfaultWdowBtn, 'Value', 1);
    set(handles.WdowList, 'Enable', 'on');
    set(handles.OwnWdowList, 'Enable', 'off');
    set(handles.ViewWdowBtn, 'Enable', 'on');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Value', 0);
    set(handles.WdowOlap, 'Enable', 'off');
    set(handles.WdowLengthBtn, 'Enable', 'on');
    set(handles.WdowLengthBtn, 'Value', 0);
    set(handles.WdowLength, 'Enable', 'off');
    if get(handles.MethodDrpDwn, 'Value')==1
        %If the user does want a scalogram
        set(handles.WdowOlapBtn, 'Enable', 'off');
        set(handles.WdowLengthBtn, 'Enable', 'off');
    end %if
end %if
%End of function
    
% Hint: get(hObject,'Value') returns toggle state of OwnWdowBtn


% --- Executes on button press in ViewWdowBtn.
function ViewWdowBtn_Callback(hObject, eventdata, handles)
N = length(handles.userdata);
error = 0; %define the error marker;
if get(handles.DfaultWdowBtn, 'Value')
    %make the user's window if they havent already selected one...
    %this if statement determines how long the window should be
    if get(handles.MethodDrpDwn, 'Value')==1
        %If its a periodogram then it must be the length as the data
        handles.WdowLen = N;
    elseif get(handles.WdowLengthBtn, 'Value')==0
        %if they havent specified then its the default for the PSD method, set
        %it to N for now.
        handles.WdowLen = N;
    else
        %else set it to what they define
        handles.WdowLen = str2num(get(handles.WdowLength, 'String'));
    end %if

    %Make the window they require if possible
    win = GenerateWdow(handles);
else
    window = get_var_names(handles.OwnWdowList);
    win = evalin('base', window);
    if size(win, 2)>1
        win = win';
        if size(win, 2)>1
            %If its still the wrong size, then tell them its not a valid
            %window and must be a vector!
            error = 1;
            errordlg('Your Window must be a vector. [m x 1] or [1 x m]',...
                'Incorrect Selection','modal')
            return %Leave the function Now.
        end %if
    end %if
end %If / if not default
if (error==0)
    wvtool(win);
end


% --- Executes on selection change in WdowList.
function WdowList_Callback(hObject, eventdata, handles)
% hObject    handle to WdowList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns WdowList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from WdowList

%set(handles.ViewWdowBtn, 'Enable', 'on');

% --- Executes during object creation, after setting all properties.
function WdowList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to WdowList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function WdowLength_Callback(hObject, eventdata, handles)
% hObject    handle to WdowLength (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of WdowLength as text
%        str2double(get(hObject,'String')) returns contents of WdowLength as a double


% --- Executes during object creation, after setting all properties.
function WdowLength_CreateFcn(hObject, eventdata, handles)
% hObject    handle to WdowLength (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in MethodDrpDwn.
function MethodDrpDwn_Callback(hObject, eventdata, handles)
% hObject    handle to MethodDrpDwn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns MethodDrpDwn contents as cell array
%        contents{get(hObject,'Value')} returns selected item from MethodDrpDwn
if get(hObject, 'Value')==1
    %the user wants a periodogram, so disable appropriate features
    set(handles.WdowOlap, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Value', 0);
    set(handles.WdowLengthBtn, 'Value', 0);
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowLengthBtn, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.DfaultWdowBtn, 'Enable', 'on');
    set(handles.WdowList, 'Enable', 'on');
    set(handles.OwnWdowBtn, 'Enable', 'on');
    set(handles.ViewWdowBtn, 'Enable', 'on');
        set(handles.Plot2Sided, 'Enable', 'on');
    set(handles.Plot1Sided, 'Enable', 'on');
    set(handles.MTM, 'Enable', 'off');
elseif get(hObject, 'Value')==3
    %I fhte user has selected the multitaper method they do not choose a
    %window...
    set(handles.MTM, 'Enable', 'on');
        set(handles.Plot2Sided, 'Enable', 'off');
    set(handles.Plot1Sided, 'Enable', 'off');
    set(handles.PlotFreq, 'Value', 1);
    set(handles.Plot1Sided, 'Value', 0);
    set(handles.Plot2Sided, 'Value', 0);
    set(handles.WdowOlap, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Value', 0);
    set(handles.WdowLengthBtn, 'Value', 0);
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowLengthBtn, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.DfaultWdowBtn, 'Enable', 'off');
    set(handles.WdowList, 'Enable', 'off');
    set(handles.OwnWdowBtn, 'Enable', 'off');
    set(handles.ViewWdowBtn, 'Enable', 'off');
else %The user want to use welch's method...
        set(handles.Plot2Sided, 'Enable', 'on');
    set(handles.Plot1Sided, 'Enable', 'on');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.WdowLengthBtn, 'Enable', 'on');
    set(handles.DfaultWdowBtn, 'Enable', 'on');
    set(handles.WdowList, 'Enable', 'on');
    set(handles.OwnWdowBtn, 'Enable', 'on');
    set(handles.ViewWdowBtn, 'Enable', 'on');
    set(handles.MTM, 'Enable', 'off');
end

% --- Executes during object creation, after setting all properties.
function MethodDrpDwn_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MethodDrpDwn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function [Lims] = GenerateLims(handles)
%First create boolean variables to describe the requirements:
Join = get(handles.JnAdjBands, 'Value');        %Join Adjacent bands?
CustomT = get(handles.ChooseBandsTgl, 'Value'); %User's Custom Bands?
NotchT = get(handles.SetNotchTgl, 'Value');     %Notch Filters eg. 50Hz?

%Next get the frequency bands that are selected...
%Bands is an array of start/stop frequencies
%BandBool is a bollean array of which bands are selected.
[Bands, BandBool] = GetFrequencyBands(handles);
Bands = Bands';
%Next we see how many filters are required (Numfilts)
LBool = bwlabel(BandBool);
Numfilts = max(LBool);


% If the user wants to join frequency bands
if Join ==1 && Numfilts>0
    %The user wants to join the frequency Bands together...
    ii = [];
    NewBands = [];
    for ii= 1:Numfilts
        F = find(LBool == ii);    %Finds all adjacent entries
        Min = min(Bands(F, 1)); %Find the minimum of the minimums 
        Max = max(Bands(F, 2)); %Find the maximum on the maximums
        NewBands(ii, (1: 2)) = [Min Max];
    end %For
    %NewBands are the uppr and lowe limits of each requested  band in a 
    % nx2 array. Where n is the number of required filters, Numfilts. 
    count = ii;
else
    ii = [];
    count =1;
    NewBands = [];
    F = find(Bands(:, 1)== 999);
    if length(F) ==0
        F=999;
    end
    %F is now the places of the unwanted frequency Bands within Bands
    for ii = 1:size(Bands, 1)
        if ii ~= F
            %If its not in F then add it to NewBands
           NewBands(count, (1: 2)) = Bands(ii, 1:2); 
           count = count+1;
        end % If 
    end %for ii
    %NewBands are the uppr and lowe limits of each band in a nx2 array.
    % Where n is the number of required filters.
    count = count-1;
end %if Join =1

%If the User has defined custom Bands
if CustomT == 1
    NumCust = length(handles.CustomFilters)/2; %NumCust=the number defined
    for ii = 1:NumCust   
        %Append each filter's limits to NewBands   
        NewBands(count+1, (1:2)) = handles.CustomFilters(ii:ii+1);
        %increment the count
        count = count+1;
    end %for
end %if

%set Lims to NewBands as these are the limits we wish to create filters for
Lims = NewBands; 

%End Of Function

%Makes a mask of the frequency bands selected in order of increasing freq.
function Mask = Bandmask(handles)

Mask = [get(handles.DeltaBtn, 'Value'), get(handles.ThetaBtn, 'Value'),...
    get(handles.AlphaBtn, 'Value'), get(handles.BetaBtn, 'Value'),...
    get(handles.GamLBtn, 'Value'), get(handles.GamHBtn, 'Value'),...
    get(handles.GamVHBtn, 'Value')];
%End of Function


%This function generates the user's window.
function Wdow = GenerateWdow(handles)
%first get the selected window 
windownum = get(handles.WdowList, 'Value');
WdowLen = handles.WdowLen;
%find out which window they want and make it
if windownum == 1
    Wdow = rectwin(WdowLen);
elseif windownum == 2
    Wdow = bartlett(WdowLen);
elseif windownum == 3
    Wdow = barthannwin(WdowLen);
elseif windownum == 4
    Wdow = blackman(WdowLen);
elseif windownum == 5
    Wdow = blackmanharris(WdowLen);
elseif windownum == 6
    Wdow = bohmanwin(WdowLen);
elseif windownum == 7
    Wdow = chebwin(WdowLen, 100);
elseif windownum == 8
    Wdow = flattopwin(WdowLen);
elseif windownum == 9
    Wdow = gausswin(WdowLen);
elseif windownum == 10
    Wdow = hann(WdowLen);
elseif windownum == 11
    Wdow = hamming(WdowLen);
elseif windownum == 12
    Wdow = kaiser(WdowLen, 2.5);
elseif  windownum == 13
    Wdow = tukeywin(WdowLen, 0.25);
elseif windownum == 14
    Wdow = tukeywin(WdowLen, 0.5);
else 
    Wdow = tukeywin(WdowLen, 0.75);
end
%End of function


% --- Executes on button press in PlotFreq. -DOESN'T DO ANYTHING
function PlotFreq_Callback(hObject, eventdata, handles)

% Hint: get(hObject,'Value') returns toggle state of PlotFreq
if get(hObject, 'Value')
    set(handles.Plot2Sided, 'Value', 0);
    set(handles.Plot1Sided, 'Value', 0);
else
    set(handles.PlotFreq, 'Value', 1);
end

% --- Executes on button press in Plot2Sided.
function Plot2Sided_Callback(hObject, eventdata, handles)
% hObject    handle to Plot2Sided (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of Plot2Sided
if get(hObject, 'Value')
    set(handles.Plot1Sided, 'Value', 0);
        set(handles.PlotFreq, 'Value', 0);
else
    set(handles.Plot2Sided, 'Value', 1);
end

% --- Executes on button press in Plot1Sided.
function Plot1Sided_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of Plot1Sided
if get(hObject, 'Value')
    set(handles.Plot2Sided, 'Value', 0);
    set(handles.PlotFreq, 'Value', 0);
else
    set(handles.Plot1Sided, 'Value', 1);
end


%This Function Simply sets the Button values back to their default values.
%It is useful to know when a Window has been refreshed whilst designing 
function refresh_window(handles)
    set(handles.DfaultWdowBtn,'Value', 1);
    set(handles.DfaultWdowBtn,'Enable', 'on');
    set(handles.CustomBndTgl,'Value', 0);
    set(handles.SetNotchTgl,'Value', 0);
    set(handles.PlotFreq, 'Value', 1);
    set(handles.Plot2Sided, 'Value', 0);
    set(handles.Plot1Sided, 'Value', 0);
    %Now the Window Panel
    set(handles.OwnWdowBtn,'Value', 0);
    set(handles.OwnWdowBtn,'Enable', 'on');
    set(handles.WdowList,'Enable', 'on');
    set(handles.WdowList, 'Value', 1);
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowOlap, 'Enable', 'off');    
    set(handles.WdowOlapBtn, 'Enable', 'off');    
    set(handles.ViewWdowBtn, 'Enable', 'on');
    set(handles.nFT, 'Enable', 'off');
    set(handles.MTM, 'Enable', 'off');
%End of function


% --- Executes on button press in nfftBtn.
%The user clicks this before being allowed to set the number of points in
%the FFT
function nfftBtn_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of nfftBtn
if get(hObject, 'Value')
    set(handles.nFT, 'Enable', 'on');
else
    set(handles.nFT, 'Enable', 'off');
end %if



% get the variable selected in the listbox
function var1 = get_var_names(handlesbit)
list_entries = get(handlesbit,'String');
index_selected = get(handlesbit,'Value');
if length(index_selected) ~= 1
    errordlg('You must select only one variable',...
            'Incorrect Selection','modal')
else
    var1 = list_entries{index_selected(1)};
end 

%End Of Funciton

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
%This Function Generates the PSD using requested technique                %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function [Pxx, f, Hpsd] = GeneratePSD(handles)

win = handles.Wdow; %The User's Window (if they have one)

% Next get the number of samples in the user's selection
N = length(handles.userdata); 


%Get the chosen method from the dropdown menu
Method = get(handles.MethodDrpDwn, 'Value');
handles.method = get(handles.MethodDrpDwn, 'Value');

%Set the number of points to use in the FFT to the user's choice (If they
%have chosen to specify it.
if get(handles.nfftBtn, 'Value') 
    %If the user has specified the order of the FFT store it
   nfftV = (get(handles.nFT, 'Value'));
   if nfftV==1
       nfft=512;
   elseif nfftV==2
       nfft=1024;
   elseif nfftV==3
       nfft=2048;
   elseif nfftV==4
       nfft=4084;
   elseif nfftV==5
       nfft=8168;
   else nfftV==6
       nfft=16344;
   end
else
    %If a periodogram is defined with NFFT = [] then nextpow2 is used
    nfft = [];
end

%the user wants a meaningful frequency axis which is
if get(handles.PlotFreq, 'Value')
    % obtained by specifying the smapling frequency. 
    Fs = handles.tstep;
else
    Fs = [];
end

%Now specify Whether the user wants a one or two-sided spectrum
if get(handles.Plot1Sided, 'Value')
    range =  'Onesided';
else
    range = 'Twosided';
end

%Now make the user's window if they havent already selected one...
%this if statement determines how long the window should be
if get(handles.MethodDrpDwn, 'Value')==1  
    %If its a periodogram then it must be the length as the data
    handles.WdowLen = N;
elseif get(handles.MethodDrpDwn, 'Value')==2 && get(handles.WdowLengthBtn, 'Value')==0
    %If its a periodogram then it must be the length as the data
    handles.WdowLen = floor(2*N/9);   
elseif get(handles.WdowLengthBtn, 'Value')==0
    %if they havent specified then its the default for the PSD method, set
    %it to N for now.
    handles.WdowLen = N;
else
    %else set it to what they define
    handles.WdowLen = str2num(get(handles.WdowLength, 'String'))*1000;
end %if

%If the user is using a default window...
if ~length(win)
    %Make the window they require if possible
    win = GenerateWdow(handles);
end

%If they've specified the overlap, set it too
if get(handles.WdowOlapBtn, 'Value')
    noverlap = round(str2num(get(handles.WdowOlap, 'Value'))/100*length(win));
else
    noverlap = [];
end



%Get the chosen method from the dropdown menu
Method = get(handles.MethodDrpDwn, 'Value');

%Now make the PSDs
if Method == 1
    %The user wants a Periodogram so do it:
    if ~get(handles.PlotFreq, 'Value')
        [Pxx, f] = periodogram(handles.userdata,win,  nfft, range);
        Hpsd = dspdata.psd(Pxx,f, 'SpectrumType',range);
    else
        [Pxx, f] = periodogram(handles.userdata,win,  nfft, Fs);
        Hpsd = dspdata.psd(Pxx,f, 'Fs', Fs);
    end
elseif Method == 2
    %The user want to use Welch's Method
    if ~get(handles.PlotFreq, 'Value')
        [Pxx, f] = pwelch(handles.userdata,win, noverlap, nfft, range);
        Hpsd = dspdata.psd(Pxx,f, 'SpectrumType',range);
    else
        [Pxx, f] = pwelch(handles.userdata,win,noverlap,  nfft, Fs);
        Hpsd = dspdata.psd(Pxx,f, 'Fs', Fs);
    end
elseif Method == 3
    nw = (str2num(get(handles.MTM, 'String'))+1)/2;
    
    [Pxxx, Pxxc, f] = pmtm(handles.userdata,nw, nfft, Fs);
    Pxx = {Pxxx, Pxxc};%store the error estimate data
    Hpsd = dspdata.psd(Pxxx,f, 'Fs', Fs);
else
    %The user has made a bad selection.. tell them and exit funciton
    errordlg('You must select a method for the PSD',...
            'Incorrect Selection','modal')
    Pxx = [];
    f = [];
    return
end

%End of Function


% --- Executes on button press in HelpBtn.
function HelpBtn_Callback(hObject, eventdata, handles)
% hObject    handle to HelpBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function WdowOlap_Callback(hObject, eventdata, handles)
% hObject    handle to WdowOlap (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of WdowOlap as text
%        str2double(get(hObject,'String')) returns contents of WdowOlap as a double


% --- Executes during object creation, after setting all properties.
function WdowOlap_CreateFcn(hObject, eventdata, handles)
% hObject    handle to WdowOlap (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in WdowLengthBtn.
function WdowLengthBtn_Callback(hObject, eventdata, handles)
% hObject    handle to WdowLengthBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of WdowLengthBtn
if get(hObject, 'Value')
    set(handles.WdowLength, 'Enable', 'on');
    set(handles.WdowOlapBtn, 'Enable', 'on');
else
    set(handles.WdowLength, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Enable', 'off');
    set(handles.WdowOlap, 'Enable', 'off');
    set(handles.WdowOlapBtn, 'Value', 0);
end
% --- Executes on button press in WdowOlapBtn.
function WdowOlapBtn_Callback(hObject, eventdata, handles)
% hObject    handle to WdowOlapBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of WdowOlapBtn
if get(hObject, 'Value')
    set(handles.WdowOlap, 'Enable', 'on');
else
    set(handles.WdowOlap, 'Enable', 'off');
end


    function Notchfilt = GenerateNotchFilters(handles);
        for ii = 1:2:length(handles.NotchVals)
            W = [handles.NotchVals];
            Notchfilt{ii} = fir1(500, W, 'Stop');
            Notchfilt{ii+1} = 1;
        end



function nPtsFFT_Callback(hObject, eventdata, handles)
% hObject    handle to nPtsFFT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of nPtsFFT as text
%        str2double(get(hObject,'String')) returns contents of nPtsFFT as a double


% --- Executes during object creation, after setting all properties.
function nPtsFFT_CreateFcn(hObject, eventdata, handles)
% hObject    handle to nPtsFFT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end





function nFT_Callback(hObject, eventdata, handles)
% hObject    handle to nFT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of nFT as text
%        str2double(get(hObject,'String')) returns contents of nFT as a double


% --- Executes during object creation, after setting all properties.
function nFT_CreateFcn(hObject, eventdata, handles)
% hObject    handle to nFT (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end





function MTM_Callback(hObject, eventdata, handles)
% hObject    handle to MTM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of MTM as text
%        str2double(get(hObject,'String')) returns contents of MTM as a double


% --- Executes during object creation, after setting all properties.
function MTM_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MTM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end




% --------------------------------------------------------------------
function HELP_help_Callback(hObject, eventdata, handles)
% hObject    handle to HELP_help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Power_Spectra_Help;

% --------------------------------------------------------------------
function Help_Callback(hObject, eventdata, handles)
% hObject    handle to Help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function HELP_Callback(hObject, eventdata, handles)
% hObject    handle to HELP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --------------------------------------------------------------------
function HELP_Quickstart_Callback(hObject, eventdata, handles)
% hObject    handle to HELP_Quickstart (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

Power_Spectra_Quickstart
