function varargout = NotchSet(varargin)
% NOTCHSET M-file for NotchSet.fig
%      The Function is called from FBA_int, and is passed the handles 
%      Structure. It then saves the vector of notch values in
%      handles.notches.
%
%      NOTCHSET, by itself, creates a new NOTCHSET or raises the existing
%      singleton*.
%
%      H = NOTCHSET returns the handle to a new NOTCHSET or the handle to
%      the existing singleton*.
%
%      NOTCHSET('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in NOTCHSET.M with the given input arguments.
%
%      NOTCHSET('Property','Value',...) creates a new NOTCHSET or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before NotchSet_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to NotchSet_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help NotchSet

% Last Modified by GUIDE v2.5 02-May-2006 13:43:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @NotchSet_OpeningFcn, ...
                   'gui_OutputFcn',  @NotchSet_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 NotchSet is made visible.
function NotchSet_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 NotchSet (see VARARGIN)

% Choose default command line output for NotchSet
handles.output = hObject;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Initialisation Code
%Get the old notch values
handles.OldNotchVals = varargin{1}.NotchVals;
%Get the value of the get notch filter toggle button
handles.OldSetNotchTgl = varargin{1}.SetNotchTgl;
%Set the Notch values to the old notch values the user had already entered
% (Kind of like a sticky form.)
%Get the sampling frequency
handles.tstep = varargin{1}.tstep;
if(length(handles.OldNotchVals)~=0)
    set(handles.UserNotchFilters, 'String', num2str(handles.OldNotchVals));
end
%prepare the output function for detecting an ok click
handles.okclicked = false;

%Define Variables that will be used in Output_Fcn
handles.SetNotchTglOut = [];    
handles.NotchValsOut = [];
% Update handles structure
guidata(hObject, handles);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% make the figure visible here
set(gcf,'Visible','on');
% wait here until the Visible property is set to 'off'
waitfor(gcf,'Visible');



% --- Outputs from this function are returned to the command line.
function varargout = NotchSet_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 output from handles structure of ok was clicked
if handles.okclicked
    handles.output1 = handles.NotchValsOut;  %Prepare to change the notch vals
    handles.output2 = (handles.SetNotchTglOut); %Prepare to toggle the button
else 
    handles.output1 = handles.NotchValsOut; %Dont change the Notch values
    handles.output2 = (handles.SetNotchTglOut);% UnToggle the Button in FBA_int
end


     %return the selected variables to FBA_int
     varargout{1} = handles.output1;
     varargout{2} = handles.output2;

% now delete the figure, which is not visible(?)
delete(hObject)

function UserNotchFilters_Callback(hObject, eventdata, handles)
% hObject    handle to UserNotchFilters (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 UserNotchFilters as text
%        str2double(get(hObject,'String')) returns contents of UserNotchFilters as a double


% --- Executes during object creation, after setting all properties.
function UserNotchFilters_CreateFcn(hObject, eventdata, handles)
% hObject    handle to UserNotchFilters (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 SetNotches.
% --- Here the user has indicated that they are finished and are ready to
% pass the nothes back to the main window. so do it
function SetNotches_Callback(hObject, eventdata, handles)
% hObject    handle to SetNotches (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%

%Trim the whitespace off the ends, and call it S...
S = strtrim(get(handles.UserNotchFilters, 'String'));
% We first check that the user has entered a value into the box and warn
% them if they havent
if(length(S)>0)
    %If the string length is greater than zero without any white space...
    
    count = 0; %Start a count of how many items there are
    while length(S)>1
        count = count+1; %Increment the count
        [N, S] = strtok(S, ' '); %Store the string in N and the remainder in S 
        handles.NotchValsOut(count) = str2num(N); %Store the Notch value
    end %End of while

    if(mod(count, 2)>0) % If there's an odd number of values
        handles.SetNotchTglOut= 0;   %Prepare to Untoggle the button
                                                %in FBA_int
        %Warn the user they've entered an odd number of limits
        errordlg('You must enter an even number of notch limits (Min + Max For each Notch)',...
            'Incorrect Number of Inputs','modal')
        handles.okclicked = false; %- We're not going to do anything
        guidata(hObject, handles);
    else %It is a multiple of 2 then set the notch filter values
        check = check_validity(handles);
        if check == 1
            handles.SetNotchTglOut= 1;   %Make a Note to toggle the button
                                         %in FBA_int
            handles.okclicked = true; %tell handles ok was clicked for output fcn
            %Update Handles
            guidata(hObject, handles);
            %change the visibility to call the Output_Fcn
            set(gcf,'Visible', 'off');
        else
            %Tell the user theyve made a mistake
            warndlg(strcat('You have made an error. Please check that your notch',...
                    'filter values are of the type: low1 high1 low2 high2',...
                    'and that the maximum frequency is less than the sampling frequency'),...
                    'Warning Incorrct Inputs','modal')
        end
    end %end if mod(count, 2)>0
    
else %The User has not entered any inputs
       warndlg('You have not entered any notch filters',...
            'Warning No inputs','modal')
        handles.SetNotchTglOut= 0;   %Prepare to Untoggle the button
                                                %in FBA_int
        handles.NotchValsOut = []; %Prepare to set the Notch Values as empty
        handles.okclicked = true; %- We're going to close the window
        guidata(hObject, handles);
        set(handles.figure1,'Visible', 'off');
end %End if length(S)>0
%
% We then check that the User has entered an even number of Notch values
% (a start and a stop one for each notch)
%


function  Output = check_validity(handles)
    G =[];%Define G;
    Output = 1; %Set the Boolean to True (Pass)
    for G = 1:2:length(handles.NotchValsOut)
        %If low limmit > high limit then its wrong!
        if (handles.NotchValsOut(G)>handles.NotchValsOut(G+1))
            Output = 0; %Set the Boolean to false (Fail)
        end %if
    end %for
    
    if(max(handles.NotchValsOut)>=handles.tstep/2)
        %If the max frequency is too large the stop it!
        Output = 0;
    end %If
    


