function tc = tc_addMenus(tc,hfig);
% tc = tc_addMenus(tc,[hfig]): add menus to time course UI figure.
%
% tc: the analysis struct used by the UI.
%
% hfig: handle to the figure (default is gcf).
%
% 07/04 ras.
% 09/05 ras: made each top-level menu a sub-function, to
% make 'em easier to get at.
if ~exist('hfig')   hfig = gcf;     end

tc.ui.fig = hfig;

% turn off standard menus for now:
set(hfig,'Menubar','none');

% add each top-level menu individually
tc.ui = tc_plotMenu(tc, tc.ui);
tc.ui = tc_viewMenu(tc, tc.ui);
tc.ui = tc_analMenu(tc, tc.ui);
tc.ui = tc_settingsMenu(tc, tc.ui);
tc.ui = tc_condMenu(tc, tc.ui);
tc.ui = tc_exportMenu(tc, tc.ui);
tc.ui = tc_helpMenu(tc, tc.ui);

% add standard MATLAB menus
tc.ui.spacerMenu = uimenu('Label',' ');
% eval(get(tc.ui.figMenuToggle,'Callback'));

return
% /---------------------------------------------------------------/ %

% /---------------------------------------------------------------/ %
function h = tc_plotMenu(tc,h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add menus (1): Plotting options for time course
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h.plotMenu = uimenu('ForegroundColor',[0 0 0],'Label','Plot','Separator','on');

% callback for all plotting options:
%   TMP = get(gcf, 'UserData');
%   TMP_H = get(gcbo, 'UserData');
%   set(TMP_H, 'Checked', 'off');
%   set(gcbo, 'Checked', 'on');
%   TMP.plotType = find(TMP_H==gcbo);
%   set(gcf, 'UserData', TMP);
%   timeCourseUI;
%   clear TMP_H TMP;
cb=['TMP_H = get(gcbo, ''UserData''); ' ...
    'TMP = get(gcf, ''UserData''); ' ...
    'set(TMP_H, ''Checked'', ''off''); ' ...
    'set(gcbo, ''Checked'', ''on''); ' ...
    'TMP.plotType = find(TMP_H==gcbo); ' ...
    'set(gcf, ''UserData'', TMP); ' ...
    'timeCourseUI; clear TMP_H TMP; ' ];

h.plotWholeTc = uimenu(h.plotMenu,'Label','Plot Whole Time Course','Separator','off',...
    'Accelerator','K','Callback',cb);

h.sparklineWholeTc = uimenu(h.plotMenu, 'Label', 'Plot Whole Time Course (sparkline)',...
                        'Callback',cb);

h.plotMeanTrials = uimenu(h.plotMenu,'Label','Plot Mean Time Course','Separator','off',...
    'Checked','off','Accelerator','M','Callback',cb);

h.meanSubplots = uimenu(h.plotMenu,'Label','Mean Time Course Subplots','Separator','off',...
    'Checked','off','Accelerator','B','Callback',cb);

h.plotAllTrials = uimenu(h.plotMenu,'Label','Plot All Trials','Separator','off',...
    'Accelerator','I','Callback',cb);

h.plotRelAmps = uimenu(h.plotMenu,'Label','Plot Relative Amplitudes','Separator','on',...
    'Accelerator','J','Callback',cb);

h.plotMeanAmps = uimenu(h.plotMenu,'Label','Plot Mean Amplitudes','Separator','off',...
    'Accelerator','U','Callback',cb);

h.plotSummary = uimenu(h.plotMenu,'Label','Mean Time Course Plus Amplitudes','Separator','on',...
    'Checked','on','Accelerator','D','Callback',cb);

h.plotFFT = uimenu(h.plotMenu,'Label','FFT of mean tSeries','Separator','on',...
    'Checked','off','Accelerator','F','Callback',cb);

h.plotGlm = uimenu(h.plotMenu,'Label','Visualize GLM Results','Separator','on',...
    'Checked','off','Accelerator','G','Callback',cb);

h.plotCorAnal = uimenu(h.plotMenu,'Label','Visualize Cor Anal','Separator','off',...
    'Checked','off','Accelerator','T','Callback',cb);

% this code allows the UI to exclusively check the selected
% plot option, and deselect the others:
handlesArray = [h.plotWholeTc h.plotAllTrials h.plotMeanTrials ...
                h.plotRelAmps h.plotMeanAmps h.meanSubplots ...
                h.plotSummary h.plotFFT h.plotGlm h.plotCorAnal ...
                h.sparklineWholeTc];
set(h.plotWholeTc,'UserData',handlesArray);
set(h.plotAllTrials,'UserData',handlesArray);
set(h.plotMeanTrials,'UserData',handlesArray);
set(h.plotRelAmps,'UserData',handlesArray);
set(h.plotMeanAmps,'UserData',handlesArray);
set(h.meanSubplots,'UserData',handlesArray);
set(h.plotSummary,'UserData',handlesArray);
set(h.plotFFT,'UserData',handlesArray);
set(h.plotGlm,'UserData',handlesArray);
set(h.plotCorAnal,'UserData',handlesArray);
set(h.sparklineWholeTc,'UserData',handlesArray);

return
% /---------------------------------------------------------------/ %

% /---------------------------------------------------------------/ %
function h = tc_viewMenu(tc,h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add menus (2): View options for time course
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h.viewMenu = uimenu('ForegroundColor',[0 0 0],'Label','View','Separator','on');

% spawn new UI callback:
% tc_openFig(get(gcf,'UserData'));
h.newTCUI = uimenu(h.viewMenu,'Label','New UI Window','Separator','off',...
    'Callback',' tc_openFig(get(gcf,''UserData'')); timeCourseUI;');

% view/edit parfiles callback:
% tc = get(gcf, 'UserData');
% for p = tc.trials.parfiles, edit(p{1}); end
cb = 'tc = get(gcf, ''UserData''); ';
cb = [cb 'for p = tc.trials.parfiles, edit(p{1}); end '];
h.editParfiles = uimenu(h.viewMenu, 'Label', 'View/Edit Parfiles', ...
    'Separator', 'on', 'Callback', cb);

% mark individual trials in All Trials plot:
%   umtoggle(gcbo);
%   TMP = get(gcf,'UserData');
%   TMP.params.markEachTrial = isequal(get(gcbo,'Checked'),'on');
%   set(gcf,'UserData',TMP);
%   timeCourseUI;
%   clear TMP
cb = ['umtoggle(gcbo); '...
       'TMP = get(gcf,''UserData''); '...
       'TMP.params.markEachTrial = isequal(get(gcbo,''Checked''),''on''); '...
       'set(gcf, ''UserData'', TMP); '...
       'timeCourseUI; clear TMP;'];
h.markEachTrial = uimenu(h.viewMenu,'Label','Color Single Trials (All Trials Plot)', ....
                'Separator','on', 'Checked', 'on', 'Callback', cb);

% show grid:
%   umtoggle(gcbo);
%   TMP = get(gcf,'UserData');
%   TMP.params.grid = isequal(get(gcbo,'Checked'),'on');
%   set(gcf,'UserData',TMP);
%   timeCourseUI;
%   clear TMP
cb = ['umtoggle(gcbo); '...
       'TMP = get(gcf,''UserData''); '...
       'TMP.params.grid = isequal(get(gcbo,''Checked''),''on''); '...
       'set(gcf, ''UserData'', TMP); '...
       'timeCourseUI; clear TMP;'];
h.grid = uimenu(h.viewMenu, 'Label', 'Grid',  'Separator', 'off', ...
                'Checked', 'off', 'Callback', cb);

% show peak and baseline periods callback:
%   umtoggle(gcbo);
%   TMP = get(gcf,'UserData');
%   TMP.params.showPkBsl = isequal(get(gcbo,'Checked'),'on');
%   set(gcf,'UserData',TMP);
%   timeCourseUI;
%   clear TMP
cb = ['umtoggle(gcbo); '...
       'TMP = get(gcf,''UserData''); '...
       'TMP.params.showPkBsl = isequal(get(gcbo,''Checked''),''on''); '...
       'set(gcf, ''UserData'', TMP); '...
       'timeCourseUI; clear TMP;'];
h.showPkBsl = uimenu(h.viewMenu,'Label','Show Peak/Baseline Periods', ....
                'Separator','off', 'Checked', 'on', 'Callback', cb);

% legend callback:
% TMP = get(gcf, 'UserData');
% TMP.params.legend = mrvPanelToggle(TMP.ui.legend, gcbo);
% set(gcf, 'UserData', TMP);
% clear TMP
cb = ['TMP = get(gcf, ''UserData''); ' ...
      'TMP.params.legend = mrvPanelToggle(TMP.ui.legend, gcbo); ' ...
      'set(gcf, ''UserData'', TMP); ' ...
      'clear TMP; '];
h.showLegend = uimenu(h.viewMenu, 'Label', 'Show Legend', ...
    'Separator', 'off', 'Checked', 'on', 'Accelerator', 'L', ...
    'Callback', cb);

h.figMenuToggle = addFigMenuToggle(h.viewMenu);

return
% /---------------------------------------------------------------/ %

% /---------------------------------------------------------------/ %
function h = tc_analMenu(tc,h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add menus (3): Analysis options for time course
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h.analMenu = uimenu('ForegroundColor',[0 0 0],'Label','Analysis','Separator','on');

% calc SNR (peak v bsl)
cb = 'tc = get(gcf,''UserData''); ';
cb = [cb 'title(sprintf(''SNR Peak Vs Baseline: %2.2f (%2.2f dB)'',tc.SNR,tc.SNRdb),''FontSize'',14);'];
h.calcSNR = uimenu(h.analMenu,'Label','Calculate SNR (peak vs bsl)','Separator','off','Callback',cb);

% blur time course
cb = 'tc_blurTimeCourse;';
h.blurTc = uimenu(h.analMenu,'Label','Blur Time Course','Separator','off','Callback',cb);

% detrend time course
cb = 'tc_detrendTimeCourse;';
h.blurTc = uimenu(h.analMenu,'Label','Detrend Time Course','Separator','off','Callback',cb);

% remove outlier data points
cb = 'tc_removeOutliers;';
h.blurTc = uimenu(h.analMenu,'Label','Remove Outlier Time Points',...
    'Separator','on','Callback',cb);

% apply corAnal
cb = 'tc_applyCorAnal; tc_visualizeCorAnal; ';
h.applyCorAnal = uimenu(h.analMenu, 'Label', 'Apply Cor Anal',...
    'Separator', 'on', 'Callback', cb);

% apply GLM
cb = 'tc_applyGlm; tc_visualizeGlm; ';
h.applyGLM = uimenu(h.analMenu, 'Label', 'Apply GLM',...
    'Separator', 'off', 'Callback', cb);

% Apply statistical contrast callback:
% tc_contrast;
h.contrast = uimenu(h.analMenu,'Label', 'Apply Statistical Contrast',...
    'Separator', 'on', 'Callback', ' tc_contrast;');

% % for a certain design type, with alternating null periods b/w active
% % conditions, allow the user to automatically merge each null condition
% % with the previous trial, (maybe) saving a parfile along the way
%  if all(tc.trials.cond(1:2:end)==0) | all(tc.trials.cond(2:2:end)==0)
%     uimenu(h.analMenu,'Label','Remove Null Conditions...','Separator','on',...
%                      'Callback','tc_mergeNullTrials;');
%  end

% save HRF callback:
% tc_saveHrf;
h.saveHrf = uimenu(h.analMenu,'Label','Save HRF','Separator','on',...
    'Callback',' tc_saveHrf; timeCourseUI;');

% dump data to workspace callback:
% tc_dumpDataToWorkspace;
h.dumpToWs = uimenu(h.analMenu,'Label','Dump Data to Workspace','Separator','on',...
    'Callback','tc_dumpDataToWorkspace;');

return
% /---------------------------------------------------------------/ %

% /---------------------------------------------------------------/ %
function h = tc_settingsMenu(tc,h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add menus (3): Settings
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h.settingsMenu = uimenu('ForegroundColor',[0 0 0],'Label','Settings','Separator','on');

% recompute tc callback:
% tc = get(gcf,'UserData');
% tc_recomputeTc(tc);
cb = sprintf('tc = get(gcf,''UserData'');\n');
cb = [cb sprintf('tc = tc_recomputeTc(tc);')];
h.recompute = uimenu(h.settingsMenu,'Label','Change chopTSeries params...','Separator','off','Callback',cb);

% set zero %signal submenu
h.zeroSubMenu = uimenu(h.settingsMenu,'Label','Set Zero % Value...',...
                        'Separator','on');

% set mean of data to 0% callback:
% tc_setZeroPt(1);
h.setMean2Null = uimenu(h.zeroSubMenu,'Label','Set Mean of All Data as Zero',...
                    'Separator','off','Callback','tc_setZeroPt([],-1);');

% set null to 0% callback:
% tc_setZeroPt(1);
h.setZero2Null = uimenu(h.zeroSubMenu,'Label','Set Null Condition as Zero',...
                    'Separator','off','Callback','tc_setZeroPt([],-2);');

% set other condition as 0% callback:
% val = input('What condition should be set as the 0% signal condition? ');
% tc_setZeroPt(val);
h.setOther2Null = uimenu(h.zeroSubMenu,'Label','Set Other Condition as Zero',...
                    'Separator','off','Callback','tc_setZeroPt([],-3);');

% set null to 0% callback:
% tc_setZeroPt(1);
h.setGLMNull = uimenu(h.zeroSubMenu, 'Label', 'Estimate Null from GLM',...
                    'Separator', 'off', 'Callback', 'tc_setZeroPt([],-4);');

% set axis bounds submenu
h.axisSubmenu = uimenu(h.settingsMenu,'Label','Axis Bounds...','Separator','on');

% manually reset
uimenu(h.axisSubmenu,'Label','Set Manually','Separator','off',...
                     'Callback','tc_setAxisBounds;');
% reset to nice value
cb = 'tc_setAxisBounds([],''auto'');';
uimenu(h.axisSubmenu,'Label','Reset to nice values','Separator','off',...
                     'Callback',cb);

% add also a way to change the assigned colors for each condition
uimenu(h.settingsMenu,'Label','Assign Condition Colors...',...
                     'Separator','off','Callback','tc_assignColors;');

% add also a way to change the assigned names for each condition
uimenu(h.settingsMenu,'Label','Assign Condition Names...','Separator','off',...
                     'Callback','tc_assignNames;');

% allow reordering of condition #s
uimenu(h.settingsMenu,'Label','Reorder Condition #s...','Separator','on',...
                     'Callback','tc_reorderCondNums;');

% group several conditions together
uimenu(h.settingsMenu,'Label','Group Conditions...','Separator','off',...
                     'Callback','tc_groupConditions([], ''dialog'');');

% % allow saving of the parfile info (will soon add color info, not yet)
% uimenu(h.settingsMenu,'Label','Save parfiles...','Separator','on',...
%                      'Callback','tc = get(gcf,''UserData''); tc_saveParfiles(tc);');
return
% /---------------------------------------------------------------/ %

% /---------------------------------------------------------------/ %
function h = tc_condMenu(tc,h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add menus (4): condition menu w/ conditions toggle buttons
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback for all menu items:
% umtoggle(gcbo);
% tc_legend(get(gcf, 'UserData'));
% timeCourseUI;
h.condMenu = uimenu('ForegroundColor',[0 0 0],'Label','Conditions','Separator','on');
accelChars = '0123456789-=|';
cb = ['umtoggle(gcbo); tc_legend(get(gcf,''UserData'')); timeCourseUI; '];
for i = 1:length(tc.trials.condNames)
    if i < length(accelChars)
        accel = accelChars(i);
    else
        accel = '';
    end

    if isempty(tc.trials.condNames{i})
        tc.trials.condNames{i} = num2str(i);
    end

    hc(i) = uimenu(h.condMenu, 'Label', tc.trials.condNames{i}, ...
                 'Separator', 'off', 'Checked', 'on', ...
                 'Accelerator', accel, ...
                 'Tag', tc.trials.condNames{i}, ...
                 'UserData', tc.trials.condNums(i), ...
                 'Callback', cb);
end

% unselect the null condition if there is one
if any(tc.trials.condNums==0)
    null = find(tc.trials.condNums==0);
    set(hc(null), 'Checked', 'off');
end
h.condMenuHandles = hc;

return
% /---------------------------------------------------------------/ %

% /---------------------------------------------------------------/ %
function h = tc_exportMenu(tc,h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add menus (6): export options menu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h.exportMenu = uimenu('Label', 'Export', 'Separator', 'on');

h.exportOptions = uimenu(h.exportMenu, 'Label', 'Export Options', ...
							'Callback', 'exportsetupdlg;');

% dump data to workspace:
% (replicated from analysis menu, will disable it once people get used to
% this new menu)
h.dumpToWs = uimenu(h.exportMenu, 'Label', 'Dump Data to Workspace', ...
					'Callback', 'tc_dumpDataToWorkspace;');

% export parfile info (moved over from analysis menu)
uimenu(h.exportMenu, 'Label', 'Save parfiles as...', ...
		 'Callback', 'tc_saveParfiles(get(gcf,''UserData''));');

return
% /---------------------------------------------------------------/ %

% /---------------------------------------------------------------/ %
function h = tc_helpMenu(tc,h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add menus (6): help menu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h.helpMenu = uimenu('ForegroundColor',[.6 .2 0],'Label','Help','Separator','on');

% web page callback:
% web http://white.stanford.edu/newlm/index.php/Time_Course_UI
cb = 'web http://white.stanford.edu/newlm/index.php/Time_Course_UI';
h.webHelp = uimenu(h.helpMenu,'Label','Time Course UI page','Separator','off',...
    'Callback',cb);

% web page (external browser) callback:
% web http://white.stanford.edu/newlm/index.php/Time_Course_UI -browser
cb = 'web http://white.stanford.edu/newlm/index.php/Time_Course_UI -browser';
cb = 'web http://white/newlm/index.php/Main_Page -browser';
h.webHelp2 = uimenu(h.helpMenu,'Label','Time Course UI page (external browser)','Separator','off',...
    'Callback',cb);

% mrVista web page callback:
% web web http://white.stanford.edu/newlm/index.php/Main_Page
cb = 'web http://white.stanford.edu/newlm/index.php/Main_Page';
h.webWiki = uimenu(h.helpMenu, 'Label', 'mrVista wiki', ...
    'Separator', 'off', 'Callback', cb);

% mrVista web page (external browser) callback:
% web web http://white.stanford.edu/newlm/index.php/Main_Page
% -browser
h.webWiki2 = uimenu(h.helpMenu, 'Label', 'mrVista wiki (external browser)', ...
    'Separator', 'off', 'Callback', cb);

% identify callback for menu item
cb = 'helpFindCallback; ';
uimenu(h.helpMenu, 'Label', 'Identify Callback for a menu item', ...
        'Separator', 'on', 'Callback', cb);

% add handles to tc struct
fields = fieldnames(h);
for i = 1:length(fields)
    tc.ui.(fields{i}) = h.(fields{i});
end

return


function toolboxGenDoc
% Generate documentation, must run from dir toolbox.
%
% 1) Make sure to update and run toolboxUpdateHeader.m
% 2) Update history.txt appropriately, including w current version
% 3) Update overview.html file with the version/data/link to zip:
%     edit external/m2html/templates/frame-piotr/overview.html
%
% USAGE
%  toolboxGenDoc
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Image&Video Toolbox      Version 3.20
% Copyright 2013 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

% Requires external/m2html to be in path.
cd(fileparts(mfilename('fullpath'))); cd('../');
addpath([pwd '/external/m2html']);

% delete temporary files that should not be part of release
fs={'pngreadc','pngwritec','rjpg8c','wjpg8c'};
for i=1:length(fs), delete(['images/private/' fs{i} '.*']); end

% delete old doc and run m2html
if(exist('doc/','dir')), rmdir('doc/','s'); end
dirs={'channels','classify','detector','images','filters','matlab'};
m2html('mfiles',dirs,'htmldir','doc','recursive','on','source','off',...
  'template','frame-piotr','index','menu','global','on');

% copy custom menu.html and history file
sDir='external/m2html/templates/';
copyfile([sDir 'menu-for-frame-piotr.html'],'doc/menu.html');
copyfile('external/history.txt','doc/history.txt');

% remove links to private/ in the menu.html files and remove private/ dirs
for i=1:length(dirs)
  name = ['doc/' dirs{i} '/menu.html'];
  fid=fopen(name,'r'); c=fread(fid,'*char')'; fclose(fid);
  c=regexprep(c,'
([^<]*[<]?[^<]*)private([^<]*[<]?[^<]*)
','');
  fid=fopen(name,'w'); fwrite(fid,c); fclose(fid);
  name = ['doc/' dirs{i} '/private/'];
  if(exist(name,'dir')), rmdir(name,'s'); end
end

% postprocess each html file
for d=1:length(dirs)
  fs=dir(['doc/' dirs{d} '/*.html']); fs={fs.name};
  for j=1:length(fs), postProcess(['doc/' dirs{d} '/' fs{j}]); end
end

end

function postProcess( fName )
lines=readFile(fName);
assert(strcmp(lines{end-1},'') && strcmp(lines{end},''));
% remove m2html datestamp (if present)
assert(strcmp(lines{end-2}(1:22),'
<address>Generated'));
if( strcmp(lines{end-2}(1:25),'
<address>Generated on'))
  lines{end-2}=regexprep(lines{end-2}, ...
    '
<address>Generated on .* by','
<address>Generated by');
end
% insert Google Analytics snippet to end of file
ga={ '';
  '';
  '';
  '';
  '';
  '' };
lines = [lines(1:end-3); ga; lines(end-2:end)];
% write file
writeFile( fName, lines );
end

function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
  n=n+1; lines{n}=fgetl(fid);
  if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end

function writeFile( fName, lines )
fid = fopen( fName, 'wt' );
for i=1:length(lines); fprintf( fid, '%s\n', lines{i} ); end
fclose(fid);
end


function [fixedstring]=fixstring(string)
%FIXSTRING utility function with several purposes:
% - clear possible initial spaces
% - turn possible multiple spaces into single spaces
% - replace irregular spaces (e.g. tab space) with regular spaces
% - suppress possible final spaces
% this guarantees good behaviour of the code

fixedstring = regexprep(strtrim(string), '[ ]{2,}',' ');


classdef PTKContextSet
    % PTKContextSet. An enumeration used to specify the regions of interest
    %     over which a plugin can operate
    %
    %     A context set represents a set of contexts. A context is a region
    %     of interest for which the plugin can be executed. Therefore the
    %     context type repesents the set of contexts for which the plugin
    %     can be run.
    %
    %     For example, the "SingleLung" type represents two contexts: "LeftLung"
    %     and "RightLung". A plugin with the "SingleLung" type can only be run
    %     with one of these two input contexts. If a result is requested for
    %     another context, the Framework will try to convert the contexts
    %     appropriately (this happens in the MimContextHierarchy class).
    %
    %     For example, if a result is requested for the conext "LungROI" but the
    %     plugin being called has type "SingleLung", then the plugin will be
    %     called twice (once for "RightLung" and once for "LeftLung"). The
    %     final result will contain both results.
    %
    %     Plugins specify their PTKContextSet by setting their "Context"
    %     class property.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    enumeration
        OriginalImage,  % The full image
        LungROI,        % A region containing the lung and airways
        Lungs,          % Left and right lungs
        SingleLung,     % Left lung or right lung
        Lobe,
        Segment,

        Any             % Valid for any context
    end

end


classdef LaunchVehicleExtremaTypeEnum < matlab.mixin.SetGet
    %LaunchVehicleExtremaTypeEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        Maximum('Maximum');
        Minimum('Minimum');
    end

    properties
        nameStr char = '';
    end

    methods
        function obj = LaunchVehicleExtremaTypeEnum(nameStr)
            obj.nameStr = nameStr;
        end
    end

    methods(Static)
        function [nameStrs, m] = getNameStrs()
            [m,~] = enumeration('LaunchVehicleExtremaTypeEnum');

            nameStrs = {};
            for(i=1:length(m)) %#ok<*NO4LP>
                nameStrs{end+1} = m(i).nameStr; %#ok<AGROW>
            end
        end

        function [ind, mI] = getIndOfListboxStrs(recordingEnum)
            [m,~] = enumeration('LaunchVehicleExtremaTypeEnum');

            ind = -1;
            mI = [];
            for(i=1:length(m))
                if(m(i) == recordingEnum)
                    ind = i;
                    mI = m(i);
                    break;
                end
            end
        end
    end
end


function xyzf_header_write ( output_filename, output_unit, point_num, ...
  face_num, face_data_num )

%*****************************************************************************80
%
%% XYZF_HEADER_WRITE writes the header of an XYL file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 January 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the name of the output file.
%
%    Input, integer OUTPUT_UNIT, the output file unit number.
%
%    Input, integer POINT_NUM, the number of points.
%
%    Input, integer FACE_NUM, the number of faces.
%
%    Input, integer FACE_DATA_NUM, the number of face items.
%
  fprintf ( output_unit, '#  %s\n', output_filename );
  fprintf ( output_unit, '#  created by xyz_io::xyzf_header_write.m\n' );
  fprintf ( output_unit, '#\n');
  fprintf ( output_unit, '#  Number of points =     %d\n', point_num );
  fprintf ( output_unit, '#  Number of faces =      %d\n', face_num );
  fprintf ( output_unit, '#  Number of face items = %d\n', face_data_num );
  fprintf ( output_unit, '#\n' );

  return
end


function ma_UndoAction(handles)
%ma_UndoAction Summary of this function goes here
%   Detailed explanation goes here
    global number_state_log_entries_per_coast num_SoI_search_revs strict_SoI_search use_selective_soi_search soi_search_tol num_soi_search_attempts_per_rev;

    undo_states = getappdata(handles.ma_MainGUI,'undo_states');
    undo_pointer = getappdata(handles.ma_MainGUI,'undo_pointer');
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');

    if(undo_pointer < 1 || undo_pointer > size(undo_states,1))
        return;
    end

    if(undo_pointer == size(undo_states,1))
        undo_states{end+1,1} = maData;
        undo_states{end,2}   = '';
    end

    maData = undo_states{undo_pointer,1};
    undo_pointer = undo_pointer - 1;

    number_state_log_entries_per_coast = maData.settings.numStateLogPtsPerCoast;
    num_SoI_search_revs = maData.settings.numSoISearchRevs;
    strict_SoI_search = maData.settings.strictSoISearch;
    use_selective_soi_search = maData.settings.useSelectiveSoISearch;
    soi_search_tol = maData.settings.soiSearchTol;
    num_soi_search_attempts_per_rev = maData.settings.numSoiSearchAttemptsPerRev;

    maData.stateLog = ma_executeScript(maData.script,handles,celBodyData,findobj('Tag','scriptWorkingLbl'));
    maData.celBodyData = celBodyData;
    setappdata(handles.ma_MainGUI,'undo_pointer',undo_pointer);
    setappdata(handles.ma_MainGUI,'undo_states',undo_states);
    setappdata(handles.ma_MainGUI,'ma_data',maData);
    ma_processData(handles);
end


classdef figurePrinter < handle

    properties (Access = protected)
        x0 = 1920;
        y0 = 500;
        width = 600;
        height = 600;
        %labelFontSize = 30;
        labelFontSize = 200;
        %fontSize = 20;
        fontSize = 30;
        outFormat = '-dpng';
        figID
    end

    methods (Access = public)

        function print(obj,figName)
            obj.printFigure(figName)
        end

    end

    methods (Access = protected)

        function setFontSizes(obj)
            obj.setCurrentAxisFontSize();
            obj.setXlabelFontSize();
            obj.setYlabelFontSize();
        end

        function setPositionAndSize(obj)
            set(obj.figID,'units','points','position',[obj.x0,obj.y0,obj.width,obj.height])
        end

        function printFigure(obj,figName)
            print(obj.figID,figName,obj.outFormat);
        end

    end

    methods (Access = private)

        function setCurrentAxisFontSize(obj)
            set(gca,'fontsize',obj.fontSize)
        end

        function setXlabelFontSize(obj)
            ca = get(obj.figID,'CurrentAxes');
            xl = get(ca,'xlabel');
            set(xl,'FontSize',obj.labelFontSize)
        end

        function setYlabelFontSize(obj)
            ca = get(obj.figID,'CurrentAxes');
            yl = get(ca,'ylabel');
            set(yl,'FontSize',obj.labelFontSize)
        end

    end

end


function str = optiMLVer()

v = ver('matlab');
if(v.Release(1) == '(')
    str = v.Release(2:end-1);
else
    str = v.Release;
end


function structout = setstructfields(structin, newfields)
%SETSTRUCTFIELDS Set fields of a structure using another structure
%   SETSTRUCTFIELDS(STRUCTIN, NEWFIELDS) Set fields of STRUCTIN using
%   another structure NEWFIELDS fields.  If fields exist in STRUCTIN
%   but not in NEWFIELDS, they will not be changed.

%   Author(s): J. Schickler
%   Copyright 1988-2004 The MathWorks, Inc.
%   $Revision: 1.3.4.3 $  $Date: 2007/12/14 15:16:12 $
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

%narginchk(2,2);

% Set the output to the input
structout = structin;

% If newfields is not a structure return
if ~isstruct(newfields), return; end

% Loop over all the fields of newfields and assign them to the output
fields = fieldnames(newfields);
for i = 1:length(fields),
    value = newfields.(fields{i});
    if isstruct(value) && isfield(structout, fields{i}) && isstruct(structout.(fields{i}))
        structout.(fields{i}) = setstructfields(structout.(fields{i}), value);
    else
        structout.(fields{i}) = newfields.(fields{i});
    end
end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////


function X = parseargs(X,varargin)
%PARSEARGS - Parses name-value pairs
%
% Behaves like setfield, but accepts multiple name-value pairs and provides
% some additional features:
% 1) If any field of X is an cell-array of strings, it can only be set to
%    one of those strings.  If no value is specified for that field, the
%    first string is selected.
% 2) Where the field is not empty, its data type cannot be changed
% 3) Where the field contains a scalar, its size cannot be changed.
%
% X = parseargs(X,name1,value1,name2,value2,...)
%
% Intended for use as an argument parser for functions which multiple options.
% Example usage:
%
% function my_function(varargin)
%   X.StartValue = 0;
%   X.StopOnError = false;
%   X.SolverType = {'fixedstep','variablestep'};
%   X.OutputFile = 'out.txt';
%   X = parseargs(X,varargin{:});
%
% Then call (e.g.):
%
% my_function('OutputFile','out2.txt','SolverType','variablestep');

% The various #ok comments below are to stop MLint complaining about
% inefficient usage.  In all cases, the inefficient usage (of error, getfield,
% setfield and find) is used to ensure compatibility with earlier versions
% of MATLAB.

% Copyright 2006-2010 The MathWorks, Inc.

remaining = nargin-1; % number of arguments other than X
count = 1;
fields = fieldnames(X);
modified = zeros(size(fields));
% Take input arguments two at a time until we run out.
while remaining>=2
    fieldname = varargin{count};
    fieldind = find(strcmp(fieldname,fields));
    if ~isempty(fieldind)
        oldvalue = getfield(X,fieldname); %#ok
        newvalue = varargin{count+1};
        if iscell(oldvalue)
            % Cell arrays must contain strings, and the new value must be
            % a string which appears in the list.
            if ~iscellstr(oldvalue)
                error(sprintf('All allowed values for "%s" must be strings',fieldname));  %#ok
            end
            if ~ischar(newvalue)
                error(sprintf('New value for "%s" must be a string',fieldname));  %#ok
            end
            if isempty(find(strcmp(oldvalue,newvalue))) %#ok
                error(sprintf('"%s" is not allowed for field "%s"',newvalue,fieldname));  %#ok
            end
        elseif ~isempty(oldvalue)
            % The caller isn't allowed to change the data type of a non-empty property,
            % and scalars must remain as scalars.
            if ~strcmp(class(oldvalue),class(newvalue))
                error(sprintf('Cannot change class of field "%s" from "%s" to "%s"',...
                    fieldname,class(oldvalue),class(newvalue))); %#ok
            elseif numel(oldvalue)==1 & numel(newvalue)~=1 %#ok
                error(sprintf('New value for "%s" must be a scalar',fieldname));  %#ok
            end
        end
        X = setfield(X,fieldname,newvalue); %#ok
        modified(fieldind) = 1;
    else
        error(['Not a valid field name: ' fieldname]);
    end
    remaining = remaining - 2;
    count = count + 2;
end
% Check that we had a value for every name.
if remaining~=0
    error('Odd number of arguments supplied.  Name-value pairs required');
end

% Now find cell arrays which were not modified by the above process, and select
% the first string.
notmodified = find(~modified);
for i=1:length(notmodified)
    fieldname = fields{notmodified(i)};
    oldvalue = getfield(X,fieldname); %#ok
    if iscell(oldvalue)
        if ~iscellstr(oldvalue)
            error(sprintf('All allowed values for "%s" must be strings',fieldname)); %#ok
        elseif isempty(oldvalue)
            error(sprintf('Empty cell array not allowed for field "%s"',fieldname)); %#ok
        end
        X = setfield(X,fieldname,oldvalue{1}); %#ok
    end
end


%   AUTHORSHIP
%   Primary Developer: Stephen Meehan <swmeehan@stanford.edu>
%   Math Lead & Secondary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>
%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%

% this wrapper around MatLab internal map is meant for
% polymorphic function signature compatability with other
% classdef and JAVA class in CytoGenie AutoGate
classdef BasicMap < Map
    properties
        pu;
        parentCmpForPopup;
        needToAskForUmap=true;
        noDbscan=false;
        urlMap;
    end

    properties(SetAccess=private)
        appFolder;
        contentFolder;
        toolBarSize=0;
        toolBarFactor=0;
        highDef=false;
        supStart='';
        supEnd='';
        subStart='';
        subEnd='';
        smallStart='';
        smallEnd='';
        h3Start='
';
        h3End='
';
        h2Start='
';
        h2End='
';
        h1Start='
';
        h1End='
';
        whereMsgOrQuestion='center';
    end

    methods(Static)

        function this=Global(closeIfTrueOrMap)
            persistent singleton;
            if nargin>0 && islogical(closeIfTrueOrMap) && closeIfTrueOrMap
                clear singleton;
                singleton=[];
                disp('Resetting global BasicMap');
                this=[];
            else
                if nargin==1
                    try
                        priorMap=closeIfTrueOrMap;
                        %test method compatibility
                        priorMap.size
                        prop='IsBasicMap';
                        if ~priorMap.has(prop)
                            priorMap.set(prop, 'false')
                            priorMap.get(prop, 'true')
                            priorMap.remove(prop);
                        else
                            priorMap.get(prop, 'true')
                        end
                        singleton=priorMap;
                        this=singleton;
                        return;
                    catch ex
                        ex.getReport
                    end
                end
                if isempty(singleton)
                    singleton=BasicMap;
                    singleton.highDef=Gui.hasPcHighDefinitionAProblem(2000, 2500, false);
                    BasicMap.SetHighDef(singleton, singleton.highDef);
                end
                this=singleton;
            end
        end

        function path=Path
            path=BasicMap.Global.contentFolder;
        end

        function obj=SetHighDef(obj, hasHighDef)
            factor=0;
            NORMAL_FONT_SIZE=12;
            SMALL_FONT_SIZE=2;
            H3_FONT_SIZE=3;
            H2_FONT_SIZE=3.5;
            H1_FONT_SIZE=4;
            if hasHighDef
                obj.highDef=true;
                factor=javax.swing.UIManager.getFont('Label.font').getSize...
                    /NORMAL_FONT_SIZE;
            else
                if ismac
                    %factor=1.6;
                end
            end
            if factor>0
                obj.toolBarFactor=factor;
                obj.toolBarSize=floor(16*factor);
                smallSize=floor(SMALL_FONT_SIZE*factor);
                if ispc
                    smallSize=smallSize+1;
                end
                obj.smallStart=[''];
                obj.smallEnd='';
                obj.subStart=obj.smallStart;
                obj.supStart=obj.smallStart;
                obj.subEnd=obj.smallEnd;
                obj.supEnd=obj.smallEnd;
                h1Size=floor(H1_FONT_SIZE *factor);
                if ispc
                    h1Size=h1Size+1;
                end
                obj.h1Start=[''];
                obj.h1End='
';

                h2Size=floor(H2_FONT_SIZE *factor);
                if ispc
                    h2Size=h2Size+1;
                end
                obj.h2Start=[''];
                obj.h2End='
';

                h3Size=floor(H3_FONT_SIZE *factor);
                if ispc
                    h3Size=h3Size+1;
                end
                obj.h3Start='
';
                obj.h3End='
';
            else
                obj.toolBarSize=0;
                obj.toolBarFactor=0;
                obj.highDef=false;

                obj.smallStart='';
                obj.smallEnd='';
                obj.h3Start='
';
                obj.h3End='
';
                obj.h2Start='
';
                obj.h2End='
';
                obj.h1Start='
';
                obj.h1End='
';

            end
        end

        function nums=GetNumbers(props, name)
            nums=props.get(name, []);
            if ~isempty(nums)
                nums=str2num(nums);
            else
                nums=[];
            end
        end

    end

    methods
        function this=BasicMap(keysOrFileName, values)
            if nargin<2
                values={};
                if nargin<1
                    keysOrFileName=[];
                end
            end
            this=this@Map(keysOrFileName, values);
            this.contentFolder=fileparts(mfilename('fullpath'));
            this.appFolder=fullfile(File.Home, '.run_umap');
            File.mkDir(this.appFolder);
            this.urlMap=Map;
            %'https://1drv.ms/u/s!AkbNI8Wap-7_jNJYg4RNDTKR4mkYOg?e=pfwWfO'
        end

        function closeToolTip(this)
        end

        function retry=reportProblem(this, exception, retryId)
            retry=false;
            exception.getReport;
        end

        function [name, found]=getMatchName(this, name, showEppImg, b1, b2)
            if nargin<4
                if this.highDef
                    b1='';
                    b2='';
                else
                    b1='';
                    b2='';
                end
                if nargin<3
                    if nargin<2
                        showEppImg=true;
                    end
                end
            end
            idx=strfind(name, ',\bf');
            if ~isempty(idx)
                sIdx=4;
                idx=idx(1);
            else
                idx=strfind(name, '\bf');
                sIdx=3;
            end
            if ~isempty(idx)
                matchName=strtrim(name(idx(1)+sIdx:end));
                eppName=name(1:idx(1)-1);
                if showEppImg
                    eppName =[ eppName ' ' this.eppImg];
                end
                if idx==1
                    name=[matchName eppName];
                else
                    name=[matchName ' ' b1 eppName b2];
                end
                found=true;
            else
                found=false;
            end
        end

    end
end


function varargout = segymat(varargin)
% segymat : Garphical User Interface for SegyMAT
%
%   (C) 2001-2004 Thomas Mejer Hansen, tmh@gfy.ku.dk/thomas@cultpenguin.com
%

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

% Last Modified by GUIDE v2.5 05-Jan-2009 17:29:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @segymat_OpeningFcn, ...
                   'gui_OutputFcn',  @segymat_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);

% Next line is edited
% ORIGINAL : if nargin & isstr(varargin{1})
if nargin>1 & isstr(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

if nargin==1 & isstr(varargin{1})
    [path,file,suffix]=fileparts(varargin{1});
    segyfile.pathname=path;
    if length(suffix)>1,
        segyfile.filename=[file,'.',suffix];
    else
        segyfile.filename=file;
    end
    % FIGURE OUT HOW TO GET THE hObject ??
    % fReadSegy_Callback(hObject, eventdata, handles,segyfile);
end

% End initialization code - DO NOT EDIT

% --- Executes just before segymat is made visible.
function segymat_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 segymat (see VARARGIN)

  SegymatVerbose(['GUI : OPENING GUI'],20)
% Choose default command line output for segymat
handles.output = hObject;

% Initialize PlotPref
handles.PlotPref.Show=0;

% Update handles structure
guidata(hObject, handles);

% Resize Figure
fMain_ResizeFcn(hObject, eventdata, handles)

%  read in segy file
segyfile.pathname='c:\MaTLAB6p5\work\';
segyfile.filename='test.sgy';
%segyfile.filename='peaksh.segy';
%fReadSegy_Callback(hObject, eventdata, handles,segyfile);

% disable edit menu
UpdateMenus(hObject, eventdata, handles)

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

% --- Outputs from this function are returned to the command line.
function varargout = segymat_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 when fMain window is resized.
function fMain_ResizeFcn(hObject, eventdata, handles)
% hObject    handle to fMain (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,'fMain')==0)
    return
end

SegymatVerbose(['GUI : Resizing'],20)

data=guidata(hObject);

% Get Size of Main Window
[mainPos]=get(handles.fMain,'Position');

d=4; % Distance to edges
d_ax=.2; % distance between axes
if isfield(data,'PlotPref')==0,
    data.PlotPref.Show=1;
    guidata(hObject,data);
end
if isfield(data.PlotPref,'Show')==0,
    data.PlotPref.Show=1;
    guidata(hObject,data);
end

% fHeader Location
if data.PlotPref.Show==0,
    fHeaderW=d;
    set(handles.fHeader,'Visible','Off');
    set(handles.text7,'Visible','Off');
    set(handles.txtGain,'Visible','Off');
    set(handles.pbGainUp,'Visible','Off');
    set(handles.pbGainDown,'Visible','Off');
    set(handles.eGainMin,'Visible','Off');
    set(handles.eGainMax,'Visible','Off');
    set(handles.popTop,'Visible','Off');
    set(handles.popBot,'Visible','Off');
    set(handles.txtTop,'Visible','Off');
    set(handles.txtBot,'Visible','Off');
    set(handles.txtColormap,'Visible','Off');
    set(handles.popColormap,'Visible','Off');
    set(handles.txtStyle,'Visible','Off');
    set(handles.popStyle,'Visible','Off');
else
    fHeaderW=30; % WIDTH OF INFO PAGE
    x0=d;y0=d;
    w=fHeaderW-d;
    h=mainPos(4)-2*d;
    x1=x0+w;
    y1=y0+h;

    Wuic=8; % WIDTH OF UICONTROL
    Huic=1.4; %    HEIGHT OF UICONTROL

    set(handles.fHeader,'Position',[x0 y0 w h])
    d_frame=1;
    x0=x0+d_frame;
    wframe=w-2*d_frame;
    % TXT HEADER
    ytop=mainPos(4)-d;
%    set(handles.text7,'Position',[d+d ytop fHeaderW-3*d 2]);
    set(handles.text7,'Position',[x0 ytop wframe 2]);

    % GAIN
    ytop=ytop-d_ax-Huic;
    set(handles.txtGain,'Position',[x0,ytop,wframe,Huic])
    ytop=ytop-d_ax-Huic;
    w_sign=4;
    set(handles.eGainMin,'Position',[x0,ytop,wframe-w_sign,Huic])
    set(handles.pbGainDown,'Position',[x0+wframe-w_sign,ytop,w_sign,Huic])
    ytop=ytop-d_ax-Huic;
    set(handles.eGainMax,'Position',[x0,ytop,Wuic*1.5,Huic])
    set(handles.pbGainUp,'Position',[x0+Wuic*1.5,ytop,Wuic/2,Huic])
    set(handles.eGainMax,'Position',[x0,ytop,wframe-w_sign,Huic])
    set(handles.pbGainUp,'Position',[x0+wframe-w_sign,ytop,w_sign,Huic])

    % TopSub
    ytop=ytop-2*d_ax-Huic;
    set(handles.txtTop,'Position',[x0,ytop,wframe,Huic])
    ytop=ytop-d_ax-Huic;
    set(handles.popTop,'Position',[x0,ytop,wframe,Huic])

    % BaseSub
    ytop=ytop-2*d_ax-Huic;
    set(handles.txtBot,'Position',[x0,ytop,wframe,Huic])
    ytop=ytop-d_ax-Huic;
    set(handles.popBot,'Position',[x0,ytop,wframe,Huic])

    % Style
    ytop=ytop-2*d_ax-Huic;
    set(handles.txtStyle,'Position',[x0,ytop,wframe,Huic])
    ytop=ytop-d_ax-Huic;
    set(handles.popStyle ,'Position',[x0,ytop,wframe,Huic])

    % Colormap
    ytop=ytop-2*d_ax-Huic;
    set(handles.txtColormap,'Position',[x0,ytop,wframe,Huic])
    ytop=ytop-d_ax-Huic;
    set(handles.popColormap ,'Position',[x0,ytop,wframe,Huic])

    %

    % MAKE ALL VISIBLE
    set(handles.fHeader,'Visible','On');
    set(handles.text7,'Visible','On');
    set(handles.txtGain,'Visible','On');
    set(handles.pbGainUp,'Visible','On');
    set(handles.pbGainDown,'Visible','On');
    set(handles.eGainMin,'Visible','On');
    set(handles.eGainMax,'Visible','On');
    set(handles.popTop,'Visible','On');
    set(handles.popBot,'Visible','On');
    set(handles.txtTop,'Visible','On');
    set(handles.txtBot,'Visible','On');
    set(handles.txtColormap,'Visible','On');
    set(handles.popColormap,'Visible','On');
    set(handles.txtStyle,'Visible','On');
    set(handles.popStyle,'Visible','On');
end

% AXIS
axLeft=fHeaderW+2*d;
Hsmallax=4;

% axBot
axBotX=axLeft;
axBotY=d;
axBotW=mainPos(3)-axLeft-2*d;
axBotH=Hsmallax;
axB=get(handles.axBot,'Position');
set(handles.axBot,'Position',[axBotX axBotY axBotW axBotH])

% axTop
axTopX=axLeft;
axTopY=mainPos(4)-Hsmallax-d;
axTopW=axBotW;
axTopH=Hsmallax;
axT=get(handles.axTop,'Position');
set(handles.axTop,'Position',[axTopX axTopY axTopW axTopH])

% axMain
axMainX=axLeft;
axMainY=axBotY+Hsmallax+d_ax;
axMainW=axBotW;
axMainH=mainPos(4)-axMainY-Hsmallax-d-d_ax;
set(handles.axMain,'Position',[axMainX axMainY axMainW axMainH])

% --------------------------------------------------------------------
function UpdatePrefs(hObject, eventdata, handles)
  SegymatVerbose(['GUI : UpdatePrefs'],20)
  data=guidata(hObject);

if isfield(data,'SegyData')==0,
    set(handles.eGainMin,'Enable','off');
    set(handles.eGainMin,'String','');
    set(handles.eGainMax,'Enable','off');
    set(handles.eGainMax,'String','');
   return
else
    set(handles.eGainMin,'Enable','on');
    set(handles.eGainMax,'Enable','on');
end

if isfield(data.PlotPref,'caxis')==0
    data.PlotPref.caxis=[min(data.SegyData(:)) max(data.SegyData(:))];
end
set(handles.eGainMin,'String',data.PlotPref.caxis(1));
set(handles.eGainMax,'String',data.PlotPref.caxis(2));

if isfield(data.PlotPref,'TraceHeaders')==0,
    data.PlotPref.TraceHeaders=fieldnames(data.SegyTraceHeaders);
end
if isfield(data.PlotPref,'TopPlot')==0, data.PlotPref.TopPlot=7; end
if isfield(data.PlotPref,'BotPlot')==0, data.PlotPref.BotPlot=13; end
set(handles.popTop,'String',data.PlotPref.TraceHeaders);
set(handles.popTop,'value',data.PlotPref.TopPlot);
set(handles.popTop,'Enable','On');
set(handles.popBot,'String',data.PlotPref.TraceHeaders);
set(handles.popBot,'value',data.PlotPref.BotPlot);
set(handles.popBot,'Enable','On');
guidata(hObject,data);

% --------------------------------------------------------------------
function UpdatePlots(hObject, eventdata, handles)
  SegymatVerbose(['GUI : Update Plots'],20)
  %data=guidata(hObject);

  UpdateMainPlot(hObject, eventdata, handles)

  UpdateTopPlot(hObject, eventdata, handles)
  UpdateBotPlot(hObject, eventdata, handles)

axes(handles.axMain);%%%zoom on;

% --------------------------------------------------------------------
function UpdateMainPlot(hObject, eventdata, handles)
  SegymatVerbose(['GUI : Update Main Plot'],20)
  data=guidata(hObject);
  Style=get(handles.popStyle,'Value'); % GET PLOTTING STYLE
  axes(handles.axMain);

  if ((Style==1)|(Style==4)|(Style==5))
    imagesc(data.SegyTrace,data.SegyTime,data.SegyData);
    caxis(data.PlotPref.caxis)
    hold on
  end

  gain=max(abs(data.PlotPref.caxis));
  if ((Style==2)|(Style==4))
    wiggle(data.SegyTrace,data.SegyTime,data.SegyData,'wiggle',gain);
  end
  if ((Style==3)|(Style==5))
    wiggle(data.SegyTrace,data.SegyTime,data.SegyData,'VA',gain);
  end
  hold off
  set(gca,'YaxisLocation','Right');
  set(gca,'XtickLabel',[]);
  ylabel('TWT [ms]')

  %% RESET ZOOM SUCH THAT THIS STATE IS THE 'ZOOM OUT' STATE.
  zoom reset;

  %%%zoom on;

% --------------------------------------------------------------------
function UpdateTopPlot(hObject, eventdata, handles)
  SegymatVerbose(['GUI : Update TOP Plots'],60)
  data=guidata(hObject);
  axes(handles.axMain);axMain=axis;

  pop=get(handles.popTop,'String');
  ipop=get(handles.popTop,'value');
  hname=pop{ipop};

  axes(handles.axTop)
  if isfield(data,'dTopPlot')
		if ipop~=data.dTopPlot_ipop
			data.dTopPlot=bar([data.SegyTraceHeaders.(hname)]);
			data.dTopPlot_ipop=ipop;
			guidata(hObject,data)
		end
	else
	  data.dTopPlot=bar([data.SegyTraceHeaders.(hname)]);
		data.dTopPlot_ipop=ipop;
	  guidata(hObject,data)
	end
  ax=axis;axis([axMain(1) axMain(2) ax(3) ax(4)])
  set(gca,'XaxisLocation','Top');
  set(gca,'YaxisLocation','Right');
  xlabel(hname)
  axes(handles.axMain);%%%zoom on;

function UpdateBotPlot(hObject, eventdata, handles)
  SegymatVerbose(['GUI : Update BOT Plots'],60)
  data=guidata(hObject);
  axes(handles.axMain);axMain=axis;

  pop=get(handles.popBot,'String');
  ipop=get(handles.popBot,'value');
  hname=pop{ipop};

  axes(handles.axBot)
	if isfield(data,'dBotPlot')
		if ipop~=data.dBotPlot_ipop
			data.dBotPlot=plot([data.SegyTraceHeaders.(hname)]);
			data.dBotPlot_ipop=ipop;
			guidata(hObject,data)
		end
	else
		data.dBotPlot=plot([data.SegyTraceHeaders.(hname)]);
	  data.dBotPlot_ipop=ipop;
		guidata(hObject,data)
	end

  % bar([data.SegyTraceHeaders.(hname)]);
  ax=axis;axis([axMain(1) axMain(2) ax(3) ax(4)])
  set(gca,'XaxisLocation','Bot');
  set(gca,'YaxisLocation','Right');
  xlabel(hname)
  axes(handles.axMain);%%%zoom on;

% --------------------------------------------------------------------
function UpdateGain(hObject, eventdata, handles)
  SegymatVerbose(['GUI : UpdateGain'],20)
  data=guidata(hObject);
  set(handles.eGainMin,'String',data.PlotPref.caxis(1));
  set(handles.eGainMax,'String',data.PlotPref.caxis(2));
  axes(handles.axMain);
  caxis(data.PlotPref.caxis);
  drawnow;

% --------------------------------------------------------------------
function KeyPressFcn_Callback(hObject, eventdata, handles)
data=guidata(hObject);
Key=get(gcf,'CurrentCharacter');
%SegymatVerbose(['GUI : KeyPressFcn :  ',num2str(double(Key)),' ',char(Key)],20)
%disp(char(Key));
%disp(double(Key));

%%%%%%%%%%%
% GAIN
%if (Key=='+'),
if ((double(Key)==30)|(double(Key)==43)|(double(Key)==115))
    data.PlotPref.caxis=data.PlotPref.caxis./(1.2);
    guidata(hObject,data);
    UpdateGain(hObject, eventdata, handles) ;
end
%if (Key=='-');
if ((double(Key)==31)|(double(Key)==45)|(double(Key)==120))
    data.PlotPref.caxis=data.PlotPref.caxis.*(1.2);
    guidata(hObject,data);
    UpdateGain(hObject, eventdata, handles) ;
end

%% SHOW PREFS
if (lower(Key)=='h')
    if isfield(data.PlotPref,'Show')==0, data.PlotPref.Show=1;end
    data.PlotPref.Show=1-data.PlotPref.Show;
    guidata(hObject,data);
    fMain_ResizeFcn(hObject,[],handles);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% ZOOM ON MAIN AX
if isfield(data,'zoomfac')==0
    data.zoomfac=1.5;
    guidata(hObject,data);
end
zoom_in_keys=[29,97]; % ARROW RIGHT OR 'a'
zoom_out_keys=[28,122]; % ARROW LEFT OR 'z'
if isempty(Key)==1
  Key=0;
end

try
if find(double(Key)==zoom_in_keys);
	zoom(data.zoomfac)
	UpdateTopPlot(hObject, eventdata, handles)
	UpdateBotPlot(hObject, eventdata, handles)
end
catch
SegymatVerbose(sprintf('%s : failed to zoom',mfilename))
%keyboard;
end
if find(double(Key)==zoom_out_keys);
    zoom(-data.zoomfac)
	UpdateTopPlot(hObject, eventdata, handles)
	UpdateBotPlot(hObject, eventdata, handles)
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MOVE
if isfield(data,'movefac')==0
    % Movefac=1; move in stepos of size of window
    % Movefac=0.5; move in steps of half-size of window
    data.movefac=.02;
    guidata(hObject,data);
end
if (double(Key)>=49)&(double(Key)<=117), % NUM PAD

  go_left_keys=[52,117]; % 2,j
	go_right_keys=[54,111]; % 2,j
	go_down_keys=[50,107]; % 2,j
	go_up_keys=[56]; % 2,j

  xlim=get(handles.axMain,'Xlim');
  ylim=get(handles.axMain,'Ylim');
  wx=(xlim(2)-xlim(1)).*data.movefac;
  wy=(ylim(2)-ylim(1)).*data.movefac;

  if (find(go_up_keys==double(Key))), set(handles.axMain,'Ylim',ylim-wy); end % 8
  if (find(go_down_keys==double(Key))), set(handles.axMain,'Ylim',ylim+wy); end % 2
  if (find(go_left_keys==double(Key))), set(handles.axMain,'Xlim',xlim-wx); end % 4
  if (find(go_right_keys==double(Key))), set(handles.axMain,'Xlim',xlim+wx); end % 6

  if (double(Key)==49), % 1
    set(handles.axMain,'Ylim',ylim+wy);
    set(handles.axMain,'Xlim',xlim-wx);
  end % 1
  if (double(Key)==51),  % 3
    set(handles.axMain,'Ylim',ylim+wy);
    set(handles.axMain,'Xlim',xlim+wx);
  end % 3
  if (double(Key)==55),  % 7
    set(handles.axMain,'Ylim',ylim-wy);
    set(handles.axMain,'Xlim',xlim-wx);
  end % 7
  if (double(Key)==57), % 9
    set(handles.axMain,'Ylim',ylim-wy);
    set(handles.axMain,'Xlim',xlim+wx);
  end % 9
  if (double(Key)==53),  % 5
    axes(handles.axMain)
    zoom out;

  end % 5
  xlim_after=get(handles.axMain,'Xlim');
  if (sum(xlim==xlim_after)<2)
    UpdateTopPlot(hObject, eventdata, handles)
    UpdateBotPlot(hObject, eventdata, handles)
  end
end

%
% IO FUNCTIONS
%

% --------------------------------------------------------------------
function mFileOpen_Callback(hObject, eventdata, handles)
% hObject    handle to mFileOpen (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
    data=guidata(hObject);
    if isfield(data,'SegyFile');
        segyfile=DIAOpenSEGY(data.SegyFile);
    else
        segyfile=DIAOpenSEGY;
    end
	fReadSegy_Callback(hObject, eventdata, handles,segyfile);
catch
end
% --------------------------------------------------------------------
function mOpenFileFast_Callback(hObject, eventdata, handles)
% hObject    handle to mOpenFileFast (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
	[segyfile.filename,segyfile.pathname]=uigetfile( ...
    {'*.segy;*.SEGY;*.SEGY;*.sgy','All Segy files'; ...
     '*.su;*.SU;*.sU;*.Su','All SU files'; ...
     '*','All Files'},...
    'Pick A SEGY file');
	fReadSegy_Callback(hObject, eventdata, handles,segyfile);
catch
end

% --------------------------------------------------------------------
function fReadSegy_Callback(hObject, eventdata, handles,segyfile);
data=guidata(hObject);
try
	[dpath,dfile,dsuffix]=fileparts(segyfile.filename);
	if (strcmp(lower(dsuffix),'.su'))
		[data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSu(fullfile(segyfile.pathname,segyfile.filename));
    else
        if isfield(segyfile,'JUMP');
            k=0;
            try
            if segyfile.JUMP.enable==1
                k=k+1;v{k}='jump';
                k=k+1;v{k}=segyfile.JUMP.jump;
            end
            if segyfile.TIMERANGE.enable==1
                k=k+1;v{k}='trange';
                k=k+1;v{k}=segyfile.TIMERANGE.min;
                k=k+1;v{k}=segyfile.TIMERANGE.max;
            end
            if segyfile.TRACEHEADER.enable==1
                k=k+1;v{k}='minmax';
                k=k+1;v{k}=segyfile.TRACEHEADER.name;
                k=k+1;v{k}=segyfile.TRACEHEADER.min;
                k=k+1;v{k}=segyfile.TRACEHEADER.max;
            end
            catch
                SegymatVerbose(sprintf('%s : failed to make use of headers for reading',mfilename))
                %keyboard
            end
            if k>0
                [data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSegy(fullfile(segyfile.pathname,segyfile.filename),v);
            else
                [data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSegy(fullfile(segyfile.pathname,segyfile.filename));
            end
        else
            [data.SegyData,data.SegyTraceHeaders,data.SegyHeader]=ReadSegy(fullfile(segyfile.pathname,segyfile.filename));
        end
    end
    if isempty(data.SegyData)
          f = warndlg('No data was read !', 'ReadSegy warning', 'modal');
    else
        set(handles.fMain,'name',['SegyMAT : ',segyfile.filename])
        data.SegyFile=segyfile;
        data.SegyTime=[1:1:data.SegyHeader.ns].*data.SegyHeader.dt/1e+6;
        data.SegyTrace=[1:length(data.SegyTraceHeaders)];
        data.PlotPref.Show=1;
        data.PlotPref.caxis=[min(data.SegyData(:)) max(data.SegyData(:))];
        guidata(hObject,data);
        fMain_ResizeFcn(hObject, eventdata, handles);
        UpdatePrefs(hObject, eventdata, handles);
        UpdatePlots(hObject, eventdata, handles);
    end
catch
    errordlg('An error occured while reading the SEGY file','Error reading SGY file','modal')
    %keyboard
end
UpdateMenus(hObject, eventdata, handles);

% --------------------------------------------------------------------
function mFileSave_Callback(hObject, eventdata, handles)
% hObject    handle to mFileSave (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
	data=guidata(hObject);
	file=fullfile(data.SegyFile.pathname,data.SegyFile.filename);
	ButtonName=questdlg(['Are you sure you want to override :',file], ...
                       'Warning !!!', ...
                       'Yes','No','No');
  if strcmp(ButtonName,'Yes')
		[dpath,dfile,dsuffix]=fileparts(file);
		if (strcmp(lower(dsuffix),'.su'))
			WriteSuStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
		else
			WriteSegyStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
		end
	end
catch
	errordlg('An error occured while writing SEGY file','Error writing SGY file','modal')
end

% --------------------------------------------------------------------
function mFileSaveAs_Callback(hObject, eventdata, handles)
% hObject    handle to mFileSaveAs (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
try
	data=guidata(hObject);
	[segyfile.filename,segyfile.pathname]=uiputfile( ...
    {'*.segy;*.SEGY;*.SEGY;*.sgy','All Segy files'; ...
     '*.su;*.SU;*.sU;*.Su','All SU files'; ...
     '*','All Files'},...
    'Save as ');
	file=fullfile(segyfile.pathname,segyfile.filename);
	[dpath,dfile,dsuffix]=fileparts(file);
	if (strcmp(lower(dsuffix),'.su'))
		WriteSuStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
	else
		WriteSegyStructure(file,data.SegyHeader,data.SegyTraceHeaders,data.SegyData);
	end
catch
	errordlg('An error occured while writing SEGY file','Error writing SGY file','modal')
end

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

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

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

% --- Executes on button press in pbGainUp.
function pbGainUp_Callback(hObject, eventdata, handles)
% hObject    handle to pbGainUp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
  data=guidata(hObject);
  data.PlotPref.caxis=data.PlotPref.caxis./(1.2);
  guidata(hObject,data);
  UpdateGain(hObject, eventdata, handles) ;

	Style=get(handles.popStyle,'Value'); % GET PLOTTING STYLE
  if ((Style==2)|(Style==4|(Style==3)|(Style==5)))
		UpdateMainPlot(hObject, eventdata, handles)
	end

% --- Executes on button press in pbGainDown.
function pbGainDown_Callback(hObject, eventdata, handles)
% hObject    handle to pbGainDown (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
  data=guidata(hObject);
  data.PlotPref.caxis=data.PlotPref.caxis.*(1.2);
  guidata(hObject,data);
  UpdateGain(hObject, eventdata, handles) ;

	Style=get(handles.popStyle,'Value'); % GET PLOTTING STYLE
  if ((Style==2)|(Style==4|(Style==3)|(Style==5)))
		UpdateMainPlot(hObject, eventdata, handles)
	end

% --- Executes during object creation, after setting all properties.
function eGainMin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to eGainMin (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 eGainMin_Callback(hObject, eventdata, handles)
% hObject    handle to eGainMin (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 eGainMin as text
%        str2double(get(hObject,'String')) returns contents of eGainMin as a double
data=guidata(hObject);
data.PlotPref.caxis(1)=str2double(get(hObject,'String'));
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles);

% --- Executes during object creation, after setting all properties.
function eGainMax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to eGainMax (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 eGainMax_Callback(hObject, eventdata, handles)
% hObject    handle to eGainMax (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 eGainMax as text
%        str2double(get(hObject,'String')) returns contents of eGainMax as a double
data=guidata(hObject);
data.PlotPref.caxis(2)=str2double(get(hObject,'String'));
guidata(hObject,data);
UpdateGain(hObject, eventdata, handles);

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

% --- Executes on selection change in popTop.
function popTop_Callback(hObject, eventdata, handles)
% hObject    handle to popTop (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 popTop contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popTop
  SegymatVerbose(['GUI : Update popTOP'],20)
  UpdateTopPlot(hObject, eventdata, handles)

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

% --- Executes on selection change in popBot.
function popBot_Callback(hObject, eventdata, handles)
% hObject    handle to popBot (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 popBot contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popBot
  SegymatVerbose(['GUI : Update popBOT'],20)
  UpdateBotPlot(hObject, eventdata, handles)

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

% --- Executes on selection change in popColormap.
function popColormap_Callback(hObject, eventdata, handles)
% hObject    handle to popColormap (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 popColormap contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popColormap
  SegymatVerbose(['GUI : Update popColormap'],20)
  data=guidata(hObject);
  cmap=get(hObject,'String');
  icmap=get(hObject,'value');
  axes(handles.axMain);
  colormap(cmap{icmap});
  %%% zoom on;

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

% --- Executes on selection change in popStyle.
function popStyle_Callback(hObject, eventdata, handles)
% hObject    handle to popStyle (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 popStyle contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popStyle
  SegymatVerbose(['GUI : popStyle'],20)
  UpdateMainPlot(hObject, eventdata, handles);
  UpdateTopPlot(hObject, eventdata, handles)
  UpdateBotPlot(hObject, eventdata, handles)

%
% MENUS
%
% --------------------------------------------------------------------
function UpdateMenus(hObject, eventdata, handles)
  SegymatVerbose(['GUI : Update Menus'],20)
	data=guidata(hObject);

	if isfield(data,'SegyData')==0
		set(handles.mEdit,'Visible','Off')
	else
		set(handles.mEdit,'Visible','On')
	end

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

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

% --------------------------------------------------------------------
function mEditSH_Callback(hObject, eventdata, handles)
% hObject    handle to mEditSH (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
	data.SegyHeader=GUIEditSegyHeader(data.SegyHeader);
	guidata(hObject,data)
catch
end
% --------------------------------------------------------------------
function mEditSTH_Callback(hObject, eventdata, handles)
% hObject    handle to mEditSTH (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
	data.SegyTraceHeaders=GUIEditSegyTraceHeader(data.SegyTraceHeaders);
	guidata(hObject,data)
	UpdateTopPlot(hObject, eventdata, handles)
	UpdateBotPlot(hObject, eventdata, handles)
catch
  SegymatVerbose('Something Went wrong calling GUISegyMat')
end

% --------------------------------------------------------------------
function mPlotXY_Callback(hObject, eventdata, handles)
% hObject    handle to mPlotXY (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
    GUIPlotXY(data.SegyTraceHeaders);
catch
  SegymatVerbose('Something Went wrong calling GUISegyMat')
end

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

% --------------------------------------------------------------------
function mEditTextualHeader_Callback(hObject, eventdata, handles)
% hObject    handle to mEditTextualHeader (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=guidata(hObject);
try
	data.SegyHeader=GUIEditTextualFileHeader(data.SegyHeader);
	guidata(hObject,data)
catch
end


function undockfig(fig)
% Copyright 2008 The MathWorks, Inc.
% Programmatically undock one or all open figures.
%
% SYNTAX:
% undockfig
%    Undocks the current figure
%
% undockfig(fig)
%    Undocks figure with handle FIG, and brings it to the front.
%
% undockfig('all')
%    Undocks all open figures
%
% Written by Brett Shoelson, PhD
% brett.shoelson@mathworks.com
% 01/01/08

% Revision 1
% 01/03/08: Providing default behavior when no input argument is provided
% (operates on current figure).

if nargin == 0
    fig = gcf;
end
if ischar(fig) && strcmpi(fig,'all')
    fig = findall(0,'type','figure');
end
for ii = 1:numel(fig)
    set(fig(ii),'windowstyle','modal');
    set(fig(ii),'windowstyle','normal');
end
if numel(fig) == 1
    figure(fig);
end


classdef DesignVarMonitor_LevelSet_2D < DesignVarMonitor_LevelSet

    properties (Access = protected)
        unfittedType = 'INTERIOR'
        meshIncludeBoxContour = false
    end

end


%% efw
% Below is a demonstration of the features of the |efw| function

%% Syntax
% |efw(hf);|

%% Description
% The |efw| function, the export figure widget, adds a push button to a
% figure toolbar to link with the |export_fig| function. Press the button
% to start exporting a figure. Users can specify file names, formats,
% resolution and also additional export_fig options.
%%
% The Export Figure Widget requires the external function |export_fig|
% created by Oliver Woodford and Yair Altman. It can be obtained from the
% Mathworks Central File Exchange:
%%
% <http://www.mathworks.com/matlabcentral/fileexchange/23629-export-fig>

%% Examples

%% Using the preloaded Export Figure Widget (efw) in |cFigure|
% A |cFigure| window has the Export Figure Widget loaded by default. To use
% |efw| click on the icon in the toolbar.
%
% <<efw_icon_menubar.png>>

%%
% Pressing the |efw| button will open a basic |inputdlg| allowing users to
% specify all the usual export_fig options. Hints are given in brackets
% behind the input labels. The default entries are altered according to the
% previous usage within the current figure.

%%
% <<efw_inputdlg.png>>

%% Use with |figure|
% The default MATLAB |figure| does not contain the Export Figure Widget. To
% load it here the user must enter |efw;| either before or after axes are
% created. e.g.:
%%
% |figure; surf(peaks(25)); axis equal; axis tight; efw;|
%%
% which is equivalent to:
%%
% |figure; efw; surf(peaks(25)); axis equal; axis tight;|

%% Tip
% You can create your own figure function that simply contains |figure;
% efw;| to create a standard MATLAB figure containing the Export Figure
% Widget.

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 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 General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function ok = mrInit(varargin)
% Initialize a mrVista session. Replacement for mrInitRet, mrvInit and
% mrInit2.  Moved from mrRSTools (formerly mrVista2).
%
% USAGE: mrInit should be called when the current directory is the one
% you wish to initialize. It can be called one of three ways:
%
%	(1) Interactively: type 'mrInit' without arguments, and a series of
%		dialogues ('mrInitGUI') will collect the initialization parameters.
%
%	(2) With a params struct: mrInit(params) will initialize without user
%		feedback. params is a struct with fields described below.
%
%	(3) mrInit('param', [value], 'param', [value]...) will also initialize
%		without user feedback. The 'param' strings are fields in the param
%		structs, the values are the value for that parameters. Any
%		non-specicified parameters will use the default values.
%
%
% INPUTS:
%   functionals: path string, or cell array of path strings, to the input
%   functional files. Defaults to looking in Raw/Pfiles/P*.mag for Lucas
%   P-mags. Input functionals can be any format readable by mrLoad,
%   including ANALYZE, NIFTI, or DICOM images.
%
%   inplane: path string to the input co-registered inplane anatomy.
%   Defaults to 'Raw/Anatomy/Inplane/I*.dcm' (again consistent w/ Lucas
%   Center conventions.) Can be any format readable by mrLoad.
%
%   params: structure which specifies the organization of the 'Original'
%   data type in the new session. See mrInitDefaultParams for a full
%   description of the parameters. mrInitGUI calls a series of dialogs to
%   get these parameters interactively.
%
% OUTPUTS:
%     The main output is a new mrVista session, with the following files
%     and directory structure:
%       mrSESSION.mat: contains the variables:
%           * mrSESSION: contains info on the input inplanes and
%           functionals.
%           * dataTYPES: info on groups of scans. Initialized only to the
%           default first group, 'Original', which derives from the set of
%           functionals. Analysis parameters for traveling-wave / event
%           analyses are also stored here.
%       Inplane/ directory: contains:
%           * anat.mat: anatomy file. Soon, this should be replaced with a
%           more robust format, like anat.nii.gz (NIFTI) or anat.img
%           (ANALYZE).
%           * Original/: 'data directory' for the Original data type.
%               * Original/TSeries/: directory for time series data from the
%                 functionals. Again, this is an older format: each scan
%                 has a directory ('/Scan2/'), and contains one MATLAB file
%                 for each slice ('tSeries4.mat'), which has the variable
%                 'tSeries', format [nFrames x nVoxelsInSlice].
%           * If running motion compensation, will also create new data
%           types: 'MotionComp' for within-scan, and 'BwScansMotionComp'
%           for between scan. If running both, you can choose to do either
%           between or within-scan first, then the other on top of that.
%           (You may want to remove the intermediate within-scan data type
%           to save space, if it looks like things went well.)
%
%   Also returns the variable ok, which is 1 if everything succeeded and 0
%   otherwise.
%
% EXAMPLE:
%	Suppose we have a session with four functional files, named 'func1.img'
%	to 'func4.img', and an inplane file, 'inplane.img'. All files are
%	single ANALYZE-format images.
%
%	params.inplane = 'inplane.img';
%	for i=1:5, params.functionals{i} = sprintf('func%i.img', i); end
%	mrInit(params);
%
%
% ras, 09/2006.

% PROGRAMMING NOTES:
% This code is intended to improve upon mrInitRet, addressing a few
% concerns:
%
% (1) More input file neutral. While mrInitRet was largely built to use
%     Lucas Center P.mag files, mrInit is intended to allow any files
%     readable by the mrVista 2 mrLoad functions. Specifically,
%     ANALYZE files are supported. Also, it's no longer required that
%     you have the Inplane files be DICOM files in Raw/Anatomy/Inplane.
%     Although consistent naming is recommended, the input anatomy file can
%     also be any format or location.
%
% (2) Scriptable. mrInitRet provided a nice 'wizard' of dialogs, but was
%     extremely hard to automate. This code is intended to be more modular,
%     and not require any user dialogs to run. If the optional 'params'
%     argument is not provided, it will provide a set of dialogs (mrInitGUI)
%     to get them. But otherwise, it runs without further input from the
%     user.
%
% (3) Saves more info from the header files. Things like the corners of the
%     inplane in scanner coordinates were not extracted previously, making
%     it difficult to e.g. label left from right. These are now saved in
%     the mrSESSION file.
%
% (4) Free of several of the bugs that have been cropping up lately, e.g.
%     in EditSession.
%
% (5) Run Motion Compensation / Slice Timing Correction at the front end,
%    so you can leave a session intitializing and have it also do these
%    steps overnight.
% ras, 07/23/07: debugged / slight overhaul to be cleaner, rely more on
% mrLoad and mrSave to actually set the mrSESSION fields.
% ras, 05/08: fixed several bugs in the GUI processing stream for dealing
% with file patterns; the main code also properly tests that the specified
% session directory exists, and cleans up the workspace when it finishes.
%
% Modified by DY on 09/2008 to allow for within then between or between
% then within MC. Changed comments here and in mrInitDefaultParams.m to
% reflect this. Email DY if you would like to see an example wrapper script
% that sets all params.

%%%%% (0) ensure all input parameters are specified
if nargin==0
    % get params interactively
    [params, ok] = mrInitGUI;
    if ~ok, disp('mrInit Aborted.'); return; end

elseif length(varargin)==1 && isstruct(varargin{1})
    % params struct entered
    params = mrInitDefaultParams;
    params = mergeStructures(params, varargin{1});

else
    params = mrInitDefaultParams;

    % param/value pairs specified -- parse
    for i = 1:2:length(varargin)
        params.(varargin{i}) = varargin{i+1};
    end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% (1) cd to session dir; init empty session %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
params.startTime = datestr(now);
fprintf('***** [%s] Initializing Session %s ***** (%s)\n', mfilename, ...
    params.sessionCode, params.startTime);
ensureDirExists(params.sessionDir);
callingDir = pwd;
cd(params.sessionDir);

mrGlobals; %Declared here since we want HOMEDIR to be sessPath

initEmptySession; %Replace this save and then load of mrSESSION with that variable simply passed
% from one to the other
load mrSESSION mrSESSION dataTYPES
mrSESSION = sessionSet(mrSESSION,'description', params.description);
mrSESSION = sessionSet(mrSESSION,'sessionCode',params.sessionCode);
mrSESSION = sessionSet(mrSESSION,'subject',params.subject);
mrSESSION = sessionSet(mrSESSION,'comments',params.comments);
mrSESSION = sessionSet(mrSESSION,'Inplane Path',params.inplane); %Populates the mrSESSION inplane path var
mrSESSION = sessionSet(mrSESSION,'alignment',params.alignment);
mrSESSION = sessionSet(mrSESSION,'Version','2.1');

save mrSESSION mrSESSION -append;
save mrInit_params params   % stash the params in case we crash

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% (2) Load functional data, if it exists      %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if isfield(params,'functionals') && ~isempty(params.functionals)
    if ischar(params.functionals), params.functionals = {params.functionals}; end

    for scan = 1:length(params.functionals)

        func.path = params.functionals{scan};

        %Read in the nifti to the tS struct, then apply the same transform as
        %the inplane data. Then, transfer the necessary components to the
        %local func struct.
        tS = niftiRead(func.path);
        tS = niftiApplyAndCreateXform(tS,'Inplane');

        func.hdr = rmfield(tS, 'data');

        %Store the orientation of the functional data. We will need the
        %anatomical Inplane to have the same orientation.
        [~, func.orientation] = niftiCreateXform(tS,'Inplane');

        %Need to move over:
        %Data
        func.data = niftiGet(tS,'Data');
        %Dims
        func.dims = niftiGet(tS, 'Dim');
        %PixDims
        func.pixdims = niftiGet(tS, 'Pix Dim', 'xyz_units', 'mm', 'time_units', 's');

        % select keepFrames if they're provided
        if isfield(params, 'keepFrames') && ~isempty(params.keepFrames)
            %Put keepFrames into func so that we can save it into mrSESSION
            func.keepFrames = params.keepFrames(scan,:);
        else
            %We will need to create keepFrames if it doesn't exist
            func.keepFrames = [0 -1];
        end

        % assign annotation if it's provided
        if length(params.annotations) >= scan && ...
                ~isempty(params.annotations{scan})
            func.name = params.annotations{scan};
        else
            func.name = [];
        end

        %This call updates dataTYPES as well
        %We will no longer call mrSave
        mrInitInplaneTseries(func,scan);

    end

end

fprintf('[%s]: Finished initializing mrVista session. \t(%s)\n', ...
    mfilename, datestr(now));

%%%%%%%%%%%%%%%%%%%%%%%
% (3)  VOLUME anatomy %
%%%%%%%%%%%%%%%%%%%%%%%
if isfield(params,'vAnatomy') && ~isempty(params.vAnatomy)
    setVAnatomyPath(params.vAnatomy);
end

%%%%%%%%%%%%%%%%%%%%%%%
% (4)  pre-processing %
%%%%%%%%%%%%%%%%%%%%%%%
% update dataTYPES as needed.

INPLANE{1} = initHiddenInplane;

% assign coherence analysis parameters
for s = cellfind(params.coParams)
    coParams = params.coParams{s};
    for f = fieldnames(coParams)'
        dataTYPES.blockedAnalysisParams(s).(f{1}) = coParams.(f{1});
    end
end

% assign GLM analysis parameters
for scan = cellfind(params.glmParams)
    er_setParams(INPLANE{1}, params.glmParams{scan}, scan);
end

% slice timing correction
if params.sliceTimingCorrection==1
    if isfield(params, 'sliceOrder')
        mrSESSION = sessionSet(mrSESSION, 'sliceorder', params.sliceOrder);
        saveSession;
    end
    INPLANE{1} = AdjustSliceTiming(INPLANE{1}, 1:length(sessionGet(mrSESSION, 'functionals')));
    INPLANE{1} = selectDataType(INPLANE{1}, 'Timed');
end

% motion compensation
if params.motionComp > 1
    switch params.motionComp
        case 1, % between scans only
            newDataType = 'BwScansMotionComp';
            if ~existDataType(newDataType), addDataType(newDataType); end
            hI = initHiddenInplane(newDataType);
            [INPLANE{1}, ~] = betweenScanMotComp(INPLANE{1}, hI, params.motionCompRefScan);
            INPLANE{1} = selectDataType(INPLANE{1}, newDataType);

        case 2, % within scans only
            INPLANE{1} = motionCompSelScan(INPLANE{1}, 'MotionComp', ...
                [], params.motionCompRefFrame);

        case 3, % both between and within scans
            motionCompNestaresFull(INPLANE{1}, [], ...
                params.motionCompRefScan, ...
                params.motionCompRefFrame);
            INPLANE{1} = selectDataType(INPLANE{1}, 'MotionComp');
        case 4, % both between and within scans
            motionCompNestaresWithin1st(INPLANE{1}, [], params.motionCompRefScan, params.motionCompRefFrame);
            mcdtName=['MotionComp_RefScan' num2str(params.motionCompRefScan)];
            INPLANE{1} = selectDataType(INPLANE{1}, mcdtName);

    end
end

% group scans, assign parfiles, apply GLM
for scan = cellfind(params.parfile)
    er_assignParfilesToScans(INPLANE{1}, scan, params.parfile(scan));
end

if ~isempty(params.scanGroups)
    for ii = 1:length(params.scanGroups)
        INPLANE{1} = er_groupScans(INPLANE{1}, params.scanGroups{ii}, 2);

        if params.applyGlm==1
            glmParams = er_getParams(INPLANE{1}, params.scanGroups{ii}(1));
            applyGlm(INPLANE{1}, [], params.scanGroups{ii}, glmParams);
        end
    end
end

% apply coherence analysis
if any(params.applyCorAnal > 0)
    INPLANE{1} = computeCorAnal(INPLANE{1}, params.applyCorAnal, 1);
end

% All tasks are now complete
saveSession;
fprintf('***** [%s] Finished Initializing Session %s (%s)*****\n', ...
    mfilename, mrSESSION.sessionCode, datestr(now));
mrvCleanWorkspace;
ok = 1;

cd(callingDir);

return
% /---------------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function mrInitInplaneTseries(mr, scan)

%Taken from mrSave, with the 'save' functionality removed, the rest of the
%data transfer functionality has been retained, however

mrGlobals;

% set header info in mrSESSION.functionals, dataTYPES.scanParmas
if notDefined('scan') || isempty(scan), scan = length(mrSESSION.functionals) + 1; end %#ok<NODEF>
f.PfileName = mr.path;
f.totalFrames = mr.dims(4);

f.firstName = '';  f.lastName = '';
if checkfields(mr, 'info', 'subject')
    sp = strfind(' ', mr.info.subject);
    if ~isempty(sp) % space in name
        f.firstName = mr.info.subject( 1:(sp(1)-1) );
        f.lastName = mr.info.subject( (sp(1)+1):end );
    else
        f.firstName = mr.info.subject;
    end
end

f.date = ''; f.time = '';
if checkfields(mr, 'info', 'date'), f.date = mr.info.date; end
if checkfields(mr, 'info', 'time'), f.time = mr.info.time; end

f.junkFirstFrames = 0; %This always appears to be 0. perhaps remove it?

if mr.keepFrames(2) == -1,
    % if 2nd column of keepframes is -1, keep all frames after drop frames
    nFrames = mr.dims(4) - mr.keepFrames(1);
else
    % if 2nd column of keepframes is +n, keep n frames after drop frames
    nFrames = mr.keepFrames(2);
end

f.nFrames   = nFrames;
f.slices    = 1:mr.dims(3);
f.fullSize  = mr.dims(1:2);
f.cropSize  = mr.dims(1:2);
f.crop      = [1 1; mr.dims(1:2)];
f.voxelSize = mr.pixdims(1:3);
f.effectiveResolution = mr.pixdims(1:3);
f.keepFrames = mr.keepFrames; %Keep Frames will now be udpated in both mrSESSION and dataTYPES
if checkfields(mr, 'info', 'effectiveResolution')
    f.effectiveResolution = mr.info.effectiveResolution;
end
f.framePeriod = mr.pixdims(4);
f.reconParams = mr.hdr;

if scan==1
    mrSESSION = sessionSet(mrSESSION, 'Functionals', f);
    mrSESSION = sessionSet(mrSESSION, 'Functional Orientation', mr.orientation);
else
    mrSESSION = sessionSet(mrSESSION, 'Functionals', ...
        mergeStructures(sessionGet(mrSESSION, 'Functionals', scan-1), f), scan);
end

% Default params, initializing the parameters in dataTYPES

% Copy one field at a time, so we don't get type-mismatch errors.

% scan params
srcScanParams = scanParamsDefaults(mrSESSION, scan, mr.name);
for f = fieldnames(srcScanParams)'
    dataTYPES(1).scanParams(scan).(f{1}) = srcScanParams.(f{1});
end

% blocked analysis params
srcBlockParams = blockedAnalysisDefaults;
for f = fieldnames(srcBlockParams)'
    dataTYPES(1).blockedAnalysisParams(scan).(f{1}) = ...
        srcBlockParams.(f{1});
end

% event analysis params
srcEventParams = er_defaultParams;
for f = fieldnames(srcEventParams)'
    dataTYPES(1).eventAnalysisParams(scan).(f{1}) = ...
        srcEventParams.(f{1});
end

saveSession

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function params = scanParamsDefaults(mrSESSION, scan, annotation)
% Default scan parameters for a new scan.
params.annotation   = annotation;
params.nFrames      = mrSESSION.functionals(scan).nFrames;
params.framePeriod  = mrSESSION.functionals(scan).framePeriod;
params.slices       = mrSESSION.functionals(scan).slices;
params.cropSize     = mrSESSION.functionals(scan).cropSize;
params.PfileName    = mrSESSION.functionals(scan).PfileName;
params.inplanePath  = mrSESSION.functionals(scan).PfileName;
params.keepFrames   = mrSESSION.functionals(scan).keepFrames;
params.parfile      = '';
params.scanGroup            = sprintf('Original: %i',scan);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function params = blockedAnalysisDefaults
% Default values for the blocked analyses.
params.blockedAnalysis       = 1;
params.detrend               = 1;
params.inhomoCorrect         = 1;
params.temporalNormalization = 0;
params.nCycles               = 6;
return
% /-----------------------------------------------------------------/ %


classdef TankToTankConnection < matlab.mixin.SetGet
    %TankToTankConnection Summary of this class goes here
    %   Detailed explanation goes here

    properties
        srcTank LaunchVehicleTank
        tgtTank LaunchVehicleTank
        initFlowRate(1,1) double = 0;
    end

    properties(Dependent)
        lvdData
    end

    methods
        function obj = TankToTankConnection(srcTank, tgtTank)
            if(nargin > 0)
                obj.srcTank = srcTank;
                obj.tgtTank = tgtTank;
            end
        end

        function lvdData = get.lvdData(obj)
            if(not(isempty(obj.srcTank)))
                lvdData = obj.srcTank.stage.launchVehicle.lvdData;
            else
                lvdData = obj.tgtTank.stage.launchVehicle.lvdData;
            end
        end

        function nameStr = getName(obj)
            if(isempty(obj.srcTank))
                srcNameStr = '<External>';
            else
                srcNameStr = obj.srcTank.name;
            end

            if(isempty(obj.tgtTank))
                tgtNameStr = '<External>';
            else
                tgtNameStr = obj.tgtTank.name;
            end

            nameStr = sprintf('%s to %s (%.3f mT/s)', srcNameStr, tgtNameStr, obj.initFlowRate);
        end

        function tf = isInUse(obj)
            tf = obj.lvdData.usesTankToTankConn(obj);
        end
    end

    methods(Static)
        function tankMassDots = getTankMassFlowRatesFromTankToTankConnections(tankStates, tankStatesMasses, t2tConnStates)
            activeT2TConnStates = t2tConnStates([t2tConnStates.active]);

            tankMassDots = zeros(size(tankStates));
            tankMassDots = tankMassDots(:);

            if(isempty(activeT2TConnStates))
                return;
            end

            tanks = [tankStates.tank];

            for(i=1:length(activeT2TConnStates))
                t2tConnState = activeT2TConnStates(i);

                srcTank = t2tConnState.conn.srcTank;
                if(not(isempty(srcTank)))
                    srcBool = tanks == srcTank;
                    if(any(srcBool))
                        srcTankState = tankStates(srcBool);
                        srcStageState = srcTankState.stageState.active;
                        srcIsTank = true;
                    else
                        srcIsTank = true;
                        srcStageState = false;
                    end
                else
                    srcStageState = true;
                    srcIsTank = false;
                end

                tgtTank = t2tConnState.conn.tgtTank;
                if(not(isempty(tgtTank)))
                    tgtBool = tanks == tgtTank;
                    if(any(tgtBool))
                        tgtTankState = tankStates(tgtBool);
                        tgtStageState = tgtTankState.stageState.active;
                        tgtIsTank = true;
                    else
                        tgtStageState = false;
                        tgtIsTank = true;
                    end
                else
                    tgtStageState = true;
                    tgtIsTank = false;
                end

                if(srcStageState && tgtStageState)
                    flowRate = t2tConnState.flowRate;

                    if(srcIsTank && tgtIsTank)
                        if(tankStatesMasses(srcBool) > 0)
                            tankMassDots(srcBool) = tankMassDots(srcBool) - flowRate;
                            tankMassDots(tgtBool) = tankMassDots(tgtBool) + flowRate;
                        end

                    elseif(srcIsTank && tgtIsTank == false)
                        if(tankStatesMasses(srcBool) > 0)
                            tankMassDots(srcBool) = tankMassDots(srcBool) - flowRate;
                        end

                    elseif(srcIsTank == false && tgtIsTank)
                        tankMassDots(tgtBool) = tankMassDots(tgtBool) + flowRate;
                    end
                end
            end
        end
    end
end


classdef ButtonBox < uix.Box
    %uix.ButtonBox  Button box base class
    %
    %  uix.ButtonBox is a base class for containers that lay out buttons.

    %  Copyright 2009-2015 The MathWorks, Inc.
    %  $Revision: 1165 $ $Date: 2015-12-06 03:09:17 -0500 (Sun, 06 Dec 2015) $

    properties( Access = public, Dependent, AbortSet )
        ButtonSize % button size, in pixels
        HorizontalAlignment % horizontal alignment [left|center|right]
        VerticalAlignment % vertical alignment [top|middle|bottom]
    end

    properties( Access = protected )
        ButtonSize_ = [60 20] % backing for ButtonSize
        HorizontalAlignment_ = 'center' % backing for HorizontalAlignment
        VerticalAlignment_ = 'middle' % backing for VerticalAlignment
    end

    methods

        function value = get.ButtonSize( obj )

            value = obj.ButtonSize_;

        end % get.ButtonSize

        function set.ButtonSize( obj, value )

            % Check
            assert( isa( value, 'double' ), 'uix:InvalidPropertyValue', ...
                'Property ''ButtonSize'' must be of type double.' )
            assert( isequal( size( value ), [1 2] ), ...
                'uix:InvalidPropertyValue', ...
                'Size of property ''ButtonSize'' must by 1-by-2.' )
            assert( all( isreal( value ) ) && ~any( isinf( value ) ) && ...
                ~any( isnan( value ) ) && ~any( value <= 0 ), ...
                'uix:InvalidPropertyValue', ...
                'Elements of property ''ButtonSize'' must be real, finite and positive.' )

            % Set
            obj.ButtonSize_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.ButtonSize

        function value = get.HorizontalAlignment( obj )

            value = obj.HorizontalAlignment_;

        end % get.HorizontalAlignment

        function set.HorizontalAlignment( obj, value )

            % Check
            assert( ischar( value ), 'uix:InvalidPropertyValue', ...
                'Property ''HorizontalAlignment'' must be a string.' )
            assert( any( strcmp( value, {'left';'center';'right'} ) ), ...
                'Property ''HorizontalAlignment'' must be ''left'', ''center'' or ''right''.' )

            % Set
            obj.HorizontalAlignment_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.HorizontalAlignment

        function value = get.VerticalAlignment( obj )

            value = obj.VerticalAlignment_;

        end % get.VerticalAlignment

        function set.VerticalAlignment( obj, value )

            % Check
            assert( ischar( value ), 'uix:InvalidPropertyValue', ...
                'Property ''VerticalAlignment'' must be a string.' )
            assert( any( strcmp( value, {'top';'middle';'bottom'} ) ), ...
                'Property ''VerticalAlignment'' must be ''top'', ''middle'' or ''bottom''.' )

            % Set
            obj.VerticalAlignment_ = value;

            % Mark as dirty
            obj.Dirty = true;

        end % set.VerticalAlignment

    end % accessors

end % classdef