function [segm_params, filepath_params, other_params] = ...
        internal_params(segm_params, filepath_params, other_params, ...
                       extra_params)
% the internal parameters which are not usually of severe importance to a
% practictioner. Nevertheless, feel free to tinker if you know what you are
% doing :)
%
% @authors:     Ahmad Humayun
% @contact:     ahumayun@cc.gatech.edu
% @affiliation: Georgia Institute of Technology
% @date:        Fall 2013 - Summer 2014

    fp = filepath_params;                                                   % Parameters related to directory locations
    sp = segm_params;                                                       % Parameters for FastSeg's technical internals
    op = other_params;                                                      % Misc. parameters
    ep = extra_params;                                                      % Params passed as an argument for overriding parameters here

    % set the filepath parameters
    fp = get_param_val(fp, ep, 'extern_src_dir', ...
                           fullfile(fp.code_root_dir, 'extern_src'));       % External dependencies directory
    fp = get_param_val(fp, ep, 'fuxin_lib_dir', ...
                           fullfile(fp.code_root_dir, 'extern_src/fuxin_lib_src'));    % External dependencies to Fuxin's library
    fp = get_param_val(fp, ep, 'extern_codes_dir', ...
                           fullfile(fp.code_root_dir, 'extern_src'));       % External dependencies packaged with this code
    fp = get_param_val(fp, ep, 'utils_src_dir', ...
                           fullfile(fp.code_root_dir, 'utils'));            % Directory to our utility functions
    fp = get_param_val(fp, ep, 'seg_save_dirpath', ...
                           fullfile(fp.data_save_dirpath, 'MySegmentsMat'));% Directory where segments computed (results) are saved
   fp = get_param_val(fp, ep, 'trained_models_dirpath', ...
                           fullfile(fp.code_root_dir, 'trained_models'));   % All the trained models (for instance, for boundary energies) reside in this directory
    fp = get_param_val(fp, ep, 'scores_dirpath', ...
                           fullfile(fp.seg_save_dirpath, 'scores'));        % Used by compute_print_results() to save quantitative results for the segments computed
    fp = get_param_val(fp, ep, 'boundaries_parent_dirpath', ...
                           fp.data_save_dirpath);                           % The main directory where boundary detection results are saved
    fp = get_param_val(fp, ep, 'debug_parent_dirpath', ...
                           fullfile(fp.data_save_dirpath, 'Debug'));        % Where any debug information is output (usually when other_params.debug = true)

    % set the Segmenter parameters
    sp = get_param_val(sp, ep, 'bg_frame_width',        1);                 % Decides the no. of pixels to use at the boundary, which is then used to generate the bg seed. A large number would force more superpixels
                                                                            % to be used background seeds. Invoked at Segmenter.precompute_unary_data().
    sp = get_param_val(sp, ep, 'filter_max_energy',     5000);              % Threshold used by Segmenter.filter_segments to filter segments with too high of a cut ratio. The energy is computed in compute_energies().
    sp = get_param_val(sp, ep, 'graph_pairwise_multiplier', ...
            {         1000           ,          1000           });          % Used in AbstractGraph.set_pairwise_graph() as a scaling factor for all pairwise capacities. A larger value will increase pairwise
                                                                            % capacities and hence increase the likelihood for larger segments. Each cell gives a value used for each graph method.
    sp = get_param_val(sp, ep, 'graph_sub_methods_cut_param', ...
            {[     1    ,     1     ], [    1     ,     1     ]});          % For graph-cut settings. Invoked in GraphProcessor.multiseed_param_min_st_cut() as <graphcut_params>. A 0 value here would schedule
                                                                            % parametric lambdas in reverse i.e. if you have lambda values of 0,1,2,5 for paramertic min-cut, a 0 parameter here would compute min-cuts
                                                                            % in the order 5,2,1,0. A parameter 1 schedules it in the normal ascending direction. Both methods give the same results but might effect the
                                                                            % computation time. This can possibly be extended to support other parameter settings for graph-cuts.
    sp = get_param_val(sp, ep, 'graph_filter_segs', ...
            {         true           ,           true          });          % Indicates whether you want to filter the segments produced by a particular graph method. Invoked in Segmenter.filter_segments().
    sp = get_param_val(sp, ep, 'graph_sol_upper_bp', ...
            [         20             ,           300           ]);          % Decides the upper limit for the lambdas used for the parameteric min-cut. This is the <u> value in GraphProcessor.generate_param_lambdas()
                                                                            % See the function to find the exact algorithm used to generate the list of lambdas for parametric min-cut.

    % set miscellaneous parameters
    hash_params.Format = 'base64';
    hash_params.Method = 'SHA-1';
    op = get_param_val(op, ep, 'hash_params', hash_params);                 % Hashing parameters. This is used to create a hash of the settings used - this is useful for figuring out if the same set of parameters were
                                                                            % used for computing a set of segments, without comparing the parameters directly.

    % compute the hash for the parameters (acts as a unique ID for params)
%     addpath(fullfile(fp.extern_codes_dir, 'DataHash'));
%     op.filepath_params_hash = DataHash(fp, hash_params);
%     op.segm_params_hash = DataHash(sp, hash_params);
    op.filepath_params_hash = num2str(sum(getByteStreamFromArray(fp)));
    op.segm_params_hash = num2str(sum(getByteStreamFromArray(sp)));

    filepath_params = fp;
    segm_params = sp;
    other_params = op;
end


function newCell=reformatElements(inputCell,type,delimiter)
%reformatElements  reformat elements of cell array to desired format
% reformatElements
%   convert cell array element format between string and nested cell
%
% Input:
%   inputCell    the input cell array
%   type         two conversion approaches: cell2str and str2cell
%                (default: str2cell)
%   delimiter    specify the delimiter separating values within the
%                element (default: semicolon)
%
% Output:
%   newCell      the output of cell array with refromatted elements
%
% Usage: newCell=reformatElements(inputCell,type,delimiter)
%

newCell={};

if ~iscell(inputCell)
		EM='Wrong input arguments';
		disp(EM);
end

if nargin < 2
    type = 'str2cell';
end

if nargin < 3
    delimiter = ';';
end

% get the index of non-empty elements
index=find(~cellfun(@isempty,inputCell));

if length(index)>0
		if (iscell(inputCell{index(1)}) && strcmpi(type,'str2cell')) || (~iscell(inputCell{index(1)})  &&  strcmpi(type,'cell2str'))
		fprintf('The conversion parameter is conflic with input data!\n');
		return;
elseif length(index)==0
		fprintf('The input cell is empty!\n');
		return;
end

% initilize output
newCell=cell(numel(inputCell),1);
newCell(:)={''};

if strcmp('str2cell',type)
    % from string to nested cell
    inputCell = regexprep(inputCell, '\s', '');   % remove space from input
	newCell(index)=cellfun(@(s) strsplit(s,delimiter),inputCell(index),'UniformOutput', false);
elseif isequal('cell2str',type)
    % combine elements of each cell to string
    delimiter = [delimiter(~isspace(delimiter)) ' '];  % append one space only
    newCell(index)=cellfun(@(s) strjoin(s,delimiter),inputCell(index),'UniformOutput', false);
end

end


function[]=boxoff
% BOXON  Sets 'box' property to 'off'.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2006 J.M. Lilly --- type 'help jlab_license' for details

set(gca,'box','off');


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

% Last Modified by GUIDE v2.5 23-Jul-2004 12:45:11

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

handles.output = hObject;
Monitor_Mode(hObject, eventdata, handles);
S = imread('autumn.tif');
handles.S = S;
axes(handles.axes1);
subimage(S);
S2 = imread('autumn.tif');
axes(handles.axes2);
subimage(S2);
handles.S2 = S2;
guidata(hObject, handles);

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

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

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

% --- Executes on button press in pbStart.
function pbStart_Callback(hObject, eventdata, handles)
% hObject    handle to pbStart (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,'outdata')
    handles = rmfield(handles,'outdata');
end
guidata(hObject, handles);
set(handles.pbStart,'enable','off');
set(handles.pbStop,'enable','on');

set(handles.pbStop,'UserData',0);

vid = videoinput('winvideo');
handles.vid = vid;
set(handles.vid,'FramesPerTrigger',1);
set(handles.vid,'TriggerRepeat',Inf);
triggerconfig(handles.vid, 'Manual');

guidata(hObject, handles);

start(handles.vid);
trigger(handles.vid);
y = (getdata(handles.vid,1,'uint8'));
cnt_move = 0;
cnt_unmove = 0;
cntsnap = 1;
while 1
    trigger(handles.vid);
    yprev = y;
    set(handles.editTime,'string',datestr(clock));
    if get(handles.pbStop,'UserData')
        break
    else
        y = (getdata(handles.vid,1,'uint8'));
        diff = abs(y-yprev);
        abs_img = mean(diff(:));
        set(handles.editAbs,'string',abs_img);
        axes(handles.axes1);subimage(y);
        axes(handles.axes2);subimage(diff);
        out = imaqmem;
        mem_left = out.FrameMemoryLimit - out.FrameMemoryUsed;
        set(handles.editMemLeft,'string',mem_left/10^6);
        set(handles.editMemLoad,'string',out.MemoryLoad);
        if abs_img > str2num(get(handles.editThresh,'string'));
            cnt_move = cnt_move + 1;
            set(handles.editObj,'string',cnt_move);
            if cnt_move >= str2num(get(handles.editSnapCnt,'string'));
                handles.outdata.image(:,:,:,cntsnap) = y;
                handles.outdata.time{cntsnap} = datestr(clock);
                cntsnap = cntsnap + 1;
                cnt_move = 0;
                set(handles.editSnap,'string',cntsnap-1);
            end
            cnt_unmove = 0;
        else
            cnt_unmove = cnt_unmove + 1;
            cnt_move = 0;
            set(handles.editObj,'string',cnt_move);
        end

    end
end

axes(handles.axes1);
cla;
subimage(handles.S);
axes(handles.axes2);
cla;
subimage(handles.S2);
delete(handles.vid);
clear handles.vid;
imaqreset;
guidata(hObject, handles);

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

set(handles.pbStart,'enable','on');
set(handles.pbStop,'enable','off');

set(handles.pbStop,'UserData',1);
set(handles.pbStop,'UserData',1);
set(handles.pbStop,'UserData',1);
set(handles.pbStop,'UserData',1);
set(handles.pbStop,'UserData',1);
guidata(hObject, handles);

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

% --- Executes during object creation, after setting all properties.
function editAbs_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editAbs (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function editMemLeft_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMemLeft (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function editMemLoad_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMemLoad (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function editThresh_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editThresh (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function editObj_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editObj (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function editSnap_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editSnap (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

    set(hObject,'string','Play');
    recorded_data = handles.outdata;
    sz = size(recorded_data.image);
    frm_num = sz(4);
    cntstart = round(get(handles.sldFrame,'value'));

    for cnt = cntstart:frm_num
        axes(handles.axes1);
        subimage(recorded_data.image(:,:,:,cnt));
        axes(handles.axes2);
        St = edge(rgb2gray(recorded_data.image(:,:,:,cnt)));
        subimage(St);
        set(handles.sldFrame,'value',cnt);
        set(handles.editTime2,'string',recorded_data.time{cnt});
        set(handles.txtCurrent,'string',cnt);

        if ~(get(hObject,'value'))
            break
        end
        pause(0.01);
    end
else
    set(hObject,'string','Pause');
end
set(hObject,'value',0);
set(hObject,'string','Pause');

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

% --- Executes during object creation, after setting all properties.
function editTime_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editTime (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

% --- Executes on slider movement.
function sldFrame_Callback(hObject, eventdata, handles)
% hObject    handle to sldFrame (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
%

recorded_data = handles.outdata;
cnt = round(get(handles.sldFrame,'value'));
set(handles.sldFrame,'value',cnt)

axes(handles.axes1);
subimage(recorded_data.image(:,:,:,cnt));
axes(handles.axes2);
St = edge(rgb2gray(recorded_data.image(:,:,:,cnt)));
subimage(St);
set(handles.editTime2,'string',recorded_data.time{cnt});
set(handles.txtCurrent,'string',cnt);

% --- Executes during object creation, after setting all properties.
function sldFrame_CreateFcn(hObject, eventdata, handles)
% hObject    handle to sldFrame (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, change
%       'usewhitebg' to 0 to use default.  See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
    set(hObject,'BackgroundColor',[.9 .9 .9]);
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function editTime2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editTime2 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% --- Executes during object creation, after setting all properties.
function editSnapCnt_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editSnapCnt (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function Monitor_Mode(hObject, eventdata, handles)
set(handles.pbStart,'enable','on');
set(handles.pbStop,'enable','off');
set(handles.pbPlay,'enable','off');
set(handles.sldFrame,'enable','off');
set(handles.txtMin,'enable','off');
set(handles.txtMax,'enable','off');
set(handles.txtCurrent,'enable','off');

function PlayBack_Mode(hObject, eventdata, handles)
set(handles.pbStart,'enable','off');
set(handles.pbStop,'enable','off');
set(handles.pbPlay,'enable','on');
set(handles.sldFrame,'enable','on');
set(handles.txtMin,'enable','on');
set(handles.txtMax,'enable','on');
set(handles.txtCurrent,'enable','on');

% % --------------------------------------------------------------------
% function modeSelect_SelectionChangeFcn(hObject, eventdata, handles)
% % hObject    handle to modeSelect (see GCBO)
% % eventdata  reserved - to be defined in a future version of MATLAB
% % handles    structure with handles and user data (see GUIDATA)
% if get(handles.radioMonitor,'Value')==1
%     Monitor_Mode(hObject, eventdata, handles);
% else
%     PlayBack_Mode(hObject, eventdata, handles);
% end

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

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

selected_mode = 1;
set(hObject,'value',selected_mode);
set(handles.radioPlayBack,'value',~selected_mode);
Monitor_Mode(hObject, eventdata, handles);

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

% Hint: get(hObject,'Value') returns toggle state of radioPlayBack
selected_mode = 1;
set(hObject,'value',selected_mode);
set(handles.radioMonitor,'value',~selected_mode);

recorded_data = handles.outdata;
sz = size(recorded_data.image);
frm_num = sz(4);

set(handles.sldFrame,'min',1);
set(handles.sldFrame,'max',frm_num);
set(handles.sldFrame,'SliderStep',[1/frm_num 5/frm_num]);
set(handles.txtMin,'string',1);
set(handles.txtMax,'string',frm_num);

set(handles.sldFrame,'value',1);
PlayBack_Mode(hObject, eventdata, handles);


function [vectorTo] = niftiCreateStringInplane(vectorFrom, sliceDimension)
%
%Given a vector string and the slice dimension, return the correct string
%orientation in the Vistalab Inplane format, which does not touch the slice
%dimension

%We are looking to return something that will keep the slice dimension the
%same, but make it be the 3rd dimension, then if, L-R are there, make it
%the second dimension, otherwise, leave the other two dimensions as they are

vectorTo = vectorFrom; %We will operate purely on vectorTo

if (sliceDimension ~= 3)
    %We need to move the slice dimension to 3
    tmpChar = vectorTo(sliceDimension);
    vectorTo(sliceDimension) = vectorTo(3);
    vectorTo(3) = tmpChar;
end %if

%We now have a vector that has the 3rd dimension be the slice dimension
%Now, let's move LR dimension to 1st position

LRdim = niftiFindDimOfString(vectorTo,'R'); %This will find either R or L

if (LRdim ~= 3 && LRdim ~= 2) %i.e. it is not the slice dimension nor is it already the second dimension
    tmpChar = vectorTo(2);
    vectorTo(2) = vectorTo(LRdim);
    vectorTo(LRdim) = tmpChar;
end %if

tmpChar = vectorTo(3); %Get the slice dimension and reapply it after, to preserve it
vectorTo = niftiCreateComplementString(vectorTo);
vectorTo(3) = tmpChar;

return


%Voice Based Biometric System
%By Ambavi K. Patel.

function w1=nanclr(w1)  % to replace  'not a number' vlues
[r1,c1]=size(w1);
for i=1:r1
    temp=isnan(w1(i,1:c1));
    for j=1:c1
        if temp(j)==1
            w1(i,j)=0.0001;
        else
        end;
    end;
end;


function qualityMeasure = callQualityMeasure(sr, gt, qualityMeasureName)

    % Assemble name of the quality measure wrapper function.
    funName = sprintf('imageQuality_%s', qualityMeasureName);

    % Call the desired quality measure.
    qualityMeasure = feval(funName, sr, gt);


function mov = aviread_rawy8(filename,varargin)
%AVIREAD Read AVI file.
%   AVIREAD will be removed in a future release. Use VIDEOREADER instead.
%
%   MOV = AVIREAD(FILENAME) reads the AVI movie FILENAME into the
%   MATLAB movie structure MOV. If FILENAME does not include an
%   extension, then '.avi' will be used. MOV has two fields, "cdata"
%   and "colormap". If the frames are truecolor images, MOV.cdata will
%   be Height-by-Width-by-3 and MOV.colormap will be empty. If the
%   frames are indexed images, then MOV.cdata field will be
%   Height-by-Width and MOV.colormap will be M-by-3. On UNIX, FILENAME
%   must be an uncompressed AVI file.
%
%   MOV = AVIREAD(...,INDEX) reads only the frame(s) specified by
%   INDEX.  INDEX can be a single index or an array of indices into the
%   video stream, where the first frame is number one.
%
%   The supported frame types are 8-bit (indexed or grayscale),
%   16-bit grayscale or 24-bit (TrueColor) frames.
%
%   See also VIDEOREADER, VIDEOWRITER, MOVIE.

%   Copyright 1984-2011 The MathWorks, Inc.
%   $Revision: 1.1.6.18.2.1 $  $Date: 2011/12/13 18:36:41 $

%warning(message('MATLAB:audiovideo:aviread:FunctionToBeRemoved'));

% Initialization
map = [];
index = -10000;

% Validate input/output.
error(nargoutchk(1,1,nargout, 'struct'));
error(nargchk(1,2,nargin, 'struct'));

if nargin == 2
    if isnumeric(varargin{1})
        index = varargin{1};
    else
        error(message('MATLAB:audiovideo:aviread:nonNumericIndex'));
    end
end

if ~ischar(filename)
    error(message('MATLAB:audiovideo:aviread:invalidFilename'));
end

[path,name,ext] = fileparts(filename);
if isempty(ext)
    filename = strcat(filename,'.avi');
end

info = getAviInfo( filename );

if ismember(lower(info.VideoFrameHeader.CompressionType),{'y800','y8'}),
  info.VideoFrameHeader.CompressionType = 'RAW ';
end

if (index(1) ~= -10000)
    if ( isfield(info.MainHeader,'HasIndex') == 0 )
        error(message('MATLAB:audiovideo:aviread:indexParameterNotSupported', filename));
    elseif any(index > info.MainHeader.TotalFrames)
        error(message('MATLAB:audiovideo:aviread:indexOutOfRange', info.MainHeader.TotalFrames));
    elseif any(index <= 0)
        error(message('MATLAB:audiovideo:aviread:invalidZeroIndex'));
    end
end

% if ispc
%     try
%         if index == -10000
%             X = readavi(info.Filename,-1);
%         else
%             X = readavi(info.Filename,index-1);
%         end
%     catch exception
%         if strcmpi(exception.identifier,'MATLAB:audiovideo:aviread:invalidcodec') == 1 && ...
%             strcmpi(info.VideoFrameHeader.CompressionType,'indeo5')
%             % if we get an invalid codec error and are asking for indeo5
%             % inform the user of the problem and link to mathworks.com
%             error(message('MATLAB:audiovideo:aviread:indeo5NotFound'));
%         else
%             throw(exception);
%         end
%     end
%
%     % The width of the frames may be padded to be on 4 byte boundaries because
%     % this is how bitmaps are typically written.  However, AVI files do not
%     % restrict the frames to lie on 4 byte boundries.  Because of
%     % inconsistencies with the header information in AVI files, the READAVI
%     % MEX-function determines if the frame is padded and reads the correct
%     % number of bytes for each frame.  If the returned data is more than
%     % expected (different for indexed and RGB) then the data is padded.  The
%     % padding is removed before frames are returned by AVIREAD.
%
%     width = info.VideoFrameHeader.Width;
%     if ((info.VideoFrameHeader.Width*info.VideoFrameHeader.Height ~= length(X(1).cdata)) && (info.VideoFrameHeader.BitDepth == 8)) || ((info.VideoFrameHeader.Width*info.VideoFrameHeader.Height*3 ~= length(X(1).cdata)) && (info.VideoFrameHeader.BitDepth == 24) )
%         paddedWidth = 4*ceil(width/4);
%     else
%         paddedWidth = width;
%     end
%     height = info.VideoFrameHeader.Height;
%
%     if info.VideoFrameHeader.BitDepth == 8 || info.VideoFrameHeader.BitDepth == 16
%         % Indexed frames
%         for i=1:length(X)
%             if height<0
%                 % Movie frames are stored top down (height is negative).
%                 mov(i).cdata = reshape(X(i).cdata, paddedWidth, abs(height))';
%             else
%                 mov(i).cdata = rot90(reshape(X(i).cdata, paddedWidth, height));
%             end
%             if paddedWidth ~= width
%                 mov(i).cdata = mov(i).cdata(:,1:width);
%             end
%             map = reshape(X(i).colormap, 4, ...
%                 info.VideoFrameHeader.NumColormapEntries);
%             map = double(flipud(map(1:3,:))')/255;
%             mov(i).colormap = map;
%         end
%     elseif info.VideoFrameHeader.BitDepth == 24
%         paddedWidth = 4*ceil(width*3/4);
%         % Truecolor frames
%         for i=1:length(X)
%             f = X(i).cdata;
%             if height<0
%                 % Movie frames are stored top down (height is negative).
%                 f = permute(reshape(f, paddedWidth, abs(height)),[2 1 3]);
%             else
%                 f = rot90(reshape(f, paddedWidth,height));
%             end
%             if paddedWidth ~= width
%                 f = f(:,1:width*3);
%             end
%             % Movie frames are stored top down (height is negative).
%             RGB(1:abs(height), 1:width,3) = f(:,1:3:end);
%             RGB(:, :, 2) = f(:,2:3:end);
%             RGB(:, :, 1) = f(:,3:3:end);
%             mov(i).cdata = RGB;
%             mov(i).colormap = [];
%         end
%     else
%         error(message('MATLAB:audiovideo:aviread:invalidColorBitDepth'));
%     end
% end %End of PC specific code

% if isunix

    if isempty(strmatch(lower(info.VideoFrameHeader.CompressionType),...
            {'dib ', 'raw ','none','raw ',char([0 0 0 0])}))
        error(message('MATLAB:audiovideo:aviread:compressedFileInvalid'));
    end

    if strcmpi(info.VideoFrameHeader.CompressionType,char([0 0 0 0]))
        info.VideoFrameHeader.CompressionType = 'none';
    end

    fid = fopen(filename,'r','l');
    if fid == -1
        error(message('MATLAB:audiovideo:aviread:unableToOpenFile', filename));
    end

    % Find RIFF chunk
    [chunk, msg,msgID] = findchunk(fid,'RIFF');
    errorWithFileClose(msgID,msg,fid);

    % Read AVI chunk
    [rifftype,msg,msgID] = readfourcc(fid);
    errorWithFileClose(msgID,msg,fid);
    if ( strcmp(rifftype,'AVI ') == 0 )
        errorWithFileClose('MATLAB:audiovideo:aviread:MissingAVIChunk',xlate('Not a valid AVI file. Missing ''AVI '' chunk.'), fid);
    end

    % Find hdrl LIST chunk
    [hdrlsize,msg,msgID] = findlist(fid,'hdrl');
    errorWithFileClose(msgID,msg,fid);

    % Find and skip avih chunk
    [chunk,msg,msgID] = findchunk(fid,'avih');
    errorWithFileClose(msgID,msg,fid);
    [msg,msgID] = skipchunk(fid,chunk);
    errorWithFileClose(msgID,msg,fid);

    % Find the video stream
    for  i = 1:info.MainHeader.NumStreams
        % Find strl LIST chunk
        [strlsize,msg,msgID] = findlist(fid,'strl');
        errorWithFileClose(msgID,msg,fid);
        % Read strh chunk
        [strhchunk,msg,msgID] = findchunk(fid,'strh');
        errorWithFileClose(msgID,msg,fid);
        % Determine stream type
        streamType = readfourcc(fid);
        % Break if it is a video stream
        if(strcmp(streamType,'vids'))
            found = 1;
            break;
        else
            found  = 0;
            % Seek to end of strl list minus the amount read
            if ( fseek(fid,listsize - 16,0) == -1 )
                errorWithFileClose('MATLAB:audiovideo:aviread:invalidChunkSize',getString(message('MATLAB:audiovideo:aviread:invalidChunkSizeAVI')), fid);
            end
        end
    end

    if (found == 0)
        errorWithFileClose('MATLAB:audiovideo:aviread:noVideoStreamFound',getString(message('MATLAB:audiovideo:aviread:noVideoStreamFound')), fid);
    end

    % Skip the strh chunk minus the fourcc (4 bytes) already read.
    strhchunk.cksize = strhchunk.cksize - 4;
    [msg,msgID] = skipchunk(fid,strhchunk);
    errorWithFileClose(msgID,msg,fid);

    % Read strf chunk
    [strfchunk,msg,msgID] = findchunk(fid,'strf');
    errorWithFileClose(msgID,msg,fid);

    if info.VideoFrameHeader.BitDepth == 24
        % For TrueColor images, skip the Stream Format chunk
        [msg,msgID] = skipchunk(fid,strfchunk);
        errorWithFileClose(msgID,msg,fid);
    elseif  info.VideoFrameHeader.BitDepth == 8
        % If bitmap has a palette Seek past the BITMAPINFOHEADER to put the
        % file pointer at the beginning of the colormap
        if  fseek(fid,info.VideoFrameHeader.BitmapHeaderSize,0) == -1
            errorWithFileClose('MATLAB:audiovideo:aviread:invalidBitmapInfoHeaderSize',getString(message('MATLAB:audiovideo:aviread:invalidBitmapInfoHeaderSize')),fid);
        end
        map = readColormap(fid,info.VideoFrameHeader.NumColorsUsed);
    else
        errorWithFileClose('MATLAB:audiovideo:aviread:invalidColorBitDepth',getString(message('MATLAB:audiovideo:aviread:invalidColorBitDepthBitmap')), fid);
    end

    % Search for the movi LIST
    [movisize,msg,msgID] = findlist(fid,'movi');
    errorWithFileClose(msgID,msg,fid);
    % movioffset will be used when using idx1. The offsets stored in idx1 are
    % with respect to just after the 'movi' LIST (not including 'movi')
    movioffset = ftell(fid) -4;

    %Determine method of reading movie
    if ( index ~= -10000 )
        method = 'UseIndex';
    elseif ( isfield(info,'IsInterleaved') == 1 )
        method = 'Interleaved';
    else
        method = 'Normal';
    end

    totalReadFrames = 1;
    switch method
        case 'Interleaved'
            % Read movies that are interleaved (contain rec lists)
            while(totalReadFrames < info.MainHeader.TotalFrames )
                [recsize, msg] = findlist(fid,'rec ');
                currentPos = ftell(fid);
                % The recListPos is the current position plus the rec list size minus
                % 4 bytes because we read the four character LIST name in findlist
                recListEndPos = currentPos + recsize - 4;
                chunk = readchunk(fid);
                while(~strcmpi(chunk.ckid,'00db') && ~strcmpi(chunk.ckid,'00dc'))
                    [msg,msgID] = skipchunk(fid,chunk);
                    errorWithFileClose(msgID,msg,fid);
                    if (ftell(fid)==recListEndPos)
                        [recsize,msg,msgID] = findlist(fid,'rec ');
                        errorWithFileClose(msgID,msg,fid);
                        currentPos = ftell(fid);
                        recListEndPos = currentPos + recsize - 4; % minus 4 because we read
                    end
                    chunk = readchunk(fid);
                end

                % Prepare input for readbmpdata
                tempinfo = info;
                tempinfo.ImageDataOffset = ftell(fid);
                tempinfo.CompressionType = info.VideoFrameHeader.CompressionType;
                tempinfo.BitDepth = info.VideoFrameHeader.BitDepth;
                % readbmpdata opens and closes the file so aviread must also to
                % have a valid fid.
                status = fclose(fid);

                RGB = readbmpdata(tempinfo);

                fid = fopen(filename,'r','l');
                fseek(fid,tempinfo.ImageDataOffset,'bof');
                % readbmpdata does not move the file pointer
                [msg,msgID] = skipchunk(fid,chunk);
                errorWithFileClose(msgID,msg,fid);
                % Assign to MATLAB movie structure
                mov(totalReadFrames).cdata = RGB;
                totalReadFrames = totalReadFrames+1;
            end
        case 'Normal'
            % Find each of the 00db or 00dc chunks and read the frames
            for i = 1:info.MainHeader.TotalFrames
                chunk = readchunk(fid);
                while (~strcmpi(chunk.ckid,'00db') && ~strcmpi(chunk.ckid,'00dc') );
                    [msg,msgID] = skipchunk(fid,chunk);
                    errorWithFileClose(msgID,msg,fid);
                    chunk = readchunk(fid);
                end

                % Prepare data to be sent to readbmpdata
                tempinfo.Filename = info.Filename;
                tempinfo.Width = info.VideoFrameHeader.Width;
                tempinfo.Height = info.VideoFrameHeader.Height;
                tempinfo.ImageDataOffset = ftell(fid);
                tempinfo.CompressionType = 'none';
                tempinfo.BitDepth = info.VideoFrameHeader.BitDepth;
                % readbmpdata opens and closes the file so aviread must also to
                % have a valid fid
                status = fclose(fid);
                % Read RGB frame
                RGB = readbmpdata(tempinfo);

                fid = fopen(filename,'r','l');
                fseek(fid,tempinfo.ImageDataOffset,'bof');
                [msg,msgID] = skipchunk(fid,chunk);
                errorWithFileClose(msgID,msg,fid);
                % Assign to MATLAB movie structure
                mov(i).cdata = RGB;
            end
        case 'UseIndex'
            % Skip the movi LIST (minus 4 because 'movi' was read) and use idx1.
            if ( fseek(fid,movisize-4,0) == -1 )
                errorWithFileClose('MATLAB:audiovideo:aviread:InvalidChunkSize',getString(message('MATLAB:audiovideo:aviread:InvalidChunkSizeWAV')), fid);
            end
            % Find idx1 chunk
            [idx1chunk,msg,msgID] = findchunk(fid,'idx1');
            errorWithFileClose(msgID,msg,fid);
            idx1ChunkPos = ftell(fid);

            for j = 1:length(index)
                fseek(fid,idx1ChunkPos,'bof');
                for i = 1:index(j)
                    found = 0;
                    while(found == 0)
                        id = readfourcc(fid);
                        if (strcmpi(id,'00db') || strcmpi(id,'00dc'))
                            found = 1;
                        end
                        [idx1data,msg,msgID] = readIDX1(fid);
                        errorWithFileClose(msgID,msg,fid);
                    end

                    % If the very first index inside the 'idx1' chunk contains a
                    % data offset that is larger than the 'movi' list offset, then
                    % it is an absolute offset.  Otherwise, we will calculate the
                    % offset relative to the beginning of the 'movi' list.
                    if (i == 1)
                        if (idx1data.offset > movioffset)
                            isIdx1OffsetAbsolute = true;
                        else
                            isIdx1OffsetAbsolute = false;
                        end
                    end
                end

                % Prepare data to be sent to readbmpdata
                tempinfo.Filename = info.Filename;
                tempinfo.Width = info.VideoFrameHeader.Width;
                tempinfo.Height = info.VideoFrameHeader.Height;
                tempinfo.BitDepth = info.VideoFrameHeader.BitDepth;
                % 8 is the riffheadersize

                % Add the 'movi' offset only if the data offset is not absolute.
                if isIdx1OffsetAbsolute
                    tempinfo.ImageDataOffset = idx1data.offset + 8;
                else
                    tempinfo.ImageDataOffset = movioffset + idx1data.offset + 8;
                end
                %tempinfo.CompressionType = info.VideoFrameHeader.CompressionType;
                tempinfo.CompressionType = 'none';
                % readbmpdata opens and closes the file so aviread must also to
                % have a valid fid
                currPos = ftell(fid);
                status = fclose(fid);

                frame = readbmpdata(tempinfo);

                fid = fopen(filename,'r','l');
                fseek(fid,currPos,'bof');
                mov(j).cdata = frame;
            end
    end
    fclose(fid);
    % Formulate outputs
    [mov.colormap] = deal(map);
    varargout{1} = mov;
%end
return

function map = readColormap(fid,numColors)
% Read colormap for 8-bit indexed images
map = fread(fid,numColors*4,'*uint8');
map = reshape(map,4,numColors);
map = double(flipud(map(1:3,:))')/255;
return;

function [idx1data,msg,msgID] = readIDX1(fid)
% Read the data in the idx1 chunk.
msg = '';
msgID='';
[idx1data.flags, count] = fread(fid,1,'uint32');
if ( count ~= 1 )
    msgID = 'MATLAB:audiovideo:aviread:IncorrectIDX1ChunkSize';
    msg = getString(message(msgID));
end
[idx1data.offset, count] = fread(fid,1,'uint32');
if ( count ~= 1 )
    msgID = 'MATLAB:audiovideo:aviread:IncorrectIDX1ChunkSize';
    msg = getString(message(msgID));
end
[idx1data.length, count] = fread(fid,1,'uint32');
if ( count ~= 1 )
    msgID = 'MATLAB:audiovideo:aviread:IncorrectIDX1ChunkSize';
    msg = getString(message(msgID));
end
return;

function errorWithFileClose(msgID,msg,fid)
%Close open file the error
if ~isempty(msgID)
    fclose(fid);
    error(msgID,msg);
end
return;

function info = getAviInfo( filename )
    aviinfoWarningID = 'MATLAB:audiovideo:aviinfo:FunctionToBeRemoved';
    S = warning('OFF', aviinfoWarningID);
    cleaner = onCleanup(@()warning(S));

    % Save the state of lastwarn
    [preWarningMsg, preWarningID] = lastwarn();

    info = aviinfo(filename,'Robust');

    [~, lastWarningID] = lastwarn();

    % If aviinfo warns about deprecation restore
    % the penultimate last warning
    if (strcmp(lastWarningID, aviinfoWarningID))
        lastwarn( preWarningMsg, preWarningID );
    end


% GREP EXAMPLES
%
% - note only selected output is shown for the sake of brevity
% - note clicking on any underlined text
%	file name
%	line number
%   will open the file at the matching line

% create a line separator
	sep=@(x) disp(sprintf(repmat('-',1,75)));

% assume GREP.TXT is in your current working folder
	fnam='grep.txt';
% - show contents (note all spaces are TABs!)
	type(fnam);

% simple case insensitive [-i] string search in GREP.M for instances of
%		Version
% listing file name [def] and the line number [-n] of occurrences
%-------------------------------------------------------------------------------
	grep -i -n Version grep.m
	sep();

% regular expression search [-R] in GREP.M for instances of
%		=true or =false
% listing line number [-n] but not the file name [-Q]
%-------------------------------------------------------------------------------
	grep -Q -n -R =true|=false grep.m
	sep();

% simple string search in GREP.M for exactly matching [-x] instances of
%		\t\tmsg=true;
% listing the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	TAB=sprintf('\t');
	fl=grep('-x -n',[TAB,TAB,'msg=true;'],'grep.m');
	sep();

% simple string search in GREP.TXT for
%		every line of itself in turn
% using the pattern-file [-f] option and
% listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] for each occurrence
%-------------------------------------------------------------------------------
	fl=grep('-l -f',fnam,fnam);
	sep();

% simple string search in GREP.TXT for instances of
%		-n
% using the [-e] option since -n itself is an option flag (listing line number!)
% and listing the file name [def] for each non-matching line [-v] only
% - compare with previous example!
%-------------------------------------------------------------------------------
	fl=grep('-v -e',{'-n'},fnam);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
% listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	fpat=[matlabroot,'/toolbox/matlab/elfun'];
	fl=grep('-r -l -n',{'sign','cosine','atan'},fpat);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
% using the two versions of the [-e] option and
% listing the full file name and pattern for each file with matches [-l]
% as well as the count [-c] of all instances
%-------------------------------------------------------------------------------
	fl=grep('-r -l -c -e sign -e',{'cosine','atan'},fpat);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
%	only including files with a regular expression pattern [-If]
%		[Cc]ont
% using the two versions of the [-e] option and
% listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	fl=grep('-r -l -n -If [Cc]ont -e sign -e',{'cosine','atan'},fpat);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
%	only including files with a regular expression pattern [-If]
%		[Cc]ont
%	and excluding folders with a pattern [-Xd]
%		/ja
% - using the two versions of the [-e] option,
% and listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	fl=grep('-r -l -n -If [Cc]ont -e sign -e',{'cosine','atan'},'-Xd','/ja',fpat);
	sep();


function [] = saveSimResults()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%{
This is a simple save routine provided as part of a quadcopter simulation.

    Additional quadcopter modeling and simulation materials available at:
    github.com/dch33/Quad-Sim

Copyright (C) 2014 D. Hartman, K. Landis, S. Moreno, J. Kim, M. Mehrer

License:
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
%}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

yout = evalin('base','yout');
tout = evalin('base','tout');
quadModel = evalin('base','quadModel');
IC = evalin('base','IC');
pathExist = 'exist(''path'',''var'')';
if evalin('base',pathExist)
    path = evalin('base','path');
    data = {'yout', 'tout', 'quadModel', 'IC', 'path'};
else
    data = {'yout', 'tout', 'quadModel', 'IC'};
end
uisave(data,'simResults_1')

github-repos/MATLAB/dch33-Quad-Sim/Quad-Sim-961bc69d4939c8d0661eeb9820de668994262f65/Quadcopter Dynamic Modeling and Simulation/Simulation Files/Functions/saveSimResults.m


function doomsday_test ( )

%*****************************************************************************80
%
%% DOOMSDAY_TEST tests the DOOMSDAY library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 May 2012
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'DOOMSDAY_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the DOOMSDAY library.\n' );

  doomsday_test01 ( );
  doomsday_test02 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'DOOMSDAY_TEST:\n' );
  fprintf ( 1, '  Test the DOOMSDAY library.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function cFiles = defaultCFileList;
% Returns a list of all .c source files found in the VISTASOFT repository.
%
% cFiles = defaultCFileList;
%
% This list was found using grep (around October 2008). cFiles is a cell
% array of strings. Each entry is relative to the default VISTASOFT root
% path.
%
% Some mex files need to concatenate multiple source files. You can
% concatenate the source file names separated by a ';'. E.g.:
% '/some/dir/first.c;some/dir/second.c' will compile first.c as the mex
% file 'first.mexext' and link in the code from second.c.
%
% Some mex files need options for compilations (e.g. linking against system
% provided libraries). To pass in an option use a string that starts with
% '-' (e.g. '-lz').  This will then be skipped in the filepath expansion
% and just based to the mex command line.
%
% ras 10/2008.
% 2009.07.01 RFD: cleaned up a few details. Can now compile things that
% require multiple source files (e.g., niftiRead)

% This will ultimately be the output:
cFiles = {};

% We search our path for these files. Files grouped together, need to be
% compiled in that order: e.g. 'mex matToQuat.c nifti1_io.c znzlib.c' (with
% their respective paths, of course).

cFileNames = {...
    {'-lz','matToQuat.c', 'nifti1_io.c', 'znzlib.c'}...
    {'-lz','readFileNifti.c', 'nifti1_io.c', 'znzlib.c'}...
    {'-lz','writeFileNifti.c', 'nifti1_io.c', 'znzlib.c'}...
    {'mrManDist.c'}...
    {'assignToNearest.c'}...
    {'spm_hist2_weighted.c'}...
    {'spm_hist2_weighted_MI.c'}...
    {'coranal.c'} ...
    {'sumOfNeighbors.c'} ...
    {'updateTinC.c'} ...
    {'varOfNeighbors.c'} ...
    {'dtiFitTensor.c'} ...
    {'dtiJointHist.c'} ...
    {'dtiSplitTensor.c'} ...
    {'dtiTensorInterp_Pajevic.c'} ...
    {'ndfun.c'} ...
    {'magicwand1.c'} ...
    {'initInvDiagsInC.c'} ...
    {'trilin.c'}...
    {'dtiLoadConTrackPaths.c'}...
    {'mrAnatFastInterp3.c'}...
    {'myCinterp3.c'}...
    {'findNearest.c'}...
    {'pnet.c'}...
    {'mrManDist.c'}...
    {'assignToNearest.c'}...
    {'edgesCross2d.c'}...
    {'mCheck.c'}...
    {'mrCheckNode2dIntersect.c'}...
    {'evaluate.c'}...
    {'regHistogram.c'}...
    {'SagittalRot.c'}...
    {'ObliqueRot.c'}...
    {'SagittalRot.c'}...
    {'ObliqueRot.c'}...
    {'SagittalRot.c'}...
    {'regInplanes.c'}...
    {'corrDn.c'}...
    {'histo.c'}...
    {'corrDn.c'}...
    {'histo.c'}...
    {'wrap.c'}...
    {'convolve.c'}...
    {'upConv.c'}...
    {'range2.c'}...
    {'edges-orig.c'}...
    {'edges.c'}...
    {'pointOp.c'}...
    {'wrap.c'}...
    {'convolve.c'}...
    {'upConv.c'}...
    {'range2.c'}...
    {'edges-orig.c'}...
    {'edges.c'}...
    {'pointOp.c'}...
    {'corrDn.c'}...
    {'histo.c'}...
    {'wrap.c'}...
    {'convolve.c'}...
    {'upConv.c'}...
    {'range2.c'}...
    {'edges-orig.c'}...
    {'edges.c'}...
    {'pointOp.c'}...
    {'varOfNeighbors.c'}};

for ii=1:length(cFileNames)
    this_files = [];
    for jj=1:length(cFileNames{ii})

        %JMA - This is a bit kludgy and not robust but quick.
        %If the first character of the string is a "-" then treat it as a
        %option string and don't try to expand the full path of a filename
        if strncmp(cFileNames{ii}{jj},'-',1)
            stringToAdd =     cFileNames{ii}{jj};
        else
            stringToAdd = which(cFileNames{ii}{jj});
        end

        this_files = [this_files stringToAdd ' '];
    end
    cFiles{ii} = this_files;
end

return


function cbar = cbarLoadPreset(name, viewer, o);
% Load a preset colorbar, and set it as the colorbar for a mrViewer
% overlay.
%
%  cbar = cbarLoadPreset([name=prompt], [viewer=gcf], [o=1]);
%
% name is the name (filename) of a saved colorbar. viewer is a handle to
% a mrViewer UI. o is the overlay index for the cbar.
%
% ras, 02/24/07.
if notDefined('name')
	name = inputdlg({'Colorbar Name?'}, 'Load a Preset Cbar', 1, {''});
	name = name{1};
end

if notDefined('viewer'),	viewer = gcf;		end
if notDefined('o'),			o = 1;				end

presetsDir = fileparts(which(mfilename));

cbarPath = fullfile(presetsDir, [name '.mat']);
if ~exist(cbarPath, 'file')
	what(presetsDir)
	error(sprintf('Preset %s not found.', name))
end

cbar = cbarLoad(cbarPath);

mrViewSetOverlay(viewer, 'cbar', cbar, o);

return


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

% Last Modified by GUIDE v2.5 07-Aug-2020 18:25:36

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

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

    centerUIFigure(hObject);

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

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

    procDataFcn = varargin{3};
    setappdata(hObject,'procDataFcn',procDataFcn);

    lvdOpt = lvdData.optimizer;
    varSet = lvdOpt.vars;
    [xVectScaled, origVars, ~, ~] = varSet.getTotalScaledXVector();
    setappdata(hObject,'origScaledXVect',xVectScaled);
    setappdata(hObject,'origVars',origVars);

    populateGUI(handles, lvdData, 1); %just close and throw an error if no variables enabled in LVD GUI

    hVarUpdatedListenerAdded = addlistener(varSet,'VarsListUpdatedAddedVar',@(src,evtData) varListUpdatedEventCallback(src,evtData, handles, lvdData));
    setappdata(hObject,'hVarUpdatedListenerAdded',hVarUpdatedListenerAdded);

    hVarUpdatedListenerRemoved = addlistener(varSet,'VarsListUpdatedRemovedVar',@(src,evtData) varListUpdatedEventCallback(src,evtData, handles, lvdData));
    setappdata(hObject,'hVarUpdatedListenerRemoved',hVarUpdatedListenerRemoved);

    jCombobox = findjobj(handles.variablesCombo);
    jCombobox.PopupMenuWillBecomeVisibleCallback = @(src,evtData) varListUpdatedEventCallback(src,evtData, handles, lvdData);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, lvdData, value)
    lvdOpt = lvdData.optimizer;
    varSet = lvdOpt.vars;
    varSet.sortVarsByEvtNum();
    [~, ~, varNameStrs, xUnscaled] = varSet.getTotalScaledXVector();
    [~, ~, lwrBndsUnscaled, uprBndsUnscaled] = varSet.getTotalScaledBndsVector();

    if(xUnscaled(value) < lwrBndsUnscaled(value))
        xUnscaled(value) = lwrBndsUnscaled(value);
    elseif(xUnscaled(value) > uprBndsUnscaled(value))
        xUnscaled(value) = uprBndsUnscaled(value);
    end

    if(lwrBndsUnscaled(value) == uprBndsUnscaled(value))
        xUnscaled(value) = lwrBndsUnscaled(value);

        lwrBndsUnscaled(value) = lwrBndsUnscaled(value) - 1E-12;
        uprBndsUnscaled(value) = uprBndsUnscaled(value) + 1E-12;
    end

    handles.variablesCombo.String = varNameStrs;
    handles.variablesCombo.Value = value;
    handles.varValueText.String = fullAccNum2Str(xUnscaled(value));
    handles.varLowerBndLabel.String = fullAccNum2Str(lwrBndsUnscaled(value));
    handles.varUpperBndLabel.String = fullAccNum2Str(uprBndsUnscaled(value));
    handles.varValueSlider.Value = scaleXToNeg1And1(xUnscaled(value), lwrBndsUnscaled(value), uprBndsUnscaled(value));

function xScaled = scaleXToNeg1And1(xi, lbi, ubi)
    bndDiff = ubi - lbi;
    bndCenter = (lbi + ubi)/2;
    xScaled = (xi - bndCenter)/(bndDiff/2);

function xUnscaled = unscaleXFromNeg1And(xSi, lbi, ubi)
    bndDiff = ubi - lbi;
    bndCenter = (lbi + ubi)/2;

    if(bndDiff > 1E-10)
        xUnscaled = xSi * (bndDiff/2) + bndCenter;
    end

function varListUpdatedEventCallback(src,evtData, handles, lvdData)
    curStrs = handles.variablesCombo.String;

    if(~isempty(curStrs))
        curValue = handles.variablesCombo.Value;
        if(curValue < 1 || curValue > length(curStrs))
            curValue = 1;
        end
        curStr = curStrs{curValue};

        populateGUI(handles, lvdData, curValue);

        newValue = findValueFromComboBox(curStr, handles.variablesCombo);
        if(not(isempty(newValue)))
            handles.variablesCombo.Value = newValue;
        end
    end

% --- Outputs from this function are returned to the command line.
function varargout = lvd_adjustOptVarGUI_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
        varargout{1} = true;
        close(handles.lvd_adjustOptVarGUI);
    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_adjustOptVarGUI);

% --- 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)
    lvdData = getappdata(handles.lvd_adjustOptVarGUI,'lvdData');
    lvdOpt = lvdData.optimizer;
    varSet = lvdOpt.vars;

    origScaledXVect = getappdata(handles.lvd_adjustOptVarGUI,'origScaledXVect');
    origVars = getappdata(handles.lvd_adjustOptVarGUI,'origVars');

    [~, curVars, ~, ~] = varSet.getTotalScaledXVector();
    for(i=1:length(curVars))
        ind = find(curVars(i) == origVars);

        if(not(isempty(ind)))
            curVars(i).updateObjWithScaledVarValue(origScaledXVect(ind));
        end
    end

%     varSet.updateObjsWithScaledVarValues(origScaledXVect);

    close(handles.lvd_adjustOptVarGUI);

% --- Executes on selection change in variablesCombo.
function variablesCombo_Callback(hObject, eventdata, handles)
% hObject    handle to variablesCombo (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 variablesCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from variablesCombo
    lvdData = getappdata(handles.lvd_adjustOptVarGUI,'lvdData');
    value = handles.variablesCombo.Value;
    populateGUI(handles, lvdData, value);

% --- Executes during object creation, after setting all properties.
function variablesCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to variablesCombo (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 slider movement.
function varValueSlider_Callback(hObject, eventdata, handles)
% hObject    handle to varValueSlider (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
    processUserChangeToVar(handles);
    figure(handles.lvd_adjustOptVarGUI); %put this figure back on top

function processUserChangeToVar(handles)
    propScriptFcn = getappdata(handles.lvd_adjustOptVarGUI,'propScriptFcn');
    procDataFcn = getappdata(handles.lvd_adjustOptVarGUI,'procDataFcn');
    lvdData = getappdata(handles.lvd_adjustOptVarGUI,'lvdData');
    lvdOpt = lvdData.optimizer;
    varSet = lvdOpt.vars;
    [xVectScaled, ~, ~, ~] = varSet.getTotalScaledXVector();
    [~, ~, lwrBndsUnscaled, uprBndsUnscaled] = varSet.getTotalScaledBndsVector();

    value = handles.variablesCombo.Value;
    xScaled = handles.varValueSlider.Value;
    xUnscaled = unscaleXFromNeg1And(xScaled, lwrBndsUnscaled(value), uprBndsUnscaled(value));

    xVectScaledUpdated = xVectScaled;
    xVectScaledUpdated(value) = xScaled;

    handles.varValueText.String = fullAccNum2Str(xUnscaled);

    varSet.updateObjsWithScaledVarValues(xVectScaledUpdated);
    propScriptFcn();
    procDataFcn();

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

% --- Executes on key press with focus on lvd_adjustOptVarGUI or any of its controls.
function lvd_adjustOptVarGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_adjustOptVarGUI (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'
            cancelButton_Callback(handles.cancelButton, [], handles);
    end

function varValueText_Callback(hObject, eventdata, handles)
% hObject    handle to varValueText (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 varValueText as text
%        str2double(get(hObject,'String')) returns contents of varValueText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    lvdData = getappdata(handles.lvd_adjustOptVarGUI,'lvdData');
    lvdOpt = lvdData.optimizer;
    varSet = lvdOpt.vars;
    [~, ~, ~, xUnscaled] = varSet.getTotalScaledXVector();
    [~, ~, lwrBndsUnscaled, uprBndsUnscaled] = varSet.getTotalScaledBndsVector();

    varInd = handles.variablesCombo.Value;

    errMsg = {};
    value = str2double(get(handles.varValueText,'String'));
    enteredStr = get(handles.varValueText,'String');
    numberName = 'Epoch (UT)';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        lb = lwrBndsUnscaled(varInd);
        ub = uprBndsUnscaled(varInd);

        if(value < lb)
            handles.varValueText.String = fullAccNum2Str(lb);
            handles.varValueSlider.Value = -1;

        elseif(value > ub)
            handles.varValueText.String = fullAccNum2Str(ub);
            handles.varValueSlider.Value = 1;

        else
            handles.varValueSlider.Value = scaleXToNeg1And1(value, lb, ub);

        end

        processUserChangeToVar(handles);
    else
        handles.varValueText.String = fullAccNum2Str(xUnscaled(varInd));
    end

% --- Executes during object deletion, before destroying properties.
function lvd_adjustOptVarGUI_DeleteFcn(hObject, eventdata, handles)
% hObject    handle to lvd_adjustOptVarGUI (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    hVarUpdatedListenerAdded = getappdata(hObject,'hVarUpdatedListenerAdded');
    delete(hVarUpdatedListenerAdded);

    hVarUpdatedListenerRemoved = getappdata(hObject,'hVarUpdatedListenerRemoved');
    delete(hVarUpdatedListenerRemoved);


%% This function is used to get the endeffector force of the KUKA iiwa 7 R 800.
% function [ f ] = getEEF_Force( t )
% This function is used to get the endeffector force of the KUKA iiwa 7 R 800.
% t: is the TCP/IP connection
% f: is 1x3 cell array,  X,Y and Z components of the force acting on the endeffector
% Copy right, Mohammad SAFEEA, 3rd of May 2017


function db_set_template( iSubject, sTemplate, isInteractive )
% DB_SET_TEMPLATE: Copy all the files from an anatomy template in any anatomy directory.
%
% USAGE:  db_set_template( iSubject, sTemplate, isInteractive=1 );
%         db_set_template( iSubject, TemplateName, isInteractive=1);
%
% INPUT:
%    - iSubject      : Subject indice in protocol definition (default anatomy: iSubject=0)
%    - sTemplate     : Struct including the path to the anatomy template (zip file, folder or URL)
%    - TemplateName  : String identifying the name of an anatomy template, as returned by bst_get('AnatomyDefaults')
%    - isInteractive : If 1, asks for confirmation and open the MRI Viewer for fiducials verification (default is 1)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2008-2022

%% ===== TARGET SUBJECT =====
% Parse inputs
if (nargin < 3) || isempty(isInteractive)
    isInteractive = 1;
end
% Get default subject directory
sSubject = bst_get('Subject', iSubject);
ProtocolInfo = bst_get('ProtocolInfo');
targetDir = bst_fullfile(ProtocolInfo.SUBJECTS, bst_fileparts(sSubject.FileName));
% Ask for confirmation if existing anatomy
if isInteractive && (~isempty(sSubject.Anatomy) || ~isempty(sSubject.Surface))
    if ~java_dialog('confirm', ['Warning: There is already an anatomy defined for this subject.' 10 10 ...
        'Are you sure you want to delete the previous MRI and surfaces ?' 10 10], 'Use default anatomy');
        return;
    end
end

%% ===== GET TEMPLATE =====
% If template selection is a string: get the template structure
if ischar(sTemplate)
    TemplateName = sTemplate;
    sTemplate = bst_get('AnatomyDefaults', TemplateName);
    if isempty(sTemplate)
        error(['Invalid template name: ' TemplateName]);
    end
end
% Directory: just copy from it
if isdir(sTemplate.FilePath)
    templateDir = sTemplate.FilePath;
    isDeleteDir = 0;
else
    % Create to temporary folder
    templateDir = bst_fullfile(bst_get('BrainstormTmpDir'), sTemplate.Name);
    if file_exist(templateDir)
        file_delete(templateDir, 1, 3);
    end
    mkdir(templateDir);
    % URL: Download zip file
    if ~isempty(strfind(sTemplate.FilePath, 'http://')) || ~isempty(strfind(sTemplate.FilePath, 'https://')) || ~isempty(strfind(sTemplate.FilePath, 'ftp://'))
        % Output file
        ZipFile = bst_fullfile(bst_get('UserDefaultsDir'), 'anatomy', [sTemplate.Name '.zip']);
        % Download file
        errMsg = gui_brainstorm('DownloadFile', sTemplate.FilePath, ZipFile, 'Download template');
        % Error message
        if ~isempty(errMsg)
            if isInteractive
                bst_error(['Impossible to download template:' 10 errMsg], 'Download error', 0);
                return
            else
                error(['Impossible to download template: ' errMsg]);
            end
        end
    elseif ~isempty(strfind(sTemplate.FilePath, '.zip'))
        ZipFile = sTemplate.FilePath;
    else
        error('Invalid template.');
    end
    % Progress bar
    bst_progress('start', 'Import template', 'Unzipping file...');
    % URL: Download zip file
    try
        unzip(ZipFile, templateDir);
    catch
        errMsg = ['Could not unzip anatomy template: ' 10 10 lasterr];
        disp(['BST> Error: ' errMsg]);
        if isInteractive
            if java_dialog('confirm', [errMsg 10 10 'Delete invalid template file?' 10 10], 'Use default anatomy');
                file_delete(ZipFile, 1);
            end
        end
        bst_progress('stop');
        return;
    end
    isDeleteDir = 1;
end

%% ===== COPY TEMPLATE =====
% Unload everything
bst_memory('UnloadAll', 'Forced');
% Check template directory
if isempty(templateDir) || ~isdir(templateDir) || isempty(dir(bst_fullfile(templateDir, 'brainstormsubject*.mat')))
    error(['Invalid template directory : "' strrep(templateDir, '\', '\\') '".']);
end
% Progress bar
bst_progress('start', 'Import template', 'Copying template files...');
% Remove all the files of the previous default anatomy
file_delete(bst_fullfile(targetDir, '*.bin'), 1);
file_delete(bst_fullfile(targetDir, '*.bak'), 1);
file_delete(bst_fullfile(targetDir, '*_openmeeg.mat'), 1);
dirFiles = dir(bst_fullfile(targetDir, '*.mat'));
for i = 1:length(dirFiles)
    fileType = file_gettype(dirFiles(i).name);
    if ~strcmpi(fileType, 'brainstormsubject')
        file_delete(bst_fullfile(targetDir, dirFiles(i).name), 1);
    end
end
% Copy all files of the template in target directory
dirFiles = dir(bst_fullfile(templateDir, '*.mat'));
for i = 1:length(dirFiles)
    fileType = file_gettype(dirFiles(i).name);
    % Subject description: get the default surfaces and MRIs
    switch (fileType)
        % Subject definition
        case 'brainstormsubject'
            % Load template subject mat
            tempSubjMat = load(bst_fullfile(templateDir, dirFiles(i).name));
            % Load target subject mat
            targetSubjFile = file_fullpath(sSubject.FileName);
            targetSubjMat = load(targetSubjFile);
            % Copy default filenames
            for f = {'Anatomy', 'Scalp', 'Cortex', 'InnerSkull', 'OuterSkull', 'FEM'}
                if isfield(tempSubjMat, f{1}) && ~isempty(tempSubjMat.(f{1}))
                    [tmp, fBase, fExt] = bst_fileparts(tempSubjMat.(f{1}));
                    targetSubjMat.(f{1}) = [bst_fileparts(sSubject.FileName), '/', [fBase, fExt]];
                end
            end
            % Save updated subject mat
            bst_save(targetSubjFile, targetSubjMat, 'v7');
        % Anatomy file
        case {'subjectimage', 'tess', 'cortex', 'scalp', 'outerskull', 'innerskull', 'fibers', 'fem'}
            file_copy(bst_fullfile(templateDir, dirFiles(i).name), targetDir);
        % Channel file
        case 'channel'
            % Get user EEG template folder
            eegDefDir = bst_fullfile(bst_get('UserDefaultsDir'), 'eeg');
            eegTargetDir = bst_fullfile(eegDefDir, sTemplate.Name);
            % Create folder if needed
            if ~isdir(eegTargetDir)
                mkdir(eegTargetDir);
            end
            % Copy to template channel file folder
            if isdir(eegTargetDir)
                file_copy(bst_fullfile(templateDir, dirFiles(i).name), eegTargetDir);
                disp(['BST> Installed new EEG template: ' bst_fullfile(eegTargetDir, dirFiles(i).name)]);
            end
    end
end

% Reload default subject
db_reload_subjects(iSubject);
% Get subject again
sSubject = bst_get('Subject', iSubject);
% Close process bar
bst_progress('stop');
% Delete unzipped template folder
if isDeleteDir
    file_delete(templateDir, 1, 3);
end

% %% ===== CHECK FIDUCIALS =====
% if isInteractive && ~isempty(sSubject.Anatomy)
%     % DEFAULT ANAT: Check if the positions of the fiducials have been validated
%     figure_mri('FiducialsValidation', sSubject.Anatomy(1).FileName);
% end


function [ wav_files ] = find_dat( path )
%FIND_WAV, find all wav file recursively
wav_files = [];
if(isdir(path) == 0)

    return;
end
path_files = dir(path);
fileNum = length(path_files);
for k= 3:fileNum
    file = [path,'\', path_files(k).name];
    if (path_files(k).isdir == 1)
        ret = find_wav(file);
        if(isempty(ret) ~= 1)
            if(isempty(wav_files))
                wav_files = char(ret);
            else
                wav_files = char(wav_files, ret);
            end
        end
    elseif strfind(path_files(k).name, '.dat')
        if(isempty(wav_files))
            wav_files = char(file);
        else
            wav_files = char(wav_files, file);
        end
    end
end
end


% script for computing window features

% set up path
if ispc,
  JCtrax_path = 'E:\Code\JCtrax';
  FlyBowlAnalysis_path = 'E:\Code\FlyBowlAnalysis';
  rootdatadir = 'E:\Code\Jdetect\larva\fly_data\TrainingData';
  settingsdir = 'E:\Code\FlyBowlAnalysis\settings';
else
  JCtrax_path = '/groups/branson/home/bransonk/tracking/code/JCtrax';
  FlyBowlAnalysis_path = '/groups/branson/bransonlab/projects/olympiad/FlyBowlAnalysis';
  settingsdir = '/groups/branson/bransonlab/projects/olympiad/FlyBowlAnalysis/settings';
end
addpath(fullfile(JCtrax_path,'misc'));
addpath(fullfile(JCtrax_path,'filehandling'));
addpath(FlyBowlAnalysis_path);

%% load test data

labelmatnames = {
  'perframe_labeledsharpturns_movie01_pBDPGAL4U_TrpA_Rig1Plate10BowlA_20110202T105734_fly1_11.mat'
  'perframe_labeledsharpturns_movie01_pBDPGAL4U_TrpA_Rig1Plate10BowlA_20110202T105734_fly2_08.mat'
  'perframe_labeledsharpturns_movie02_pBDPGAL4U_TrpA_Rig2Plate14BowlA_20110202T110111_fly1_01.mat'
  'perframe_labeledsharpturns_movie02_pBDPGAL4U_TrpA_Rig2Plate14BowlA_20110202T110111_fly2_15.mat'
  'perframe_labeledsharpturns_movie03_pBDPGAL4U_TrpA_Rig2Plate14BowlB_20110202T110116_fly1_12.mat'
  'perframe_labeledsharpturns_movie03_pBDPGAL4U_TrpA_Rig2Plate14BowlB_20110202T110116_fly2_03.mat'
  'perframe_labeledsharpturns_movie07_GMR_14G03_AE_01_TrpA_Rig2Plate14BowlA_20110202T102516_fly2_17.mat'
  'perframe_labeledsharpturns_movie08_GMR_14H07_AE_01_TrpA_Rig1Plate10BowlB_20110202T084231_fly1_09.mat'
  'perframe_labeledsharpturns_movie09_GMR_16E02_AE_01_TrpA_Rig1Plate10BowlC_20110202T140143_fly1_09.mat'
  };
nexps = numel(labelmatnames);

paramsfilename = 'SharpturnPerFrameParams_AllParams.xml';

%% set parameters
[params,cellparams] = ReadPerFrameParams(paramsfilename);
fns = fieldnames(cellparams);

%% do it

X = cell(1,nexps);
Y = cell(1,nexps);
feature_names = {};

for expi = 1:nexps,

  labelfilename = fullfile(rootdatadir,labelmatnames{expi});
  fprintf('Computing window features for file %s...\n',labelmatnames{expi});
  if ~exist(labelfilename,'file'),
    warning('File %s does not exist, skipping',labelfilename);
    continue;
  end
  labeldata = load(labelfilename);
  for i = 1:numel(fns),
    fn = fns{i};
    fprintf('Per-frame feature %s...\n',fn);
    j = find(strcmp(labeldata.perframefns,fn));
    if isempty(j),
      error('Unknown perframe field %s',fn);
    end
    [x_curr,feature_names_curr] = ...
      ComputeWindowFeatures(labeldata.perframedata{j},cellparams.(fn){:});
    if expi == 1,
      feature_names = [feature_names,cellfun(@(s) [{fn},s],feature_names_curr,'UniformOutput',false)];
    end

    % crop out labeled part of video
    x_curr = x_curr(:,labeldata.trk_labelstart:labeldata.trk_labelend-1);

    % store
    X{expi} = [X{expi};x_curr];
  end

  % store labels
  Y{expi} = labeldata.label;

end
nfeatures = numel(feature_names);

%% display names for stats

statnames = cell(1,nfeatures);
for i = 1:nfeatures,
  fn = '';
  for j = 1:numel(feature_names{i}),
    if j == 1,
    elseif mod(j,2) == 0,
      fn = [fn,', '];
    else
      fn = [fn,'='];
    end
    if ischar(feature_names{i}{j}),
      fn = [fn,feature_names{i}{j}];
    else
      fn = [fn,num2str(feature_names{i}{j})];
    end
  end
  statnames{i} = fn;
end

%% combine stats to plot everything

X_combine = X{1};
Y_combine = Y{1};
expi_combine = ones(1,size(X{1},2));
for expi = 2:nexps,
  if isempty(X{expi}),
    continue;
  end
  X_combine = [X_combine,nan([nfeatures,1]),X{expi}];
  Y_combine = [Y_combine,nan,Y{expi}];
  expi_combine = [expi_combine,nan,expi+zeros(1,size(X{expi},2))];
end
N = numel(Y_combine);

%% interactive figure in which we can plot some of the window features

handles = struct;
handles.fig = 1;
axespos = [.05,.1,.7,.85];
border = .01;
listpos = [axespos(1)+axespos(3)+border,...
  axespos(2),...
  1-(axespos(1)+axespos(3)+2*border),...
  axespos(4)];
figure(handles.fig);
clf;
handles.ax = axes('Parent',handles.fig,'Units','Normalized','Position',axespos);
handles.listbox = uicontrol(handles.fig,'Style','listbox',...
  'Units','normalized','Position',listpos,...
  'String',statnames,...
  'Max',nfeatures,'Min',0,'Value',[]);
xlim = [0,N+1];
ylim = [min(X_combine(:)),max(X_combine(:))];
set(handles.fig,'ToolBar','figure');
set(handles.ax,'XLim',xlim,'YLim',ylim);
hold(handles.ax,'on');
[i0,i1] = get_interval_ends(Y_combine==1);
i1 = i1 - 1;
for i = 1:numel(i0),
  patch([i0(i)-.5,i1(i)+.5,i1(i)+.5,i0(i)-.5,i0(i)-.5],ylim([1,1,2,2,1]),...
    [1,.7,.7],'EdgeColor','none');
end
[i0,i1] = get_interval_ends(isnan(Y_combine));
i1 = i1 - 1;
for i = 1:numel(i0),
  patch([i0(i)-.5,i1(i)+.5,i1(i)+.5,i0(i)-.5,i0(i)-.5],ylim([1,1,2,2,1]),...
    [.5,.5,.5],'EdgeColor','none');
end
handles.title = title('');
handles.data = [];
setappdata(handles.listbox,'handles',handles);
setappdata(handles.listbox,'x',X_combine);
set(handles.listbox,'Callback',@DebugComputeWindowFeatures_ListBoxCallback);

%% interactive figure in which we can histogram some of the window features

nbins = 100;
edges = nan(nfeatures,nbins+1);
centers = nan(nfeatures,nbins);
frac = nan(nfeatures,nbins,2);
for i = 1:nfeatures,
  edges(i,:) = linspace(min(X_combine(i,:)),max(X_combine(i,:)),nbins+1);
  centers(i,:) = (edges(i,1:end-1)+edges(i,2:end))/2;
  edges(i,end) = inf;
  for j = 1:2,
    counts = histc(X_combine(i,Y_combine==j-1),edges(i,:));
    frac(i,:,j) = counts(1:end-1) / sum(counts(1:end-1));
  end
end

handles = struct;
handles.fig = 2;
axespos = [.05,.1,.7,.85];
border = .01;
listpos = [axespos(1)+axespos(3)+border,...
  axespos(2),...
  1-(axespos(1)+axespos(3)+2*border),...
  axespos(4)];
figure(handles.fig);
clf;
handles.ax = axes('Parent',handles.fig,'Units','Normalized','Position',axespos);
handles.listbox = uicontrol(handles.fig,'Style','listbox',...
  'Units','normalized','Position',listpos,...
  'String',statnames,...
  'Max',1,'Min',0,'Value',1);
set(handles.fig,'ToolBar','figure');
hold(handles.ax,'on');
handles.data = [];
setappdata(handles.listbox,'handles',handles);
setappdata(handles.listbox,'frac',frac);
setappdata(handles.listbox,'centers',centers);
setappdata(handles.listbox,'legends',{'none','sharpturn'});
DebugComputeWindowFeatures_ListBoxCallback_Hist(handles.listbox);
set(handles.listbox,'Callback',@DebugComputeWindowFeatures_ListBoxCallback_Hist);


function data_obj = import_onsets(data_obj, design_file)
% Import onsets from a csv or Excel file and attach them to the fmri_glm_design_matrix object

            % DesginmatrixTable INPUT
            % TRY readtable() -- may be more flexible than xlsread.
            xlsread(DesginmatrixTable)

end


% FIDPATH gets the path of Varian FID data

% Note that the filename one chooses in the path doesn't really
% matter since the Varian *.fid directory contains 4 files,
% and they are always named "fid" (FID data), "procpar" (MR
% parameters), "log" (acquisition on/off), and text (PSD name).

function fpath = fidpath(fpath, checkfid, title)

if nargin < 3
   title = 'Select Varian FID path';
   if nargin < 2
      checkfid = false;
      if nargin < 1
         fpath = cd;
      end
   end
end

if isempty(fpath)
   fpath = cd;
end
if isempty(checkfid)
   checkfid = false;
end
if isempty(title)
   title = 'Select Varian FID path';
end

% Make sure fpath ends with "/"
if (fpath(end) ~= '/')
   fpath = [fpath, '/'];
end

if fileexist(fpath, checkfid)
   return
end

% Check if the user forgot to add .fid extension
fpathnew = [fpath(1:end-1) '.fid/'];
if fileexist(fpathnew, checkfid)
   fpath = fpathnew;
   return
end

% Check if the user forgot to add .par extension
fpathnew = [fpath(1:end-1) '.par/'];
if fileexist(fpathnew, false)
   fpath = fpathnew;
   return
end

curdir = cd;
if exist(fpath, 'dir')
   cd(fpath);
end

% Get FID file path/name
contflag = 1;
while (contflag == 1),
    [fname, fpath] = uigetfile('*', title);
    % Make sure "fid" and "procpar" files exist
    if isequal(fpath, 0) || isequal(fname, 0)
        error('No directory selected.')
    elseif ~fileexist(fpath, checkfid)
        disp('GETPATH unable to locate fid and/or procpar file in selected directory. Try again.')
    else
        contflag = 0;
    end
end

cd(curdir);
drawnow;
return

% LOCAL FUNCTION
function res = fileexist(fpath, checkfid);

if checkfid
   if (exist([fpath 'fid']) ~= 2)
      res = 0;
      return
   end
end

if exist([fpath 'procpar']) == 2
   res = 1;
else
   res = 0;
end

return


function slshowtext(T)
%SLSHOWTEXT Displays the text
%
% $ Syntax $
%   - slshowtext(T)
%
% $ Description $
%   - slshowtext(T) shows the text in cell array of lines.
%
% $ History $
%   - Created by Dahua Lin, on Aug 9th, 2006
%

if ~isempty(T)
    nlines = length(T);
    for i = 1 : nlines
        curline = T{i};
        if isempty(curline);
            disp(' ');
        else
            disp(curline);
        end
    end
end


function y = getFieldSafe(data,fld)
% y = getFieldSafe(data,fld)
% mode: optional, either 'safe' or 'safest' (default).
% y: col cell

if isempty(data)
    y = cell(0,1);
else
    y = {data.(fld)}';
    assert(isequal(size(y),[numel(data) 1]));
end


function mask = PTKGetLobeROI(lobe_mask, context, reporting)
    % PTKGetLobeROI. Extracts a region of interest for one of the lobes.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    mask = lobe_mask.BlankCopy;

    if context == PTKContext.LeftUpperLobe
        colormap_index = PTKColormapLabels.LeftUpperLobe;
    elseif context == PTKContext.LeftLowerLobe
        colormap_index = PTKColormapLabels.LeftLowerLobe;
    elseif  context == PTKContext.RightUpperLobe
        colormap_index = PTKColormapLabels.RightUpperLobe;
    elseif  context == PTKContext.RightMiddleLobe
        colormap_index = PTKColormapLabels.RightMiddleLobe;
    elseif  context == PTKContext.RightLowerLobe
        colormap_index = PTKColormapLabels.RightLowerLobe;
    else
        reporting.Error('PTKGetLobeROI:UnknownContext', ['The context ' char(context) ' is unknown.']);
    end
    mask.ChangeRawImage(lobe_mask.RawImage == colormap_index);
    mask.CropToFitWithBorder(5);
end