%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DeepSqueak 2.7.0                                                        %
% Copyright (c) 2021 Kevin Coffey , Ruby Marx, & Robert Ciszek         %
%                                                                         %
% Licensed under the BSD 3-Clause Licence:                                %
% https://opensource.org/licenses/BSD-3-Clause                            %
%                                                                         %
% Unless required by applicable law or agreed to in writing, software     %
% distributed under the License is distributed on an "AS IS" BASIS,       %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = DeepSqueak(varargin)

set(groot,'defaultFigureVisible','on');
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @DeepSqueak_OpeningFcn, ...
    'gui_OutputFcn',  @DeepSqueak_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

% --- Executes just before DeepSqueak is made visible.
function DeepSqueak_OpeningFcn(hObject, eventdata, handles, varargin)
% Very Important Logo (Mouse from hjw)
disp '                                                                                .---.'
disp '                                                                                /  .  \  '
disp '                                                                                ) _     _               |\_/|   |'
disp '                                                                                ( (^)-~-(^)              |   |   |'
disp '    ._______________________________________________________________________________________________,-.\_( 0 0 )__,-.__________|___|__,|'
disp '   /  .-.                                                                                ''M''   \   /   ''M''                  |'
disp '  |  /   \                                                                                >o<                         |'
disp '  | |\_.  |                                                                                |  '
disp '  |\|  | /|        ,---,                                    .--.--.                                                         ,-.        |  '
disp '  | `---'' |      .''  .'' `\                      ,-.----.   /  /    ''.   ,----.                                          ,--/ /|        |'
disp '  |       |    ,---.''     \                     \    /  \ |  :  /`. /  /   /  \-.         ,--,                        ,--. :/ |        |'
disp '  |       |    |   |  .`\  |                    |   :    |;  |  |--`  |   :    :|       ,''_ /|                        :  : '' /         |'
disp '  |       |    :   : |  ''  |   ,---.     ,---.  |   | .\ :|  :  ;_    |   | .\  .  .--. |  | :    ,---.     ,--.--.   |  ''  /          |'
disp '  |       |    |   '' ''  ;  :  /     \   /     \ .   : |: | \  \    `. .   ; |:  |,''_ /| :  . |   /     \   /       \  ''  |  :          |'
disp '  |       |    ''   | ;  .  | /    /  | /    /  ||   |  \ :  `----.   \''   .  \  ||  '' | |  . .  /    /  | .--.  .-. | |  |   \         | '
disp '  |       |    |   | :  |  ''.    '' / |.    '' / ||   : .  |  __ \  \  | \   `.   ||  | '' |  | | .    '' / |  \__\/: . . ''  : |. \        |'
disp '  |       |    ''   : | /  ; ''   ;   /|''   ;   /|:     |`-'' /  /`--''  /  `--''""| |:  | : ;  ; | ''   ;   /|  ," .--.; | |  | '' \ \       |'
disp '  |       |    |   | ''` ,/  ''   |  / |''   |  / |:   : :   ''--''.     /     |   | |''  :  `--''   \''   |  / | /  /  ,.  | ''  : |--''        |'
disp '  |       |    ;   :  .''    |   :    ||   :    ||   | :     `--''---''      |   | ::  ,      .-./|   :    |;  :   .''   \;  |,''           |'
disp '  |       |    |   ,.''       \   \  /  \   \  / `---''.|                   `---''.| `--`----''     \   \  / |  ,     .-./''--''             |'
disp '  |       |    ''---''          `----''    `----''    `---`                     `---`                `----''   `--`---''                     |'
disp '  |       |                                                                                |'
disp '  \       |____________________________________________________________________________________________________________________________/'
disp '   \     /'
disp '    `---'''
disp '  '
disp '  '
disp '  '

% Set Handles
hFig = hObject;
handles.hFig=hFig;

% % Fullscreen
% warning ('off','all');
% pause(0.00001);
% frame_h = get(handle(gcf),'JavaFrame');
% set(frame_h,'Maximized',1);

% Create a class to hold the data
squeakfolder = fileparts(mfilename('fullpath'));

% Add to MATLAB path and check for toolboxes
if ~isdeployed
    % Add DeepSqueak to the path
    addpath(squeakfolder);
    addpath(genpath(fullfile(squeakfolder, 'Functions')));
    savepath

    %% Display error message if running on matlab before 2017b or toolboxes not found
    if verLessThan('matlab','9.9')
        errordlg(['Warning, DeepSqueak V3 requires MATLAB 20201 or later. It looks like you are use MATLAB ' version('-release')],'upgrade your matlab')
    end

    try
        verLessThan('nnet','1');
    catch
        warning('Deep Learning Toolbox not found')
    end

    try
        verLessThan('curvefit','1');
    catch
        warning('Curve Fitting Toolbox not found')
    end

    try
        verLessThan('vision','1');
    catch
        warning('Computer Vision System Toolbox not found')
    end

    try
        verLessThan('images','1');
    catch
        warning('Image Processing Toolbox not found')
    end

    try
        verLessThan('parallel','1');
    catch
        warning('Parallel Computing Toolbox not found')
    end
end

handles.data = squeakData(squeakfolder);

set ( hFig, 'Color', [.1 .1 .1] );
handles.output = hObject;
cd(handles.data.squeakfolder);

%% Display version
try % Read the current changelog and find the version (## number)
    fid = fopen(fullfile(handles.data.squeakfolder,'CHANGELOG.md'));
    changelog = fscanf(fid,'%c');
    fclose(fid);
    tokens = regexp(changelog, '## ([.\d])+', 'tokens');
    handles.DSVersion =  tokens{1}{:};
catch
    handles.DSVersion = '? -- can''t read CHANGELOG.md. Make sure you have the latest version!';
end
fprintf(1,'%s %s\n\n', 'DeepSqueak version', handles.DSVersion);
try % Check if a new version is avaliable by comparing changelog to whats online
    WebChangelog = webread('https://raw.githubusercontent.com/DrCoffey/DeepSqueak/master/CHANGELOG.md');
    [changes, tokens] = regexp(WebChangelog, '## ([.\d])+', 'start', 'tokens');
    WebVersion = tokens{1}{:};
    if ~strcmp(WebVersion, handles.DSVersion)
        fprintf(1,'%s\n%s\n\n%s\n',...
            'A new version of DeepSqueak is avaliable.',...
            'Download it here!',...
            WebChangelog(1:changes(2)-1))
    end
catch
    fprintf(1,'Can''t check for a updates online right now\n');
end

% set(handles.spectogramWindow,'Visible', 'off');
% set(handles.epochSpect,'Visible', 'off');
% set(handles.topRightButton, 'Visible', 'off');
% set(handles.topLeftButton, 'Visible', 'off');

if ~(exist(fullfile(handles.data.squeakfolder,'Background.png'), 'file')==2)
    disp('Background image not found')
    background = zeros(280);
    fonts = listTrueTypeFonts;
    background = insertText(background,[10 8],'DeepSqueak','Font',char(datasample(fonts,1)),'FontSize',30);
    background = insertText(background,[10 80],'DeepSqueak','Font',char(datasample(fonts,1)),'FontSize',30);
    background = insertText(background,[10 150],'DeepSqueak','Font',char(datasample(fonts,1)),'FontSize',30);
    background = insertText(background,[10 220],'DeepSqueak','Font',char(datasample(fonts,1)),'FontSize',30);
    handles.background = background;
else
    handles.background=imread('Background.png');
end
if ~(exist(fullfile(handles.data.squeakfolder,'DeepSqueak.fig'), 'file')==2)
    errordlg('"DeepSqueak.fig" not found');
end

% Cool Background Image
imshow(handles.background, 'Parent', handles.focusWindow);
set(handles.focusWindow,'Color',[0.1 0.1 0.1],'YColor',[1 1 1],'XColor',[1 1 1]);
set(handles.focusWindow,'XTick',[]);
set(handles.focusWindow,'YTick',[]);
update_folders(hObject, eventdata, handles);
handles = guidata(hObject);  % Get newest version of handles

% Set the sliders to the saved values
% set(handles.TonalitySlider, 'Value', handles.data.settings.EntropyThreshold);

% Set the page and focus window dropdown boxes to the values defined in
% squeakData, and set the current value to the one closest to the save value.
handles.epochWindowSizePopup.String = compose('%gs', handles.data.pageSizes);
[~, handles.epochWindowSizePopup.Value] =  min(abs(handles.data.pageSizes - handles.data.settings.pageSize));
handles.focusWindowSizePopup.String = compose('%gs', handles.data.focusSizes);
[~, handles.focusWindowSizePopup.Value] =  min(abs(handles.data.focusSizes - handles.data.settings.focus_window_size));

guidata(hObject, handles);

set(handles.contourWindow,'Color',[0.1 0.1 0.1],'YColor',[1 1 1],'XColor',[1 1 1],'Box','off','Clim',[0,1]);
set(handles.contourWindow,'XTickLabel',[]);
set(handles.contourWindow,'XTick',[]);
set(handles.contourWindow,'YTick',[]);

set(handles.waveformWindow,'Color',[0.1 0.1 0.1],'YColor',[1 1 1],'XColor',[1 1 1],'Box','off','Clim',[0,1]);
set(handles.waveformWindow,'XTickLabel',[]);
set(handles.waveformWindow,'XTick',[]);
set(handles.waveformWindow,'YTick',[]);

C = spatialPattern([1000,10000],-2);
imagesc(C(1:900,1:10000),'Parent', handles.spectogramWindow);
colormap(handles.spectogramWindow,inferno);
set(handles.spectogramWindow,'Color',[0.1 0.1 0.1],'YColor',[1 1 1],'XColor',[1 1 1]);
set(handles.spectogramWindow,'XTickLabel',[]);
set(handles.spectogramWindow,'XTick',[]);
set(handles.spectogramWindow,'YTick',[]);

% imagesc(C(900:1000,1:10000),'Parent', handles.detectionAxes);
% colormap(handles.detectionAxes,inferno);
set(handles.detectionAxes,'Color',[64/255 10/255 103/255],'YColor',[1 1 1],'XColor',[1 1 1]);
set(handles.detectionAxes,'XTickLabel',[]);
set(handles.detectionAxes,'XTick',[]);
set(handles.detectionAxes,'YTick',[]);
set(handles.spectogramWindow,'Parent',handles.hFig);

% Set the list of colormaps
handles.popupmenuColorMap.String = {
    'inferno'
    'magma'
    'plasma'
    'viridis'
    'cubehelix'
    'gray'
    'jet'
    'turbo'
    'hot'
    'parula'
    'hsv'
    'cool'
    'spring'
    'summer'
    'autumn'
    'winter'
    'bone'
    'copper'
    'pink'};

function varargout = DeepSqueak_OutputFcn(hObject, eventdata, handles)
shg;
varargout{1} = handles.output;

% --- Executes on button press in PlayCall.
function PlayCall_Callback(hObject, eventdata, handles)
% Play the sound within the boxs
audio = handles.data.AudioSamples(...
    handles.data.calls.Box(handles.data.currentcall, 1),...
    handles.data.calls.Box(handles.data.currentcall, 1) + handles.data.calls.Box(handles.data.currentcall, 3));
playbackRate = handles.data.audiodata.SampleRate * handles.data.settings.playback_rate; % set playback rate
audio = resample(audio, 192000, playbackRate);
audio = audio - mean(audio);
% Use a window funtion to smooth the beginning and end to remove clicks
w = hamming(2000);
audio(1:1000) = audio(1:1000) .* w(1:1000);
audio(end-999:end) = audio(end-999:end) .* w(1001:2000);
% Bandpass Filter
% audio = bandpass(audio,[handles.data.calls.Box(handles.data.currentcall, 2), handles.data.calls.Box(handles.data.currentcall, 2) + handles.data.calls.Box(handles.data.currentcall, 4)] * 1000,handles.data.audiodata.SampleRate);
soundsc(audio,192000);

% --- Executes on button press in NextCall.
function NextCall_Callback(hObject, eventdata, handles)
if handles.data.currentcall < height(handles.data.calls) % If not the last call
    handles.data.currentcall=handles.data.currentcall+1;
    handles.data.focusCenter = handles.data.calls.Box(handles.data.currentcall,1) + handles.data.calls.Box(handles.data.currentcall,3)/2;
end
handles.data.current_call_valid = true;
update_fig(hObject, eventdata, handles);

% --- Executes on button press in PreviousCall.
function PreviousCall_Callback(hObject, eventdata, handles)
if handles.data.currentcall > 1 % If not the first call
    handles.data.currentcall=handles.data.currentcall-1;
    handles.data.focusCenter = handles.data.calls.Box(handles.data.currentcall,1) + handles.data.calls.Box(handles.data.currentcall,3)/2;
end
handles.data.current_call_valid = true;
update_fig(hObject, eventdata, handles);

% --- Executes on selection change in Networks Folder Pop up.
function neuralnetworkspopup_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes during Networks Folder Pop up.
function neuralnetworkspopup_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in Audio Folder Pop up.
function AudioFilespopup_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes during Audio Folder Pop up.
function AudioFilespopup_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in Detection Folder Pop up.
function popupmenuDetectionFiles_Callback(hObject, eventdata, handles)
guidata(hObject, handles);

% --- Executes during Detection Folder Pop up.
function popupmenuDetectionFiles_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in AcceptCall.
function AcceptCall_Callback(hObject, eventdata, handles)
handles.data.calls.Accept(handles.data.currentcall) = true;
handles.update_position_axes = 1;
NextCall_Callback(hObject, eventdata, handles)

% --- Executes on button press in RejectCall.
function RejectCall_Callback(hObject, eventdata, handles)
handles.data.calls.Accept(handles.data.currentcall) = false;
handles.update_position_axes = 1;
NextCall_Callback(hObject, eventdata, handles)

% --- Executes during MAIN AXES CREATION
function focusWindow_CreateFcn(hObject, eventdata, handles)

function slide_focus(focus_offset, hObject, eventdata, handles)
% Move the focus window one unit over
new_position = handles.data.focusCenter + focus_offset;
new_position = min(new_position, handles.data.audiodata.Duration - handles.data.settings.focus_window_size ./ 2);
new_position = max(new_position, handles.data.settings.focus_window_size ./ 2);
handles.data.focusCenter = new_position;

if new_position > handles.data.windowposition + handles.data.settings.pageSize
    forwardButton_Callback(hObject, eventdata, handles);
elseif new_position < handles.data.windowposition
    backwardButton_Callback(hObject, eventdata, handles);
else
    calls_within_window = find(...
        handles.data.calls.Box(:,1) > new_position - handles.data.settings.focus_window_size/2 & ...
        handles.data.calls.Box(:,1) < new_position + handles.data.settings.focus_window_size/2 | ...
        sum(handles.data.calls.Box(:,[1,3]),2) > new_position - handles.data.settings.focus_window_size/2 &...
        sum(handles.data.calls.Box(:,[1,3]),2) < new_position + handles.data.settings.focus_window_size/2);
    if ~isempty(calls_within_window)
        handles.data.currentcall = calls_within_window(1);

        handles.data.current_call_valid = true;
    end

    guidata(hObject,handles);
    update_fig(hObject, eventdata, handles);
end

function score_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function score_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function status_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function status_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on key press with focus on figure1 or any of its controls.
function figure1_WindowKeyPressFcn(hObject, eventdata, handles)
%disp(eventdata);
switch eventdata.Character
    case 'p'
        PlayCall_Callback(hObject, eventdata, handles)
    case {'e', 29} % char(29) is right arrow key
        NextCall_Callback(hObject, eventdata, handles)
    case {'q', 28} % char(28) is left arrow key
        PreviousCall_Callback(hObject, eventdata, handles)
    case 'a'
        AcceptCall_Callback(hObject, eventdata, handles)
    case 'r'
        RejectCall_Callback(hObject, eventdata, handles)
    case 'd'
        rectangle_Callback(hObject, eventdata, handles)
    case 127 % Delete key
        handles.data.calls(handles.data.currentcall,:) = [];
        SortCalls(hObject, [], handles, 'time', 0, handles.data.currentcall - 1);
    case 30 % char(30) is up arrow key
        slide_focus(+ handles.data.settings.focus_window_size, hObject, eventdata, handles)
    case 31 % char(31) is down arrow key
        slide_focus(- handles.data.settings.focus_window_size, hObject, eventdata, handles)
    case 32 % 'space'
        forwardButton_Callback(hObject, eventdata, handles);
    case handles.data.labelShortcuts
        %% Update the call labels
        % Index of the shortcut
        idx = contains(handles.data.labelShortcuts, eventdata.Character);
        handles.data.calls.Type(handles.data.currentcall) = categorical(handles.data.settings.labels(idx));
        update_fig(hObject, eventdata, handles);
end
% drawnow

function figure1_KeyPressFcn(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function popupmenuColorMap_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function freq_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in rectangle.
function rectangle_Callback(hObject, eventdata, handles)
current_box = drawrectangle( 'Parent',handles.focusWindow,...
                            'FaceAlpha',0,...
                            'LineWidth',1 );
% Don't do anything if the new box is empty
if current_box.Position(3) == 0 || current_box.Position(4) == 4
    delete(current_box)
    return
end
new_box = table();
new_box.Box = current_box.Position;
new_box.Score = 1;
new_box.Type = categorical({'USV'});
new_box.Accept = true;
handles.data.calls = [handles.data.calls; new_box];

%Now delete the roi and render the figure. The roi will be rendered along
%with the existing boxes.
handles.data.current_call_valid = true;
SortCalls(hObject, eventdata, handles, 'time', 0, -1);
delete(current_box)

% --------------------------------------------------------------------
function select_audio_Callback(hObject, eventdata, handles)
% Find audio in folder
path=uigetdir(handles.data.settings.audiofolder,'Select Audio File Folder');
if isnumeric(path);return;end
handles.data.settings.audiofolder = path;
handles.data.saveSettings();
update_folders(hObject, eventdata, handles);

% --------------------------------------------------------------------
function load_networks_Callback(hObject, eventdata, handles)
% Find networks
path=uigetdir(handles.data.settings.networkfolder,'Select Network Folder');
if isnumeric(path);return;end
handles.data.settings.networkfolder = path;
handles.data.saveSettings();
update_folders(hObject, eventdata, handles);

function load_detectionFolder_Callback(hObject, eventdata, handles)
% Find audio in folder
path=uigetdir(handles.data.settings.detectionfolder,'Select Detection File Folder');
if isnumeric(path);return;end
handles.data.settings.detectionfolder = path;
handles.data.saveSettings();
update_folders(hObject, eventdata, handles);

% --------------------------------------------------------------------
function folders_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function export_raven_Callback(hObject, eventdata, handles)
% Export current file as a txt file for viewing in Raven
% http://www.birds.cornell.edu/brp/raven/RavenOverview.html
raventable = [{'Selection'} {'View'} {'Channel'} {'Begin Time (s)'} {'End Time (s)'} {'Low Freq (Hz)'} {'High Freq (Hz)'} {'Delta Time (s)'} {'Delta Freq (Hz)'} {'Avg Power Density (dB FS)'} {'Annotation'} {'Begin Path'} {'File Offset'}];
View = 'Spectrogram 1';
Channel = 1;
for i = 1:height(handles.data.calls)
    if handles.data.calls.Accept(i)
        Selection = i;
        BeginTime = handles.data.calls.Box(i, 1);
        EndTime = sum(handles.data.calls.Box(i ,[1, 3]));
        LowFreq = handles.data.calls.Box(i, 2) * 1000;
        HighFreq = sum(handles.data.calls.Box(i, [2, 4])) * 1000;
        DeltaTime = EndTime - BeginTime;
        DeltaFreq = HighFreq - LowFreq;
        AvgPwr = 1;
        Annotation = handles.data.calls.Accept(i);
        BeginPath = handles.data.audiodata.Filename;
        FileOffset = handles.data.calls.Box(i, 1);
        raventable = [raventable; {Selection} {View} {Channel} {BeginTime} {EndTime} {LowFreq} {HighFreq} {DeltaTime} {DeltaFreq} {AvgPwr} {Annotation} {BeginPath} {FileOffset}];
    end
end
a  = cell2table(raventable);
handles.current_file_id = get(handles.popupmenuDetectionFiles,'Value');
current_detection_file = handles.detectionfiles(handles.current_file_id).name;
ravenname=[strtok(current_detection_file,'.') '_Raven.txt'];
[FileName,PathName] = uiputfile(ravenname,'Save Raven Truth Table (.txt)');
writetable(a,[PathName FileName],'delimiter','\t','WriteVariableNames',false);
guidata(hObject, handles);

% --------------------------------------------------------------------
function export_Callback(hObject, eventdata, handles)

function training_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function customlabels_Callback(hObject, eventdata, handles)
% Define call categories
prompt = {
    'Label 1  --- Key 1'
    'Label 2  --- Key 2'
    'Label 3  --- Key 3'
    'Label 4  --- Key 4'
    'Label 5  --- Key 5'
    'Label 6  --- Key 6'
    'Label 7  --- Key 7'
    'Label 8  --- Key 8'
    'Label 9  --- Key 9'
    'Label 10  --- Key 0'
    'Label 11  --- Key -'
    'Label 12  --- Key ='
    'Label 13  --- Key !'
    'Label 14  --- Key @'
    'Label 15  --- Key #'
    'Label 16  --- Key $'
    'Label 17  --- Key %'
    'Label 18  --- Key ^'
    'Label 19  --- Key &'
    'Label 20  --- Key *'
    'Label 21  --- Key ('
    'Label 22  --- Key )'
    'Label 23  --- Key _'
    'Label 24  --- Key +'
    };

dlg_title = 'Set Custom Label Names';
num_lines=[1,60]; options.Resize='off'; options.WindowStyle='modal'; options.Interpreter='none';
old_labels = handles.data.settings.labels;
new_labels = inputdlgcol(prompt,dlg_title,num_lines,old_labels,options,3);
if ~isempty(new_labels)
    handles.data.settings.labels = new_labels;
    handles.data.saveSettings();
    update_folders(hObject, eventdata, handles);
end
guidata(hObject, handles);

% --------------------------------------------------------------------
function Change_Playback_Rate_Callback(hObject, eventdata, handles)
prompt = {'Playback Rate: (default = 0.0.5)'};
dlg_title = 'Change Playback Rate';
num_lines=1; options.Resize='off'; options.WindowStyle='modal'; options.Interpreter='tex';
defaultans = {num2str(handles.data.settings.playback_rate)};
rate = inputdlg(prompt,dlg_title,num_lines,defaultans);
if isempty(rate); return; end

[newrate,~,errmsg] = sscanf(rate{1},'%f',1);
disp(errmsg);
if ~isempty(newrate)
    handles.data.settings.playback_rate = newrate;
    handles.data.saveSettings();
    update_folders(hObject, eventdata, handles);
end
guidata(hObject, handles);

% --------------------------------------------------------------------
function Help_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function Untitled_3_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function CallClassification_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function ChangeContourThreshold_Callback(hObject, eventdata, handles)
% Change the contour threshold
prompt = {'Entropy Threshold: (range = 0-1, default = 0.215)', 'Amplitude Percentile Threshold: (range = 0-1, default = 0.825)'};
dlg_title = 'New Contour Threshold:';
num_lines=[1 50]; options.Resize='off'; options.WindowStyle='modal'; options.Interpreter='tex';
defaultans = {num2str(handles.data.settings.EntropyThreshold),num2str(handles.data.settings.AmplitudeThreshold)};
threshold = inputdlg(prompt,dlg_title,num_lines,defaultans);
if isempty(threshold); return; end

[EntropyThreshold,~,errmsg] = sscanf(threshold{1},'%f',1);
disp(errmsg);
[AmplitudeThreshold,~,errmsg] = sscanf(threshold{2},'%f',1);
disp(errmsg);

if ~isempty(EntropyThreshold) && ~isempty(AmplitudeThreshold)

    if AmplitudeThreshold < .001 || AmplitudeThreshold > .999
        disp('Warning! Amplitude Percentile Threshold Must be (0 > 1), Reverting to Default (.825)');
        AmplitudeThreshold = handles.data.defaultSettings.AmplitudeThreshold;
    end
    if EntropyThreshold < .001 || EntropyThreshold > .999
        disp('Warning! Entropy Threshold Must be (0 > 1), Reverting to Default (.215)');
        EntropyThreshold = handles.data.defaultSettings.EntropyThreshold;
    end

    handles.data.settings.EntropyThreshold = EntropyThreshold;
    handles.data.settings.AmplitudeThreshold = AmplitudeThreshold;
    handles.data.saveSettings();
    update_folders(hObject, eventdata, handles);
    try
        update_fig(hObject, eventdata, handles);
    catch
        disp('Could not update figure. Is a call loaded?')
    end
end
guidata(hObject, handles);

% --------------------------------------------------------------------
function ViewManual_Callback(hObject, eventdata, handles)
web('https://github.com/DrCoffey/DeepSqueak/wiki','-browser');

% --------------------------------------------------------------------
function AboutDeepSqueak_Callback(hObject, eventdata, handles)
title = 'About DeepSqueak';

d = dialog('Position',[300 350 500  600],'Name',title,'WindowStyle','Normal','Visible', 'off','Color', [0,0,0]);
movegui(d,'center');
ha = axes(d,'Units','Normalized','Position',[0,0,1,1]);

A = zeros(128);
A = insertText(A,[64,20],'Coffey & Marx, 2019','TextColor','white','BoxColor','Black','AnchorPoint','Center','FontSize',11);
A = insertText(A,[64,64],'DeepSqueak','TextColor','white','BoxColor','Black','AnchorPoint','Center');
A = insertText(A,[64,80],['Version ' handles.DSVersion],'TextColor','white','BoxColor','Black','AnchorPoint','Center','FontSize',11);

A = A(:,:,1);

P = [64, 64];
D = 3;
T = [1,0,-1,0;0,1,0,-1];	% 4 directions
k = 0;

handle_image = imshow(A,[0,1],'parent',ha);

btn = uicontrol('Parent',d,...
    'Units','Normalized',...
    'Position',[.42 .01 .16 .06],...
    'String','Okay',...
    'Callback','delete(gcf)');
set(d,'Visible','on')

while isvalid(handle_image)
    k = k+1;
    a = A(P(1),P(2));
    A(P(1),P(2)) = ~a;
    if ( a )
        D = mod(D+1,4);
    else
        D = mod(D-1,4);
    end
    P = P+T(:,D+1);
    handle_image.CData = A;
    pause(.01)
end

% --- Executes on slider movement.
function TonalitySlider_Callback(hObject, eventdata, handles)
handles.data.settings.EntropyThreshold=(get(hObject,'Value'));
handles.data.saveSettings();
update_fig(hObject, eventdata, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --------------------------------------------------------------------
function submit_a_bug_Callback(hObject, eventdata, handles)
% hObject    handle to submit_a_bug (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web('https://github.com/UEFepilepsyAIVI/DeepSqueak/issues','-browser');

% --- Executes on slider movement.
function optimization_slider_Callback(hObject, eventdata, handles)
hObject.Value = round(hObject.Value);

% --- Executes on button press in backwardButton.
function backwardButton_Callback(hObject, eventdata, handles)
% handles.data.windowposition = max(0, handles.data.windowposition - handles.data.settings.pageSize);
handles.data.focusCenter = max(0, handles.data.windowposition - handles.data.settings.focus_window_size ./ 2);
% get_closest_call_to_focus(hObject, eventdata, handles);

jumps = floor(handles.data.focusCenter / handles.data.settings.pageSize);
handles.data.windowposition = jumps*handles.data.settings.pageSize;

calls_within_window = find(handles.data.calls.Box(:,1) < handles.data.windowposition + handles.data.settings.pageSize, 1, 'last');
if ~isempty(calls_within_window)
    handles.data.currentcall = calls_within_window;
    handles.data.current_call_valid = true;
end

update_fig(hObject, eventdata, handles);

% --- Executes on button press in forwardButton.
function forwardButton_Callback(hObject, eventdata, handles)
% handles.data.windowposition = min(handles.data.audiodata.Duration - handles.data.settings.pageSize, handles.data.windowposition + handles.data.settings.pageSize);
handles.data.focusCenter = handles.data.windowposition + handles.data.settings.pageSize + handles.data.settings.focus_window_size ./ 2;
handles.data.focusCenter = min(handles.data.focusCenter, handles.data.audiodata.Duration - handles.data.settings.focus_window_size ./ 2);

jumps = floor(handles.data.focusCenter / handles.data.settings.pageSize);
handles.data.windowposition = jumps*handles.data.settings.pageSize;

% handles.data.focusCenter = max(0, handles.data.windowposition - handles.data.settings.focus_window_size ./ 2);
% get_closest_call_to_focus(hObject, eventdata, handles);

calls_within_window = find(handles.data.calls.Box(:,1) > handles.data.windowposition, 1);
if ~isempty(calls_within_window)
    handles.data.currentcall = calls_within_window;
    handles.data.current_call_valid = true;
end

update_fig(hObject, eventdata, handles);
% guidata(hObject, handles);

function get_closest_call_to_focus(hObject, eventdata, handles)
calls_within_window = find(...
    handles.data.calls.Box(:,1) > handles.data.windowposition &...
    sum(handles.data.calls.Box(:,[1,3]),2) < handles.data.windowposition + handles.data.settings.pageSize);
if ~isempty(calls_within_window)
    callMidpoints = handles.data.calls.Box(calls_within_window,1) + handles.data.calls.Box(calls_within_window,3)/2;
    [~, closestCall] = min(abs(callMidpoints - handles.data.focusCenter));
    handles.data.currentcall = calls_within_window(closestCall);
    handles.data.current_call_valid = true;
end
update_fig(hObject, eventdata, handles);

% --- Executes during object creation, after setting all properties.
function epochWindowSizePopup_CreateFcn(hObject, eventdata, handles)
% hObject    handle to epochWindowSizePopup (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called
padding = cellstr(get(hObject,'String'));
seconds = regexp(padding{get(hObject,'Value')},'([\d*.])*','match');
seconds = str2num(seconds{1});
handles.data.settings.pageSize = seconds;
guidata(hObject, handles);

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

% Hints: contents = cellstr(get(hObject,'String')) returns spectogramScalePopup contents as cell array
%        contents{get(hObject,'Value')} returns selected item from spectogramScalePopup
update_fig(hObject, [], handles);

% --- Executes during object creation, after setting all properties.
function spectogramScalePopup_CreateFcn(hObject, eventdata, handles)
% hObject    handle to spectogramScalePopup (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 SpectogramMax_Callback(hObject, eventdata, handles)
% hObject    handle to SpectogramMax (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    set(hObject, 'String', num2str(get_spectogram_max(hObject, handles)));
    guidata(hObject,handles);
    update_fig(hObject, [], handles);

% --- Executes during object creation, after setting all properties.
function SpectogramMax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SpectogramMax (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 during object creation, after setting all properties.
function focusWindowSizePopup_CreateFcn(hObject, eventdata, handles)
% hObject    handle to focusWindowSizePopup (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

padding = cellstr(get(hObject,'String'));
seconds = regexp(padding{get(hObject,'Value')},'([\d*.])*','match');
seconds = str2double(seconds{1});
handles.data.settings.focus_window_size = seconds;
guidata(hObject, handles);

% --- Executes on button press in topLeftButton.
function topLeftButton_Callback(hObject, eventdata, handles)
% hObject    handle to topLeftButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    slide_focus(handles.data.settings.focus_window_size*(-1), hObject, eventdata, handles)

% --- Executes on button press in topRightButton.
function topRightButton_Callback(hObject, eventdata, handles)
% hObject    handle to topRightButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    slide_focus(handles.data.settings.focus_window_size*(1), hObject, eventdata, handles)

% --- Executes on button press in loadAudioFile.
function loadAudioFile_Callback(hObject, eventdata, handles)
h = waitbar(0,'Loading Audio Please wait...');
update_folders(hObject, eventdata, handles);
handles = guidata(hObject);

if nargin == 3 % if "Load Calls" button pressed
    if isempty(handles.audiofiles)
        close(h);
        errordlg(['No valid audio files in current audio folder. Select a folder containing audio with '...
            '"File -> Select Audio Folder", then choose the desired file in the "Audio Files" dropdown box.'])
        return
    end
    handles.current_file_id = get(handles.AudioFilespopup,'Value');
    handles.current_audio_file = handles.audiofiles(handles.current_file_id).name;
end

handles.data.audiodata = audioinfo(fullfile(handles.data.settings.audiofolder,handles.current_audio_file));

Calls = table(zeros(0,4),[],[],[], 'VariableNames', {'Box', 'Score', 'Type', 'Accept'});
% Calls.Box = [0 0 1 1];
% Calls.Score = 0;
% Calls.Type = categorical({'NA'});
% Calls.Power = 1;
% Calls.Accept = false;
handles.data.calls = Calls;
% Position of the focus window
handles.data.focusCenter = handles.data.settings.focus_window_size ./ 2;
initialize_display(hObject, eventdata, handles);
close(h);

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

% --------------------------------------------------------------------
function contributorToolsMenu_Callback(hObject, eventdata, handles)
web('https://gitter.im/DeepSqueak_Community/General')

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

% --- Executes on button press in invert_cmap.
function invert_cmap_Callback(hObject, eventdata, handles)
colormap(handles.spectogramWindow, flipud(colormap(handles.spectogramWindow)))
colormap(handles.focusWindow, flipud(colormap(handles.focusWindow)))

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

% Hint: place code in OpeningFcn to populate waveformWindow

% --------------------------------------------------------------------
function Keyboard_Shortcuts_Callback(hObject, eventdata, handles)
% Display a list of keyboard shortcuts
Keyboard_Shortcuts = [
    "Save file", "ctrl + s"
    "Next call", "e, right arrow"
    "Previous call", "q, left arrow"
    "Accept call", "a"
    "Reject call", "r"
    "Delete call", "delete, right click"
    "Redraw box", "d"
    "Play call audio", "p"
    "Set call label", "See ""Add Custom Labels"", double click"
    "Slide foucs forward", "up arrow"
    "Slide foucs back", "down arrow"
    "Next page", "space"
    ];
CreateStruct.Interpreter = 'tex';
CreateStruct.WindowStyle = 'modal';
msgbox(['\fontname{Courier}\fontsize{12}' sprintf('%-20s |   %s\n', Keyboard_Shortcuts')], 'Keyboard Shortcuts', CreateStruct)


function varargout = struct2double(varargin)

% This function is a backward compatibility wrapper. It allows existing
% MATLAB scripts that do not use the new FieldTrip ft_xxx function naming
% scheme to work with recent versions of the FieldTrip toolbox.
%
% Please look in ft_xxx for the help of the function that you are looking
% for, where xxx is the name of the function that you were looking for.

% Copyright (C) 2009, Robert Oostenveld

prefix    = 'ft_';
funname   = mfilename;
warning([upper(mfilename) ' is only a compatibility wrapper, which will soon be removed. Please instead call ' upper(prefix) upper(funname) '.']);
funhandle = str2func([prefix funname]);
[varargout{1:nargout}] = funhandle(varargin{:});


classdef AnnotationState < uint8
    enumeration
        kZoomInState(1)
        kZoomOutState (2)
        kPanState (3)
        kSetTimelineState (4)
        kAddEventState (5)
        kAddRangeState (6)
        kModifyAnnotationState (7)
        kDeleteAnnotationState (8)
    end
end


function varargout = lvd_EditActionSetExtremumRecordingStateGUI(varargin)
% LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI MATLAB code for lvd_EditActionSetExtremumRecordingStateGUI.fig
%      LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI, by itself, creates a new LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI or raises the existing
%      singleton*.
%
%      H = LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI returns the handle to a new LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI or the handle to
%      the existing singleton*.
%
%      LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI.M with the given input arguments.
%
%      LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI('Property','Value',...) creates a new LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_EditActionSetExtremumRecordingStateGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_EditActionSetExtremumRecordingStateGUI_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 lvd_EditActionSetExtremumRecordingStateGUI

% Last Modified by GUIDE v2.5 14-Jan-2019 13:53:03

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

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

    centerUIFigure(hObject);

    action = varargin{1};
    setappdata(hObject,'action',action);

    lv = varargin{2};
    setappdata(hObject,'lv',lv);

    populateGUI(handles, action, lv);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action, lv)
    [exListStr, extrema] = lv.getExtremaListBoxStr();
    if(not(isempty(exListStr)))
        set(handles.refExtremumCombo,'String',exListStr);
    else
        set(handles.refExtremumCombo,'String',' ');
    end

    recordingStateStrs = LaunchVehicleExtremaRecordingEnum.getNameStrs();
    set(handles.stateCombo,'String',recordingStateStrs);

    if(not(isempty(action.extremum)))
        ind = find(extrema == action.extremum,1,'first');
    else
        ind = [];
    end

    if(not(isempty(ind)))
        set(handles.refExtremumCombo,'Value',ind);
    end

    if(not(isempty(action.extremum)))
        ind = LaunchVehicleExtremaRecordingEnum.getIndOfListboxStrs(action.extremum.startingState);
    else
        ind = 1;
    end
    set(handles.stateCombo,'Value',ind);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditActionSetExtremumRecordingStateGUI_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
    if(isempty(handles))
        varargout{1} = false;
    else
        action = getappdata(hObject,'action');
        lv = getappdata(hObject,'lv');

        [~, extrema] = lv.getExtremaListBoxStr();
        if(not(isempty(extrema)))
            ind = get(handles.refExtremumCombo,'Value');
            action.extremum = extrema(ind);
        end

        [~,m] = LaunchVehicleExtremaRecordingEnum.getNameStrs();
        action.runningStateToSet = m(get(handles.stateCombo,'Value'));

        varargout{1} = true;
        close(handles.lvd_EditActionSetExtremumRecordingStateGUI);
    end

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

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

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

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

% --- Executes during object creation, after setting all properties.
function refExtremumCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to refExtremumCombo (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

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

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

% --- Executes during object creation, after setting all properties.
function stateCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stateCombo (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

% --- Executes on key press with focus on lvd_EditActionSetExtremumRecordingStateGUI or any of its controls.
function lvd_EditActionSetExtremumRecordingStateGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditActionSetExtremumRecordingStateGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditActionSetExtremumRecordingStateGUI);
    end


function varargout = exit_modaldlg(varargin)
% EXIT_MODALDLG M-file for exit_modaldlg.fig
%      EXIT_MODALDLG by itself, creates a new EXIT_MODALDLG or raises the
%      existing singleton*.
%
%      H = EXIT_MODALDLG returns the handle to a new EXIT_MODALDLG or the handle to
%      the existing singleton*.
%
%      EXIT_MODALDLG('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in EXIT_MODALDLG.M with the given input arguments.
%
%      EXIT_MODALDLG('Property','Value',...) creates a new EXIT_MODALDLG or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before exit_modaldlg_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to exit_modaldlg_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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 14-Nov-2005 01:25:26

%* Author: Ranjith Unnikrishnan                                          *
%* Carnegie Mellon University, Vision and Mobile Robotics Laboratory     *
%* THE MATERIAL EMBODIED IN THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"     *
%* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,      *
%* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR      *
%* FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL CARNEGIE MELLON  *
%* UNIVERSITY BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,            *
%* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY         *
%* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,        *
%* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF     *
%* THIRD PARTIES, WHETHER OR NOT CARNEGIE MELLON UNIVERSITY HAS BEEN     *
%* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON        *
%* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE     *
%* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.                      *
%

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

% Choose default command line output for exit_modaldlg
handles.output = 'Yes';

% Update handles structure
guidata(hObject, handles);

% Insert custom Title and Text if specified by the user
% Hint: when choosing keywords, be sure they are not easily confused
% with existing figure properties.  See the output of set(figure) for
% a list of figure properties.
if(nargin > 3)
    for index = 1:2:(nargin-3),
        if nargin-3==index, break, end
        switch lower(varargin{index})
         case 'title'
          set(hObject, 'Name', varargin{index+1});
         case 'string'
          set(handles.text1, 'String', varargin{index+1});
        end
    end
end

% Determine the position of the dialog - centered on the callback figure
% if available, else, centered on the screen
FigPos=get(0,'DefaultFigurePosition');
OldUnits = get(hObject, 'Units');
set(hObject, 'Units', 'pixels');
OldPos = get(hObject,'Position');
FigWidth = OldPos(3);
FigHeight = OldPos(4);
if isempty(gcbf)
    ScreenUnits=get(0,'Units');
    set(0,'Units','pixels');
    ScreenSize=get(0,'ScreenSize');
    set(0,'Units',ScreenUnits);

    FigPos(1)=1/2*(ScreenSize(3)-FigWidth);
    FigPos(2)=2/3*(ScreenSize(4)-FigHeight);
else
    GCBFOldUnits = get(gcbf,'Units');
    set(gcbf,'Units','pixels');
    GCBFPos = get(gcbf,'Position');
    set(gcbf,'Units',GCBFOldUnits);
    FigPos(1:2) = [(GCBFPos(1) + GCBFPos(3) / 2) - FigWidth / 2, ...
                   (GCBFPos(2) + GCBFPos(4) / 2) - FigHeight / 2];
end
FigPos(3:4)=[FigWidth FigHeight];
set(hObject, 'Position', FigPos);
set(hObject, 'Units', OldUnits);

% Show a question icon from dialogicons.mat - variables questIconData
% and questIconMap
load dialogicons.mat

IconData=questIconData;
questIconMap(256,:) = get(handles.figure1, 'Color');
IconCMap=questIconMap;

Img=image(IconData, 'Parent', handles.axes1);
set(handles.figure1, 'Colormap', IconCMap);

set(handles.axes1, ...
    'Visible', 'off', ...
    'YDir'   , 'reverse'       , ...
    'XLim'   , get(Img,'XData'), ...
    'YLim'   , get(Img,'YData')  ...
    );

% Make the GUI modal
set(handles.figure1,'WindowStyle','modal')

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

% --- Outputs from this function are returned to the command line.
function varargout = exit_modaldlg_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;

% The figure can be deleted now
delete(handles.figure1);

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

handles.output = get(hObject,'String');

% Update handles structure
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

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

handles.output = get(hObject,'String');

% Update handles structure
guidata(hObject, handles);

% Use UIRESUME instead of delete because the OutputFcn needs
% to get the updated handles structure.
uiresume(handles.figure1);

% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if isequal(get(handles.figure1, 'waitstatus'), 'waiting')
    % The GUI is still in UIWAIT, us UIRESUME
    uiresume(handles.figure1);
else
    % The GUI is no longer waiting, just close it
    delete(handles.figure1);
end

% --- Executes on key press over figure1 with no controls selected.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Check for "enter" or "escape"
if isequal(get(hObject,'CurrentKey'),'escape')
    % User said no by hitting escape
    handles.output = 'No';

    % Update handles structure
    guidata(hObject, handles);

    uiresume(handles.figure1);
end

if isequal(get(hObject,'CurrentKey'),'return')
    uiresume(handles.figure1);
end

% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over pushbutton1.
function pushbutton1_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


function setM(OCP,M)
    setM@DynamicSystem(OCP,M);
end


function logS = batch_uniformizer(sourceDirName, destinDirName, destinDCMDirName)
%
% function logS = batch_uniformizer(dirName)
%
% This function uniformizes CERR plans in the passed source directory and
% writes them to the destination directory
%
% APA, 08/19/2011

% sourceDirName = '/Users/aptea/Documents/MSKCC/Projects/TRISMUS/TRISMUS CERR';
% destinDCMDirName = '/Users/aptea/Documents/MSKCC/Projects/TRISMUS/TRISMUS CERR DICOM';
% destinDirName = '/Users/aptea/Documents/MSKCC/Projects/TRISMUS/TRISMUS CERR UNIFORM';

fileC = {};
if strcmpi(sourceDirName,'\') || strcmpi(sourceDirName,'/')
    filesTmp = getCERRfiles(sourceDirName(1:end-1));
else
    filesTmp = getCERRfiles(sourceDirName);
end
fileC = [fileC filesTmp];

% Initialize waitbar
hWait = waitbar(0,'Uniformizing cohort of CERR plans. Please wait...');

logS = struct('maxDiff','', 'fileName', '');

numFiles = length(fileC);

%Load CERR plan
for iFile=1:numFiles

    %Update Waitbar
    drawnow

    waitbar(iFile/numFiles,hWait)

    %Load CERR plan
    try
        planC = loadPlanC(fileC{iFile}, tempdir);
        planC = updatePlanFields(planC);
        indexS = planC{end};

        %Check for mesh representation and load meshes into memory
        currDir = cd;
        meshDir = fileparts(which('libMeshContour.dll'));
        cd(meshDir)
        for strNum = 1:length(planC{indexS.structures})
            if isfield(planC{indexS.structures}(strNum),'meshRep') && ~isempty(planC{indexS.structures}(strNum).meshRep) && planC{indexS.structures}(strNum).meshRep
                try
                    calllib('libMeshContour','loadSurface',planC{indexS.structures}(strNum).strUID,planC{indexS.structures}(strNum).meshS)
                catch
                    planC{indexS.structures}(strNum).meshRep    = 0;
                    planC{indexS.structures}(strNum).meshS      = [];
                end
            end
        end
        cd(currDir)

        stateS.optS = opts4Exe([getCERRPath,'CERROptions.json']);

        %Check color assignment for displaying structures
        [assocScanV,relStrNumV] = getStructureAssociatedScan(1:length(planC{indexS.structures}),planC);
        for scanNum = 1:length(planC{indexS.scan})
            scanIndV = find(assocScanV==scanNum);
            for i = 1:length(scanIndV)
                strNum = scanIndV(i);
                colorNum = relStrNumV(strNum);
                if isempty(planC{indexS.structures}(strNum).structureColor)
                    color = stateS.optS.colorOrder( mod(colorNum-1, size(stateS.optS.colorOrder,1))+1,:);
                    planC{indexS.structures}(strNum).structureColor = color;
                end
            end
        end

        %Check dose-grid
        for doseNum = 1:length(planC{indexS.dose})
            if planC{indexS.dose}(doseNum).zValues(2) - planC{indexS.dose}(doseNum).zValues(1) < 0
                planC{indexS.dose}(doseNum).zValues = flipud(planC{indexS.dose}(doseNum).zValues);
                planC{indexS.dose}(doseNum).doseArray = flipdim(planC{indexS.dose}(doseNum).doseArray,3);
            end
        end

        %Check whether uniformized data is in cellArray format.
        if ~isempty(planC{indexS.structureArray}) && iscell(planC{indexS.structureArray}(1).indicesArray)
            planC = setUniformizedData(planC,planC{indexS.CERROptions});
            indexS = planC{end};
        end

        if length(planC{indexS.structureArrayMore}) ~= length(planC{indexS.structureArray})
            for saNum = 1:length(planC{indexS.structureArray})
                if saNum == 1
                    planC{indexS.structureArrayMore} = struct('indicesArray', {[]},...
                        'bitsArray', {[]},...
                        'assocScanUID',{planC{indexS.structureArray}(saNum).assocScanUID},...
                        'structureSetUID', {planC{indexS.structureArray}(saNum).structureSetUID});

                else
                    planC{indexS.structureArrayMore}(saNum) = struct('indicesArray', {[]},...
                        'bitsArray', {[]},...
                        'assocScanUID',{planC{indexS.structureArray}(saNum).assocScanUID},...
                        'structureSetUID', {planC{indexS.structureArray}(saNum).structureSetUID});
                end
            end
        end

        %Create uniform slices
        % planC = createUniformlySlicedPlanC(planC);

        % Check scan grid and correct for numerical noise
        zValuesV = [planC{indexS.scan}.scanInfo(:).zValue];
        zDiffV = diff(zValuesV);
        meanDiff = mean(zDiffV);
        maxDifference = max(abs((zDiffV - meanDiff)));

        % Write to log
        [jnk, fileName] = fileparts(fileC{iFile});
        logS(iFile).maxDiff = maxDifference;
        logS(iFile).fileName = fileName;

        if maxDifference < 0.05
            newZvalsV = linspace(zValuesV(1), zValuesV(end), length(zValuesV));
        else
            continue;
        end

        for sliceNum = 1:length(planC{indexS.scan}.scanInfo)

            planC{indexS.scan}.scanInfo(sliceNum).zValue = newZvalsV(sliceNum);

        end

        % Assign appropriate z-coordinates to structures
        for strNum = 1:length(planC{indexS.structures}(strNum))

            for slcNum = 1:length(planC{indexS.structures}(strNum).contour)

                for segNum = 1:length( planC{indexS.structures}(strNum).contour(slcNum).segments)

                    if ~isempty( planC{indexS.structures}(strNum).contour(slcNum).segments(segNum).points)

                         planC{indexS.structures}(strNum).contour(slcNum).segments(segNum).points(:,3) = newZvalsV(slcNum);

                    end

                end

            end

        end

        %Save plan to destination directory
        save_planC(planC,[], 'passed', fullfile(destinDirName,fileName));

        % Export DICOM
        dcmFolderName =  fullfile(destinDCMDirName,strtok(fileName,'.'));
        if ~exist(dcmFolderName, 'dir')
            mkdir(dcmFolderName)
        end

        CERRExportDICOM(fullfile(destinDirName,fileName), dcmFolderName)

    catch

        disp([fileC{iFile}, ' failed to load'])
        continue

    end

end

close(hWait)


 function X = dtft_mex(varargin)

disp('This dtft_mex.m is a dummy m-file that is included to provide')
disp('a reminder that you must have the Mex file "dtft_mex.mex???" that')
disp('is appropriate for your system.  For pc-linux, the mex file is')
disp('called "dtft_mex.mexglx", which is provided in the "mfile"')
disp('subdirectory.  For a sun, the name is "dtft_mex.mexsol", which')
disp('may or may not be provided.  If you have another OS, then you may')
disp('be out of luck, or you may be able to cajole Jeff into compiling a')
disp('mex file for your OS.')
error 'no appropriate mex file!?'


 function [I] = wwwimread(url)

 %create a temporary file name with legal characters
 if 0
 tmpdir = '/tmp/';
 tmpfile = url;
 tmpfile = strrep(tmpfile,'//','');
 tmpfile = strrep(tmpfile,'/','-');
 tmpfile = strrep(tmpfile,'.','-');
 tmpfile = strrep(tmpfile,'http:',tmpdir);%run wget
 command = sprintf('wget %s -O %s',url,tmpfile);
 [s,w] = unix(command);
 end

 url
 s = urlread(url);
 size(s)
 fid = fopen(['./tmp.' url(end-2:end)], 'w');
 fwrite(fid, s);
 fclose(fid);

 I = imread(['./tmp.' url(end-2:end)]);
 delete(['./tmp.' url(end-2:end)]);

 if 0
 if (s == 0)
   %read in the file then delete the tmpfile
   I = imread(tmpfile);
   command = sprintf('rm -f %s',tmpfile);
   [s,w] = unix(command);
 else
   disp('error!');
   I = [];
 end;

end


function tapas_BLT_initCogent(store)
% tapas_BLT_initCogent starts cogent which is needed for the response box
%
% About:
%   Coded by F.Petzschner 19. April 2017
%	Last change: F.Petzschner 19. April 2017

if  ~store.keyboard
config_serial(store.scanner.boxport, 19200, 0, 0, 8);
start_cogent;
end

end


function bbci= bbci_calibrate_reset(bbci, varargin)
%BBCI_CALIBRATE_RESET - Revert calibration settings to original values
%
%Synopsis:
%  BBCI= bbci_calibrate_reset(BBCI)
%  BBCI= bbci_calibrate_reset(BBCI, 'param1', 'param2', ...)
%
%Argument:
%  BBCI: Structure holding specific settings for calibration in the
%     field 'calibrate'.
%
%Output:
%  BBCI - Updated BBCI structure in which all subfields of BBCI.settings
%     which are specified in BBCI.calibrate.auto_reset are reverted to
%     the values in BBCI.calibrate.default_settings.
%     For BBCI.calibrate.auto_reset=1 all subfields are reverted.

% 11-2011 - Benjamin Blankertz

BC= bbci.calibrate;
if ~isfield(BC, 'default_settings'),
  error('no default settings stored in BBCI structure');
end
BCS= bbci.calibrate.default_settings;

if nargin==1,
  fld_list= fieldnames(BCS);
elseif length(varargin)==1 && iscell(varargin{1}),
  fld_list= varargin{1};
else
  fld_list= varargin;
end

for ii= 1:length(fld_list),
  fld= fld_list{ii};
  bbci.calibrate.settings.(fld)= bbci.calibrate.default_settings.(fld);
end


function dbfprintf(varargin)
    if ~ZmapGlobal.Data.debug
        return
    end
    if isstring(varargin{1})
        fmtstr = char(varargin{1});
    else
        fmtstr = varargin{1};
    end

    if nargin>1
        fprintf(['\n---<strong> ZMAP DB: </strong>' fmtstr], varargin{2:end});
    else
        fprintf(['\n---<strong> ZMAP DB: </strong>' fmtstr]);
    end
end


function test_matlab_ci

% WALLTIME 00:05:00
% MEM 1gb
% DEPENDENCY

disp('--------------------------------------------------------------------');
ver;
disp('--------------------------------------------------------------------');
disp(pwd);
disp('--------------------------------------------------------------------');
disp(ft_version);
disp('--------------------------------------------------------------------');
system('uname -a');
disp('--------------------------------------------------------------------');
system('uptime');
disp('--------------------------------------------------------------------');
system('ls $HOME');
disp('--------------------------------------------------------------------');
system('env');
disp('--------------------------------------------------------------------');


function varargout = About(varargin)
% ABOUT M-file for About.fig
%      ABOUT, by itself, creates a new ABOUT or raises the existing
%      singleton*.
%
%      H = ABOUT returns the handle to a new ABOUT or the handle to
%      the existing singleton*.
%
%      ABOUT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in ABOUT.M with the given input arguments.
%
%      ABOUT('Property','Value',...) creates a new ABOUT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before About_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to About_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 About

% Last Modified by GUIDE v2.5 08-Jun-2009 20:35:41

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

% Choose default command line output for About
handles.output = hObject;
% Update handles structure
movegui(hObject,'onscreen')% To display application onscreen
movegui(hObject,'center')  % To display application in the center of screen
% Update handles structure
guidata(hObject, handles);

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

function varargout = About_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;

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

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

% Hint: delete(hObject) closes the figure
delete(hObject);

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

% --- Executes during object creation, after setting all properties.
function logo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to logo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called
a=imread('im3.png');
imshow(a);
% Hint: place code in OpeningFcn to populate logo


 function ir_usage(mfile_name)
%function ir_usage(mfile_name)
%|
%| Show "usage" of a given mfile in a screen-friendly way then fail with error.
%| If mfile_name is not provided, then infer from "caller_name.m"
%|
%| 2016-08-07 Jeff Fessler, University of Michigan

if nargin < 1
	mfile_name = caller_name;
	if isempty(mfile_name)
		help(mfilename), error(mfilename)
		return
	end
end

more on
help(mfile_name)
more off

%evalin('caller', 'error(''test'')')
error([mfile_name ' usage'])
%fail(mfile_name)


function write_cell(fid,cell)
% write cell string to text file

for i = 1:length(cell)
  fprintf(fid,'%s\n',cell{i});
end


function [dat] = set_name(dat,nam)

%   data = set_name(data,name) sets the name of the data_global object to
%                              name
dat.algorithm.name=nam;


% [INPUT]
% f = A valid figure instance.

function maximize_figure(varargin)

    persistent ip;

    if (isempty(ip))
        ip = inputParser();
        ip.addRequired('f',@(x)validateattributes(x,{'matlab.ui.Figure'},{'scalar'}));
    end

    ip.parse(varargin{:});

    ipr = ip.Results;
    f = ipr.f;

    nargoutchk(0,0);

    maximize_figure_internal(f);

end

function maximize_figure_internal(f)

    pause(0.1);

    if (verLessThan('MATLAB','9.4'))
        frame = get(f,'JavaFrame'); %#ok<JAVFM>
        set(frame,'Maximized',true);
    else
        set(f,'WindowState','maximized');
    end

    drawnow();

end


function varargout = MotList(varargin)
% MotionLIST MATLAB code for MotList.fig
%      MotionLIST, by itself, creates a new MotionLIST or raises the existing
%      singleton*.
%
%      H = MotionLIST returns the handle to a new MotionLIST or the handle to
%      the existing singleton*.
%
%      MotionLIST('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MotionLIST.M with the given input arguments.
%
%      MotionLIST('Property','Value',...) creates a new MotionLIST or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before MotList_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to MotList_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 MotList

% Last Modified by GUIDE v2.5 01-May-2013 21:32:35

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

handles.Simuh=varargin{1};
Category=dir([handles.Simuh.MRiLabPath filesep 'Config' filesep 'Mot']);
ind=1;
for i=1:length(Category)
    if ~strcmp(Category(i).name,'.') & ~strcmp(Category(i).name,'..') & Category(i).isdir
        handles.CategoryDir{ind,1}=Category(i).name;
        ind=ind+1;
    end
end
set(handles.Category_listbox,'String',handles.CategoryDir);

handles.accept = 0;
% Choose default command line output for MotList_figure
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = MotList_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 selection change in Mot_listbox.
function Mot_listbox_Callback(hObject, eventdata, handles)
% hObject    handle to Mot_listbox (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 Mot_listbox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Mot_listbox

if ~isempty(get(handles.MotPath_text,'String'))
    return;
end

if strcmp(handles.MotList,'Empty')
    return;
end

handles.MotXMLFile=[handles.Simuh.MRiLabPath filesep ...
                    'Config' filesep ...
                    'Mot' filesep ...
                    handles.CategoryDir{get(handles.Category_listbox,'Value')} filesep ...
                    handles.MotList{get(handles.Mot_listbox,'Value')} filesep...
                    handles.MotList{get(handles.Mot_listbox,'Value')} '.xml'];

handles.MotXMLDir=[handles.Simuh.MRiLabPath filesep ...
                    'Config' filesep ...
                    'Mot' filesep ...
                    handles.CategoryDir{get(handles.Category_listbox,'Value')} filesep ...
                    handles.MotList{get(handles.Mot_listbox,'Value')}];

guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Mot_listbox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Mot_listbox (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 selection change in Category_listbox.
function Category_listbox_Callback(hObject, eventdata, handles)
% hObject    handle to Category_listbox (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 Category_listbox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from Category_listbox

if ~isempty(get(handles.MotPath_text,'String'))
    return;
end

if strcmp(handles.CategoryDir,'Empty')
    return;
end

set(handles.Mot_listbox,'Enable','on');

Mot=dir([handles.Simuh.MRiLabPath filesep ...
          'Config' filesep ...
          'Mot' filesep ...
          handles.CategoryDir{get(handles.Category_listbox,'Value')}]);
ind=1;
handles.MotList=[];
for i=1:length(Mot)
    if ~strcmp(Mot(i).name,'.') & ~strcmp(Mot(i).name,'..')
        handles.MotList{ind,1}=Mot(i).name;
        ind=ind+1;
    end
end
if ind==1
    handles.MotList='Empty';
end
set(handles.Mot_listbox,'String',handles.MotList);
set(handles.Mot_listbox,'Value',1);

guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Category_listbox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Category_listbox (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 Accept_pushbutton.
function Accept_pushbutton_Callback(hObject, eventdata, handles)
% hObject    handle to Accept_pushbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if isempty(get(handles.MotPath_text,'String'))
    try
        if strcmp(handles.MotList{get(handles.Mot_listbox,'Value')},'Empty')
            DoUpdateInfo(handles.Simuh,'No Motion is selected!');
            return;
        end
    catch me
        DoUpdateInfo(handles.Simuh,'No Motion is selected!');
        return;
    end
end

%----update Motion selection
handles.Simuh.MotXMLFile=handles.MotXMLFile;
handles.Simuh.MotXMLDir=handles.MotXMLDir;
Mot=DoParseXML(handles.MotXMLFile);
handles.Simuh.MotStruct=Mot;
Mot_text=uicontrol(handles.Simuh.MotSel_uipanel,'Style','text');
set(Mot_text,'FontWeight','bold','FontSize',10,'Position',[0,0,140,18],...
    'String', Mot.Attributes(1).Value,'TooltipString',handles.MotXMLFile);
%----end
guidata(handles.Simuh.SimuPanel_figure,handles.Simuh);
DoUpdateInfo(handles.Simuh,'Mot file was successfully loaded!');
handles.accept = 1;
guidata(hObject, handles);
close(handles.MotList_figure);

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

% --- Executes when user attempts to close MotList_figure.
function MotList_figure_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to MotList_figure (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

DoDisableButton([],[],handles.Simuh);
if handles.accept == 0
    DoUpdateInfo(handles.Simuh,'Mot file loading was cancelled!');
end
% Hint: delete(hObject) closes the figure
delete(handles.MotList_figure);

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

[filename,pathname,filterindex]=uigetfile({'Mot*.xml','XML-files (*.xml)'},'MultiSelect','off');
if filename~=0
    handles.MotXMLFile=[pathname filename];
    handles.MotXMLDir=pathname(1:end-1);
    set(handles.MotPath_text,'String',[pathname filename]);
    % Add searchig path
    path(path,handles.MotXMLDir);

else
    errordlg('No Mot was loaded!');
    return;
end
guidata(hObject, handles);

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

if isfield(handles.Simuh,'MotXMLFile')
    handles.Simuh=rmfield(handles.Simuh,'MotXMLFile');
    delete(get(handles.Simuh.MotSel_uipanel,'Children'));
    guidata(handles.Simuh.SimuPanel_figure,handles.Simuh);
end
DoUpdateInfo(handles.Simuh,'Use default Motion!');
handles.accept = 1;
guidata(hObject, handles);
close(handles.MotList_figure);


function [ output_args ] = ESO_3rd( input_args )
%ESO_3RD Summary of this function goes here
%   Detailed explanation goes here

end


function y = subsasgn( x, varargin ) %#ok
error( 'cvx tuple objects are read-only.' );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function hRD = plugin_rd_rx
% Reference design definition

% Call the common reference design definition function
hRD = AnalogDevices.adrv9361z7035.common.plugin_rd('ccbox_lvds','Rx');
AnalogDevices.adrv9361z7035.common.add_io(hRD, 'Rx', 'ccbox_lvds');


function[]=jlab_addpath
%JLAB_ADDPATH  Adds JLAB and JDATA subdirectories to your Matlab search path.
%
%   This script adds JLAB subdirectories to your Matlab search path, as
%   well as the JDATA directory if it is found to exist.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2015--2019 J.M. Lilly --- type 'help jlab_license' for details

%First, find the path to JLAB
fullpath=which('jlab_license');
jlab_path=fullpath(1:end-15);
bool=real(jlab_path)==real('\');
jlab_path(bool)='/';

%jlab_path

for k=1:2
    if k==1
        disp('Adding JLAB subdirectories to your Matlab search path.')
        if exist(jlab_path)
            jlab_addpath_subdirectories(jlab_path);
        end
    end
    if k==2
        jlab_path=[jlab_path(1:end-5) '/jdata'];
        if exist(jlab_path)
            disp('Looks like you have JDATA installed; adding this to your path also.')
            addpath(jlab_path)
            jlab_addpath_subdirectories(jlab_path);
        end
    end
end
clear i j k dirlist dirlisti jlab_path fullpath bool

function[]=jlab_addpath_subdirectories(path)
dirlist=dir(path);
for i=1:length(dirlist)
    if dirlist(i).isdir
        if ~strcmpi(dirlist(i).name(1),'.')
            %dirlist(i).name
            addpath([path '/' dirlist(i).name])
            dirlisti=dir([path '/' dirlist(i).name]);
            for j=1:length(dirlisti)
                if dirlisti(j).isdir
                    if ~strcmpi(dirlisti(j).name(1),'.')
                        %[path '/' dirlist(i).name '/' dirlisti(j).name]
                        addpath([path '/' dirlist(i).name '/' dirlisti(j).name]);
                    end
                end
            end
        end
    end
end