function Rob = map2rob(Rob)
% MAP2ROB  Update Rob structure from the Map information.
%   ROB = MAP2ROB(ROB) updates the structure ROB to reflect the information
%   contained in the golbal map Map.
%
%   See also UPDATEFRAME.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

global Map

% normalize quaternion - mean and cov
[Map.x(Rob.frame.r(4:7)), NQ_q] = normvec(Map.x(Rob.frame.r(4:7)),1);
Map.P(Rob.frame.r(4:7),Map.used) = NQ_q*Map.P(Rob.frame.r(4:7),Map.used);
Map.P(Map.used,Rob.frame.r(4:7)) = Map.P(Map.used,Rob.frame.r(4:7))*NQ_q';

% means
Rob.state.x = Map.x(Rob.state.r);
Rob.frame.x = Map.x(Rob.frame.r);

Rob.frame   = updateFrame(Rob.frame);

% covariances
% Rob.state.P = Map.P(Rob.state.r,Rob.state.r);
% Rob.frame.P = Map.P(Rob.frame.r,Rob.frame.r);

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function flatten_dir(in_dir, out_dir, sep_symbol)
% flatten directory (1 level only)

if ~exist('sep_symbol','var'),
  sep_symbol = '_';
end

if ~exist(out_dir,'dir'),
  mkdir(out_dir);
end

contents = dir(in_dir);
d_list = {contents.name};
d_list = setdiff(d_list([contents.isdir]),{'.','..'});

for d_name = d_list,
  d_name = d_name{1};
  % d_name = fullfile(d_name, 'allFrames');
  contents = dir(fullfile(in_dir,d_name));
  f_list = {contents.name};
  f_list = f_list(~[contents.isdir]);
  for f_name = f_list,
    f_name = f_name{1};
    copyfile(fullfile(in_dir,d_name,f_name), ...
      fullfile(out_dir,sprintf('%s%s%s',strrep(d_name,filesep,sep_symbol),sep_symbol,f_name)));
end

end


% pop_rmdat() - Remove continuous data around specific events
%
% Usage:
%   >> OUTEEG = pop_rmdat( EEG); % pop-up a data entry window
%   >> OUTEEG = pop_rmdat( EEG, typerange, timelimits, invertselection);
%
% Graphic interface:
%   "Time-locking event type(s)" - [edit box] Select 'Edit > Event values'
%                to see a list of event.type values; else use the push button.
%                To use event types containing spaces, enter in single-quotes.
%   "..."      - [push button] scroll event types.
%   "Time limits" - [edit box] epoch latency range [start, end] in seconds relative
%                to the event type latency.
%
% Inputs:
%   EEG        - Input dataset. Data may already be epoched; in this case,
%                extract (shorter) subepochs time locked to epoch events.
%   typerange  - Cell array of event types to time lock to.
%                (Note: An event field called 'type' must be defined in
%                the 'EEG.event' structure).
%   timelimits - Epoch latency limits [start end] in seconds relative to the time-locking event
%                {default: [-1 2]}%
%   invertselection - [0|1] Invert selection {default:0 is no}
%
% Outputs:
%   OUTEEG     - output dataset
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, 2009-

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [EEG, com] = pop_rmdat( EEG, events, timelims, invertsel );

if nargin < 1
   help pop_rmdat;
	return;EEG = pop_rmdat( EEG,  {  'animal'  'bug' 'response'     },[-1 1] ,0);

end;
com = '';

if isempty(EEG.event)
    error( [ 'No event. This function removes data' 10 'based on event latencies' ]);
end;
if isempty(EEG.trials)
    error( [ 'This function only works with continuous data' ]);
end;
if ~isfield(EEG.event, 'latency'),
    error( 'Absent latency field in event array/structure: must name one of the fields ''latency''');
end;

if nargin < 3
	% popup window parameters
	% -----------------------
   promptstr    = { strvcat('Time-locking event type(s) ([]=all):', ...
                    'Select ''Edit > Event values'' to see type values.'), ...
                    'Epoch limits [start, end] in seconds:', ...
                    'Name for the new dataset:', ...
					'Out-of-bounds EEG rejection limits ([min max], []=none):'  };

   cbevent = ['if ~isfield(EEG.event, ''type'')' ...
				   '   errordlg2(''No type field'');' ...
				   'else' ...
                   '   tmpevent = EEG.event;' ...
                   '   if isnumeric(EEG.event(1).type),' ...
				   '        [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ...
				   '   else,' ...
                   '        [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ...
                   '   end;' ...
				   '   if ~isempty(tmps)' ...
				   '       set(findobj(''parent'', gcbf, ''tag'', ''events''), ''string'', tmpstr);' ...
				   '   end;' ...
				   'end;' ...
				   'clear tmps tmpv tmpstr tmpevent tmpfieldnames;' ];

   geometry = { [2 1 1.2] [2 1 1.2] };
   uilist = { { 'style' 'text'       'string' 'Event type(s) ([]=all)' } ...
              { 'style' 'edit'       'string' '' 'tag' 'events' } ...
              { 'style' 'pushbutton' 'string' '...' 'callback' cbevent } ...
              { 'style' 'text'       'string' 'Time limits [start, end] in sec.' } ...
              { 'style' 'edit'       'string' '-1 1' } ...
              { 'style' 'popupmenu'  'string' 'Keep selected|Remove selected' } };

   result = inputgui( geometry, uilist, 'pophelp(''pop_rmdat'')', 'Remove data portions around events - pop_rmdat()');
   if length(result) == 0 return; end;

   if strcmpi(result{1}, '[]'), result{1} = ''; end;
   if ~isempty(result{1})
       if strcmpi(result{1}(1),'''')   % If event type appears to be in single-quotes, use comma
                                       % and single-quote as delimiter between event types. toby 2.24.2006
                                       % fixed Arnaud May 2006
            events = eval( [ '{' result{1} '}' ] );
       else events = parsetxt( result{1});
       end;
   else events = {};
   end
   timelims = eval( [ '[' result{2} ']' ] );
   invertsel = result{3}-1;

end;

tmpevent = EEG.event;
alltypes = { tmpevent.type };

% compute event indices
% ---------------------
allinds = [];
for index = 1:length(events)
    inds = strmatch(events{index},alltypes, 'exact');
    allinds = [allinds(:); inds(:) ]';
end;
allinds = sort(allinds);
if isempty(allinds)
    disp('No event found');
    return;
end;

% compute time limits
% -------------------
array = [];
tmpevent = EEG.event;
bnd = strmatch('boundary', lower({tmpevent.type }));
bndlat = [ tmpevent(bnd).latency ];
for bind = 1:length(allinds)
    evtlat = EEG.event(allinds(bind)).latency;
    evtbeg = evtlat+EEG.srate*timelims(1);
    evtend = evtlat+EEG.srate*timelims(2);
    if any(bndlat > evtbeg & bndlat < evtend)
        % find the closer upper and lower boundaries
        bndlattmp = bndlat(bndlat > evtbeg & bndlat < evtend);
        diffbound = bndlattmp-evtlat;
        allneginds = find(diffbound < 0);
        allposinds = find(diffbound > 0);
        if ~isempty(allneginds), evtbeg = bndlattmp(allneginds(1)); end;
        if ~isempty(allposinds), evtend = bndlattmp(allposinds(1)); end;
        fprintf('Boundary found: time limits for event %d reduced from %3.2f to %3.2f\n', allinds(bind), ...
            (evtbeg-evtlat)/EEG.srate, (evtend-evtlat)/EEG.srate);
    end
    if ~isempty(array) && evtbeg < array(end)
        array(end) = evtend;
    else
        array = [ array; evtbeg  evtend];
    end;
end;
array

if ~isempty(array) && array(1) < 1, array(1) = 1; end;
if ~isempty(array) && array(end) > EEG.pnts, array(end) = EEG.pnts; end;
if isempty(array)
    disp('No event found');
    return;
end;

if invertsel
    EEG = pop_select(EEG, 'notime', (array-1)/EEG.srate);
else
    EEG = pop_select(EEG, 'time', (array-1)/EEG.srate);
end;

% generate output command
% -----------------------
com = sprintf('EEG = pop_rmdat( EEG, %s);', vararg2str( { events timelims invertsel } ));


% Init Script
% Remarks:
%   1.  sa
% TODO:
% 	1.  ds
% Release Notes
% - 1.0.000     08/11/2016  Royi Avital
%   *   First release.
%

%% General Parameters
close('all');
clear();
clc();

% set(0, 'DefaultFigureWindowStyle', 'docked');
% defaultLoosInset = get(0, 'DefaultAxesLooseInset');
% set(0, 'DefaultAxesLooseInset', [0.05, 0.05, 0.05, 0.05]);

figPosSmall     = [100, 100, 400, 300];
figPosMedium    = [100, 100, 800, 600];
figPosLarge     = [100, 100, 960, 720];
figPosDefault   = [100, 100, 560, 420];

fontSizeTitle   = 14;
fontSizeAxis    = 12;
fontSizeString  = 12;

lineWidthThin   = 1;
lineWidthNormal = 3;
lineWidthThick  = 4;

markerSizeSmall     = 4;
markerSizeNormal    = 8;
markerSizeLarge     = 10;

% https://www.mathworks.com/help/matlab/graphics_transition/why-are-plot-lines-different-colors.html
% https://www.mathworks.com/matlabcentral/answers/160332
mColorOrder = get(groot, 'DefaultAxesColorOrder');

randomNumberStream  = RandStream('mlfg6331_64', 'NormalTransform', 'Ziggurat');
subStreamNumber     = round(sum(clock()));
% subStreamNumber     = 162;
subStreamNumber     = 20;
set(randomNumberStream, 'Substream', subStreamNumber);
RandStream.setGlobalStream(randomNumberStream);

FALSE   = 0;
TRUE    = 1;

OFF     = 0;
ON      = 1;


function CreateEulerPanel(handles)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

    %Euler Panel
    handles.eulerPanel = uipanel('Parent',handles.toolPanel,'Units','normalize','FontSize',10,'Title','Registration Parameters',...
                                    'Tag','eulerPanel','Clipping','off',...
                                    'Position',[0 0 1 1],...
                                    'Visible','on');
    dx = 0; dy = 80;
    h380 = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[19.5308641975309+dx 214.470588235294+dy 115.086419753087 19],...
    'String','Rotation Scale:',...
    'Style','text',...
    'Tag','text97');

    handles.Euler_RS = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[143.395061728395+dx 210+dy 77.0493827160494 24.5882352941177],...
    'String','1.0',...
    'Style','edit',...
    'Tag','Euler_RS');

    h382 = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[19.5308641975309+dx 179.823529411765+dy 115.086419753087 19],...
    'String','Translation Scale:',...
    'Style','text',...
    'Tag','text98');

    handles.Euler_TS = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[143.395061728395+dx 175.352941176471+dy 77.0493827160494 23.4705882352941],...
    'String','0.001',...
    'Style','edit',...
    'Tag','Euler_TS');

    h384 = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[10.7530864197531+dx 146.294117647059+dy 123.864197530864 20.1176470588235],...
    'String','Initial Angle(Degree):',...
    'Style','text',...
    'Tag','text99');

    handles.Euler_InitAngle = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[143.395061728395+dx 142.941176470588+dy 77.0493827160494 23.4705882352941],...
    'String','0',...
    'Style','edit',...
    'Tag','Euler_InitAngle');

    handles.Euler_minstep = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[143.395061728395+dx 99.3529411764706+dy 76.0740740740741 26.8235294117647],...
    'String','0.01',...
    'Style','edit',...
    'Tag','Euler_minstep');

    handles.Euler_maxstep = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[143.395061728395+dx 62.4705882352942+dy 76.0740740740741 25.7058823529412],...
    'String','1.0',...
    'Style','edit',...
    'Tag','Euler_maxstep');

    h388 = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[19.5308641975309+dx 106.058823529412+dy 115.086419753087 19],...
    'String','Minimum Step:',...
    'Style','text',...
    'Tag','text100');

    h389 = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[19.5308641975309+dx 69.1764705882353+dy 115.086419753087 19],...
    'String','Maximum Step:',...
    'Style','text',...
    'Tag','text101');

    h390 = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[19.5308641975309+dx 31.1764705882353+dy 115.086419753087 19],...
    'String','Iteration Number :',...
    'Style','text',...
    'Tag','text102');

    handles.Euler_IterNum = uicontrol(...
    'Parent',handles.eulerPanel,...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[143.395061728395+dx 25.5882352941177+dy 76.0740740740741 25.7058823529412],...
    'String','200',...
    'Style','edit',...
    'Tag','Euler_IterNum');

    guidata(handles.mainframe, handles);

end


function [diet] = makeDietFormatConsistant(model,diet)
% This function takes a diet input and checks it for formatting consisteny
% for input into setFoodConstraints
%
% USAGE:
%
%   [diet] = makeDietFormatConsistant(model,diet)
%
% INPUTS
%   model:             A COBRA model
%
%   diet:            A nx2 cell array containing n dietary components and
%                    the corresponding flux
% OUTPUT
%   diet:           A diet of consistent format for setFoodConstraints
%
% Authors:
%   Bronson R. Weston 2022

load fdTable.mat
load fdCategoriesTable.mat
foods=[fdTable.Properties.VariableNames(2:end),fdCategoriesTable.Properties.VariableNames(2:end)];
for i=1:length(diet(:,1))
    if ~isempty(find(strcmp(foods,diet{i,1})))
        diet{i,1}=['Food_EX_',diet{i,1},'[d]'];
    elseif ~isempty(find(strcmp(model.rxns,['Diet_EX_' diet{i,1} '[d]'])))
                disp('C')
        diet{i,1}=['Diet_EX_',diet{i,1},'[d]'];
    end
end
end


classdef MetaboliteUtil
    methods (Static)
        function localizedMetabolites = localizeMetabolites(sim, metabolites)
            mets = sim.state('Metabolite');
            nMets = numel(mets.wholeCellModelIDs);
            nComp = sim.compartment.count;
            cIdx = sim.compartment.cytosolIndexs;
            mIdx = sim.compartment.membraneIndexs;
            hMetIdxs = mets.hydrophobicIndexs;

            localizedMetabolites = zeros(nMets, nComp);
            localizedMetabolites(:, cIdx) = metabolites;
            localizedMetabolites(hMetIdxs, mIdx) = localizedMetabolites(hMetIdxs, cIdx);
            localizedMetabolites(hMetIdxs, cIdx) = 0;
        end
    end
end


function vw = refreshFlatLevelView(vw,recomputeFlag)
%
% vw = refreshFlatLevelView(vw,recomputeFlag);
%
% This is a version of refreshView that works on the
% Flat Across-Gray-Levels View. There are 2 main reasons
% I'm breaking it off into a separate function:
%
%   1) It allows for working off a mosaic of several layers
%      at once, which may be useful for things like inplane
%      views but would also make the refreshView code confusing;
%
%   2) It's still being tested out, so it's structure is likely
%      to change.
%
% But basically, it refreshes the flat multi view interface
% based off the settings in the UI controls.
%
% ras, 08/04, off refreshView

if ~exist('recomputeFlag','var'), recomputeFlag=1; end

% Make this one the selectedInplane, selectedVolume, or selectedFlat
if iscell(vw), selectView(vw); end

% Set window title
% Check for sessionCode - this should have been set in openxxxxWindow but
% some other programs (like mrAlign) don't beshave properly.
if (~isfield(vw,'sessionCode'))
    vw.sessionCode=pwd;
end

ui = viewGet(vw,'ui');

% Get colormap, numGrays, numColors and clipMode
str = [vw.ui.displayMode,'Mode'];

% Make sure the phMode, or ampMode structure exists.  If not, then set them
% to the default values.
if ~checkfields(vw,'ui',str), vw=resetDisplayModes(vw); end

% Here is the mode, get the relevant parameters.
modeStr=['vw.ui.',str];
mode = eval(modeStr);
cmap = mode.cmap;
numGrays = mode.numGrays;
numColors = mode.numColors;
clipMode = mode.clipMode;

% get/set flat rotations
[rotations,flipLR] = getFlatRotations(vw);

if (~(recomputeFlag==2)) % Only set when the hemisphere changes
    % Retreive the imageRotation from the UI
    thisRotation = getImageRotate(vw);

    % Set the corresponding value in degrees in FLAT.imageRotateDegrees
    rotations(viewGet(vw, 'Current Slice')) = thisRotation*(180/pi);
end

vw = setFlatRotations(vw,rotations,flipLR);

% recompute the image if selected
if (recomputeFlag | isempty(vw.ui.image))
    vw = recomputeFlatLevelImage(vw);
end

% Select the window
set(0,'CurrentFigure',vw.ui.windowHandle);

% Update annotation string
set(vw.ui.annotationHandle,'string',annotation(vw,getCurScan(vw)));

% Display final image
dispMode = sprintf('%sMode',viewGet(vw,'displayMode'));
cmap = vw.ui.(dispMode).cmap;
imshow(vw.ui.image);
colormap(cmap);

% Draw colorbar
if isempty(vw.ui.cbarRange)
    setColorBar(vw,'off',[numGrays+1,numGrays+numColors]);
else
    setColorBar(vw,'on',[numGrays+1,numGrays+numColors]);
end

% Draw ROIs
if vw.ui.showROIs > 0,     drawROIsMontage(vw);
elseif vw.ui.showROIs < 0, drawROIsPerimMontage(vw);
end

return


function title = p09_title ( )

%*****************************************************************************80
%
%% P09_TITLE returns the title of problem P09.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, the title of the problem.
%
  title = 'Problem 9, Enright and Pryce #B4';

  return
end


classdef chebguiExporter
%CHEBGUIEXPORTER   Class to export a problem from CHEBGUI.
%   This is a an abstract class that defines interfaces for export problems from
%   CHEBGUI to .m-files, to the workspace, or to a .chebgui file. It is not
%   intended to be called directly by the end user.
%
% See also CHEBGUI, CHEBGUIBVPEXPORTER, CHEBGUIEIGEXPORTER, CHEBGUIPDEEXPOERTER.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DEVELOPER NOTE:
%   The CHEBGUIEXPORTER class defines a number of abstract methods, used to
%   export problems from CHEBGUI. In v4, this functionality used to live in the
%   @chebgui folder, but to increase modularity, it has been spun off to its own
%   class and subclasses.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% ABSTRACT METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    properties ( Abstract = true )

        % Default file name to be saved to
        defaultFileName

        % Description of exported .m files
        description

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% ABSTRACT STATIC METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Abstract = true, Static = true )

        % Extract information from the CHEBGUI object to a struct:
        expInfo = exportInfo(guifile)

        % Print problem description:
        printDescription(fid, expInfo)

        % Print options for solving the problem:
        printOptions(fid, expInfo)

        % Print lines for setting up the problem:
        printSetup(fid, expInfo, guifile)

        % Print the actual lines for calling the solver method:
        printSolver(fid, expInfo)

        % Print steps taken after the solver finishes:
        printPostSolver(fid, expInfo)

        % Export to a .mat-file
        toMat(handles)

        % Export to workspace
        toWorkspace(handles)

        % Export to workspace, solution only
        toWorkspaceSolutionOnly(handles)

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CONCRETE METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = false )

        function toFile(exporter, guifile, fileName, pathName)
        %TOFILE   Export a CHEBGUI to an m-file
        %   TOFILE(EXPORTER, GUIFILE, FILENAME, PATHNAME) exports the CHEBGUI
        %   object GUIFILE to the file 'PATHNAME/FILENAME' using the
        %   CHEBGUIEXPORTER object EXPORTER (of BVP, EIG, or PDE kind).

        % Concatenate the pathName and the fileName to get the full path:
        fullFileName = fullfile(pathName, fileName);

        try
            % Open a stream to write to a file:
            fid = fopen(fullFileName, 'wt');

            % Extract the necessary info for export to an .m file from the
            % GUIFILE object:
            expInfo = exporter.exportInfo(guifile);

            % Write the header information:
            writeHeader(exporter, fid, fileName)

            % Print description of the problem:
            exporter.printDescription(fid, expInfo)

            % Print the problem set-up:
            exporter.printSetup(fid, expInfo, guifile)

            % Print the options set-up:
            exporter.printOptions(fid, expInfo)

            % Print the solution step:
            exporter.printSolver(fid, expInfo)

            % Print the post-solution process:
            exporter.printPostSolver(fid, expInfo)

            % Close the file writing stream:
            fclose(fid);
        catch ME
            % Make sure to tidy up first
            fclose(fid);

            % Rethrow the error:
            rethrow(ME)
        end

        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CONCRETE STATIC METHODS
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = true )
        function obj = constructor(type)
        %CONSTRUCTOR   Constructor for the CHEBGUIEXPORTER class.
        %   OBJ = CONSTRUCTOR(TYPE), where TYPE = 'bvp', 'eig' or 'pde' returns
        %   an object that is a concrete implementation of CHEBGUIEXPORTER
        %   object OBJ. The type of OBJ is determined by the TYPE input
        %   argument.
        %
        %   This method allows one to construct concrete subclasses of the
        %   CHEBGUIEXPORTER class.

            % Return the desired type of CHEBGUIEXPORTER
            switch type
                case 'bvp'
                    obj = chebguiExporterBVP;

                case 'eig'
                    obj = chebguiExporterEIG;

                case 'ivp'
                    obj = chebguiExporterIVP;

                case 'pde'
                    obj = chebguiExporterPDE;

                otherwise
                    error('CHEBFUN:CHEBGUIEXPORTER:chebguiExporter:constructor', ...
                        'Unknown type for CHEBGUIEXPORTER constructor.')
            end

        end

        function toChebgui(guifile)
        %TOCHEBGUI   Export CHEBGUI to a CHEBGUI object in the workspace.

            % Setup for input dialog
            prompt = 'Enter the name of the chebgui variable:';
            name = 'Export GUI';
            numlines = 1;
            defaultAnswer ='chebg';
            options.Resize ='on';
            options.WindowStyle ='modal';

            % Get user input
            answer = inputdlg(prompt, name, numlines, {defaultAnswer}, options);

            % If user did not press cancel, assign to a variable in the base
            % workspace.
            if ( ~isempty(answer) )
                assignin('base', answer{1}, guifile);
            end
        end

        function str = prettyPrintFevalString(str, varnames)
        %PRETTYPRINTFEVALSTRING   Tidy up strings printed to .m files.

            % Do various string manipulations to make the output look nicer.
            for k = 1:numel(varnames)
                oldstr = ['feval(' varnames{k} ','];
                newstr = [varnames{k} '('];
                str = strrep(str, oldstr, newstr);
                oldstr = [varnames{k} '(''end'''];
                newstr = [varnames{k} '(end'];
                str = strrep(str, oldstr, newstr);
                oldstr = [varnames{k} '(''right'''];
                newstr = [varnames{k} '(end'];
                str = strrep(str, oldstr, newstr);
                oldstr = [varnames{k} '(''start'''];
                newstr = [varnames{k} '(' varnames{k} '.ends(1)'];
                str = strrep(str, oldstr, newstr);
                oldstr = [varnames{k} '(''left'''];
                newstr = [varnames{k} '(' varnames{k} '.ends(1)'];
                str = strrep(str, oldstr, newstr);
            end

        end

        function disc = discOption(isPeriodic, dom, opt)
            % Do we want to use TRIGCOLLOC for the discretization? This will be
            % the case if we're solving a periodic problem, and have
            % 'collocation' specified as the discretization option. However, we
            % don't want to use TRIGCOLLOC if there are breakpoints in the
            % domain.
            if ( isPeriodic && strcmp(opt, 'collocation') &&  ...
                    ( length(str2num(dom)) == 2 ) )
                disc = 'periodic';
            else
                disc = opt;
            end
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CONCRETE PROTECTED METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = protected )

        function writeHeader(e, fid, filename)
            %WRITEHEADER   The first few lines of exported .m-files.
            %
            % Inputs:
            %   E:          a CHEBGUIEXPORT object
            %   FID:        a valid file ID
            %   FILENAME:   name of the file being written to

            % Access usernames in different ways, depending on whether are
            % running on PCs or not:
            if ( ispc )
                userName = getenv('UserName');
            else
                userName = getenv('USER');
            end

            % Print first few lines of the .m-file:
            fprintf(fid, ['%%%% %s -- an executable m-file for solving ', ...
                '%s\n'], filename, e.description);
            fprintf(fid, ['%% Automatically created in CHEBGUI ', ...
                'by user %s.\n'], userName);
            fprintf(fid, '%% Created on %s', ...
                datestr(now, 'mmmm dd, yyyy at HH:MM.\n\n'));

            fprintf(fid, '%%%% Problem description.\n');

        end

    end

end


function DoPostScan(Simuh)

global VCtl
global VImg
global VCoi

DoUpdateInfo(Simuh,'Scan is complete!');
set(Simuh.TimeWait_text,'String', ['Est. Time Left :  ' '~' ' : ' '~' ' : ' '~']);

%% Signal Post-Processing
%  Add noise
DoAddNoise;

%% Image reconstruction
if strcmp(VCtl.AutoRecon,'on')

    %  Do image reconstruction
    DoUpdateInfo(Simuh,'Reconstructing images...');
    ExecFlag=DoImgRecon(Simuh);
    if ExecFlag==0
        error('Image recon is incomplete!');
    end
    DoUpdateInfo(Simuh,'Image recon is complete.');

    %  Enable channel selection
    channel = {'SumofMagn';'SumofCplx'};
    for i = 1:VCoi.RxCoilNum
        channel{i+2} = i;
    end
    set(Simuh.Channel_popupmenu,'String',channel);
    set(Simuh.Channel_popupmenu,'Enable','on');

    %  Enable echo selection
    echo = {};
    for i = 1:size(VImg.Mag,5)
        echo{i} = i;
    end
    set(Simuh.Echo_popupmenu,'String',echo);
    set(Simuh.Echo_popupmenu,'Enable','on');

    %  Output image display
    set(Simuh.Channel_popupmenu,'Value', 1);
    set(Simuh.Echo_popupmenu,'Value', 1);
    Simuh=guidata(Simuh.SimuPanel_figure);
    Img = sum(VImg.Mag, 4); % show SumofMagn
    Simuh.Img = Img(:,:,:,1); % show first echo
    Simuh.IV=struct(...
        'Slice',ceil(VCtl.SliceNum/2),...
        'C_lower',min(min(min(Simuh.Img))),...
        'C_upper',max(max(max(Simuh.Img))),...
        'Axes','off',...
        'Grid','off',...
        'Color_map','Gray'...
        );
    DoUpdateImage(Simuh.Preview_axes,Simuh.Img,Simuh.IV);
    set(Simuh.Preview_uipanel,'Title',['Preview : Series' num2str(Simuh.ScanSeriesInd)]);
    [row,col,layer]=size(Simuh.Img);
    if layer==1
        set(Simuh.Preview_slider,'Enable','off');
    else
        set(Simuh.Preview_slider,'Enable','on');
        set(Simuh.Preview_slider,'Min',1,'Max',layer,'SliderStep',[1/layer, 4/layer],'Value',ceil(layer/2));
    end
    guidata(Simuh.SimuPanel_figure, Simuh);

    % Saving output
    DoUpdateInfo(Simuh,'Saving recon images & data & info...');
    DoSaveOutput(Simuh);
    DoUpdateInfo(Simuh,'Image data saving is complete!');

else
    % Saving output
    TmpVImg = VImg;
    VImg = []; % clear VImg
    DoUpdateInfo(Simuh,'Saving signal data & info...');
    DoSaveOutput(Simuh);
    DoUpdateInfo(Simuh,'Signal data saving is complete!');
    VImg = TmpVImg;

end

end


function [DAT, StudyTable] = struct2canlab_dataset(data_struct)
% Take an ad hoc data structure data_struct and return a Table format
% object (StudyTable) and a canlab_dataset object DAT.
%
% - field names become variable names
% - Column vectors of numbers or text becomes Subj_Level data
% - Cell vectors containing column vectors of trial-level numeric data become Event_level data
% - Number of elements in vector stored in each field should match num. observations (subjects) for Subj_level array data
% - Trial-level data should contain same-length vectors for all variables for a given subject
%
% See also struct2table and table2canlab_dataset

N = fieldnames(data_struct);

% Empty structures to sort into
CELLS = struct();
COLUMNS = struct();

for i = 1:length(N)

    myvar = data_struct.(N{i});

    % Try to enforce columnar orientation
    if ~iscolumn(myvar), myvar = myvar'; end

    % If still not a column, skip this (matrix?)
    if ~iscolumn(myvar), continue; end

    if iscell(myvar)

        if all(cellfun(@length, myvar) == 1) && ~any(cellfun(@ischar, myvar))
            % all single values, really numbers
            myvar = cat(1, myvar{:});
            COLUMNS.(N{i}) = myvar;
        else
            CELLS.(N{i}) = myvar;
        end

    else
        % Text or event-level data
        COLUMNS.(N{i}) = myvar;

    end

end

%% Get sizes and remove odd-sized

CELLS = remove_odd_sized(CELLS);

COLUMNS = remove_odd_sized(COLUMNS);

% ------------------------------------------------------------------------

%% Make table

StudyTable = struct2table(COLUMNS);

%% Initialize canlab_dataset
% Deal with subject-level data in matrix first

DAT = table2canlab_dataset(StudyTable);

%% Add text data

DAT = add_text_data_from_CELLS(DAT, CELLS);

%% Add event-level data from cells

CELLS = remove_text_data_from_CELLS_struct(DAT, CELLS);

N = fieldnames(CELLS);
nobs = length(CELLS.(N{1}));

% Build array of event-level data
% Deal data from each of nobs into a matrix of vars for each obs
XX = cell(1, nobs);

for i = 1:length(N)

    myvar = CELLS.(N{i});
    XXnames(1, i) = N(i);

    for j = 1:nobs

        datatoadd =  myvar{j};

        if ~iscolumn(datatoadd), datatoadd = datatoadd'; end
        if ~iscolumn(datatoadd), continue; end

        if ~isempty(XX{j}) && size(XX{j}, 1) ~= size(datatoadd, 1)
            continue
        end

        XX{j}(:, i) = datatoadd;

    end

end

DAT.Event_Level.names = XXnames;
DAT.Event_Level.data = XX;
DAT.Event_Level.type = repmat({'numeric'}, 1, length(XXnames));

end % function

function CELLS = remove_odd_sized(CELLS)

N = fieldnames(CELLS);

for i = 1:length(N)

    cellsize(i) = size(CELLS.(N{i}), 1);

end

cellmode = mode(cellsize);
cellmode = cellmode(1);

wh_omit = cellsize ~= cellmode;

for i = 1:length(N)

    if wh_omit(i)

        CELLS = rmfield(CELLS, N{i});

    end

end

end

function DAT = add_text_data_from_CELLS(DAT, CELLS)

nobs = 0;
if ~isempty(DAT.Subj_Level.data), nobs = size(DAT.Subj_Level.data, 1); end

N = fieldnames(CELLS);

for i = 1:length(N)

    cellsize = size(CELLS.(N{i}), 1);

    % Skip if Subj_level nobs is defined and this does not match
    if nobs && cellsize ~= nobs
        continue
    end

    istext = all(cellfun(@ischar, CELLS.(N{i})));

    if istext

        nextvar = max(size(DAT.Subj_Level.data, 2), size(DAT.Subj_Level.textdata, 2));

        DAT.Subj_Level.textdata(:, nextvar) = CELLS.(N{i});
        DAT.Subj_Level.names(nextvar) = N(i);
        DAT.Subj_Level.type(nextvar) = {'text'};

    end

end

end

function CELLS = remove_text_data_from_CELLS_struct(DAT, CELLS)

nobs = 0;
if ~isempty(DAT.Subj_Level.data), nobs = size(DAT.Subj_Level.data, 1); end

N = fieldnames(CELLS);

for i = 1:length(N)

    cellsize = size(CELLS.(N{i}), 1);

    % Remove if Subj_level nobs is defined and this does not match
    if nobs && cellsize ~= nobs

        CELLS = rmfield(CELLS, N{i});

    end

    istext = all(cellfun(@ischar, CELLS.(N{i})));

    if istext

        CELLS = rmfield(CELLS, N{i});

    end

end

end


function value = p21_i4vec ( action, name, dim_num, value )

%*****************************************************************************80
%
%% P21_I4VEC sets or gets I4VEC parameters for problem 21.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION, the action.
%    'D' sets the object to a default value.
%    'G' means the current value of the object should be returned.
%    'S' means the input values of the object and its dimension
%    should be stored.
%
%    Input, string NAME, the name of the parameter.
%    'E' is the exponent vector.
%
%    Input, integer DIM_NUM, the dimension of the object.
%
%    Input/output, integer VALUE(DIM_NUM), the value of the object.
%
  persistent e
  persistent dim_num_save

  if ( size ( dim_num_save ) == 0 )
    dim_num_save = 0;
  end

  if ( dim_num_save ~= dim_num )
    dim_num_save = 0;
    e = [];
  end

  if ( dim_num_save == 0 )
    dim_num_save = dim_num;
  end

  if ( action == 'D' | action == 'd' )

    if ( name == 'E' | name == 'e' | name == '*' )
      e(1:dim_num) = 2;
    end

  elseif ( action == 'G' | action == 'g' )

    if ( name == 'E' | name == 'e' )
      value(1:dim_num) = e(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P21_I4VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P21_I4VEC - Fatal error!' );
    end

  elseif ( action == 'S' | action == 's' )

    if ( name == 'E' | name == 'e' )
      e(1:dim_num) = value(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P21_I4VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P21_I4VEC - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P21_I4VEC - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action = "%s".\n', action );
    error ( 'P21_I4VEC - Fatal error!' );

  end

  return
end


function [im_hatch,colorlist] = applyhatch_plus(h,patterns,colorlist,dpi, ...
                                                hatchsc,lw)
%APPLYHATCH_PLUS Apply hatched patterns to a figure
%  im_hatch = applyhatch_plus(h,patterns,colorlist,dpi,hatchsc,lw)
%
%  APPLYHATCH(H,PATTERNS) creates a new figure from the figure H by
%  replacing distinct colors in H with the black and white
%  patterns in PATTERNS. The format for PATTERNS can be
%    a string of the characters like '/', '\', '|', '-', '+', 'x', '.'
%    (see makehatch_plus.m for more details) or
%    a cell array of matrices of zeros (white) and ones (black)
%
%  In addition, H can alternatively be a uint8 NxMx3 matrix of the type
%  produced by imread.  In this case, colors in this image will be
%  replaced with patterns as if it was a figure.  A final figure window
%  will be generated that displays the result.  The DPI argument
%  discussed below will be ignored if H is an image matrix.
%
%  APPLYHATCH(H,PATTERNS,COLORS) maps the colors in the n by 3
%  matrix COLORS to PATTERNS. Each row of COLORS specifies an RGB
%  color value.
%
%  Note this function makes a bitmap image of H and so is limited
%  to bitmap output.
%
%  Additional arguments:
%
%  [im_hatch,colorlist] = applyhatch_plus(h,patterns,colorlist,dpi,hatchsc,linewidth)
%
%   input   DPI         allows specification of bitmap resolution, making plot resolution
%                       better for printing.  Ignored if H is an image matrix.
%           HATCHSC     multiplier for hatch scale to increase size of pattern for better operation
%                       at higher resolutions
%                       default [] uses screen resolution as in
%                       APPLYHATCH
%           LINEWIDTH   A scaling factor to apply to line and dot sizes
%                       in hatching.  Defaults to 1.
%   output  IM_HATCH    RGB bitmap matrix of new figure
%                       use IMWRITE to output in desired format
%           COLORLIST   List of colors actually replaced.  Useful info if
%                       no colorlist initially given to function.
%                       Colorlist will be uint8, not 0-1 scale as
%                       originally specified.
%
%  Example 1:
%    bar(rand(3,4));
%    [im_hatch,colorlist] = applyhatch_plus(gcf,'\-x.',[],150);
%    imwrite(im_hatch,'im_hatch.tiff','tiff')
%
%  Example 2:
%    colormap(cool(6));
%    pie(rand(6,1));
%    legend('Jan','Feb','Mar','Apr','May','Jun');
%    im_hatch = applyhatch_plus(gcf,'|-+.\/',cool(6),150,4);
%    imwrite(im_hatch,'im_hatch.tiff','tiff')
%
%  Example 3: Produces roughly the same thing as example 1
%    bar(rand(3,4));
%    print -dtiff -r150 im.tiff
%    im = imread( 'im.tiff', 'tiff' );
%    [im_hatch,colorlist] = applyhatch_plus(im,'\-x.',[]);
%    imwrite(im_hatch,'im_hatch.tiff','tiff')
%
%
% Modification of APPLYHATCH to allow higher resolution output
% Modified Brian FG Katz    8-aout-03
% Modified David M Kaplan   19-fevrier-08
%
%  See also: APPLYHATCH, MAKEHATCH, MAKEHATCH_PLUS

%  By Ben Hinkle, bhinkle@mathworks.com
%  This code is in the public domain.

if ~exist('hatchsc','var'); hatchsc = 1      ; end
if ~exist('dpi','var'); dpi = 0          ; end     % defaults to screen resolution
if ~exist('colorlist','var'); colorlist = []   ; end
if ~exist('lw','var'); lw=1; end

if numel(h) == 1 % Assume it is a figure window
  oldppmode = get(h,'paperpositionmode');
  oldunits = get(h,'units');
  oldcolor = get(h,'color');
  oldpos = get(h,'position');
  set(h,'paperpositionmode','auto');
  set(h,'units','pixels');
  set(h,'color',[1 1 1]);
  figsize = get(h,'position');

  bits = hardcopy(h,'-dzbuffer',['-r' num2str(dpi)]);

  % % Try a different approach using a temporary file - use this if having probs
  % tn = [ tempname '.tif' ];
  % print( '-dtiff', [ '-r' num2str(dpi) ], tn )
  % bits = uint8( imread( tn, 'TIFF' ) );
  % delete(tn)

  set(h,'paperpositionmode',oldppmode);
  set(h,'color',oldcolor);
elseif size(h,3) == 3 % Assume it is an image matrix
  bits = h;
  oldunits='pixels';
  oldpos = [ 0, 0, size(bits,2), size(bits,1) ];
  figsize = oldpos;
else
  error( 'Bad first argument.' );
end

bwidth = size(bits,2);
bheight = size(bits,1);
bsize = bwidth * bheight;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The next bit basically modernizes the original
% version of this function using things like unique
% and for loops
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make bitmap one long matrix with 3 columns
bits = reshape(bits,[bsize,3]);

% Convert original color scale to 255 scale
if ~isempty(colorlist)
  % NOTE: Added "floor" below because this seems to better pick out
  % correct colors produced by "hardcopy above better than uint8 by itself

  %colorlist = uint8(255*colorlist);
  colorlist = uint8(floor(255*colorlist));
else
  % Find unique colors in image - this takes a long time at high resolution
  [B,I,J] = unique( bits, 'rows' );

  % Find just "colored" colors
  C = find( B(:,1)~=B(:,2) | B(:,1)~=B(:,3) );
  colorlist = B( C , : );
end

% Loop over list of colors and find matches
for k = 1:size(colorlist,1)

  % Find points that match color
  if exist('B','var') % Use unique colors if around
    I = C(k) == J;
  else % Otherwise test each point
    cc = colorlist(k,:);
    I = bits(:,1)==cc(1) & bits(:,2)==cc(2) & bits(:,3)==cc(3);
    if ~any(I(:)), continue, end
  end

  % What pattern to use
  pati = mod( k-1, numel(patterns) ) + 1;
  if iscell(patterns)
    pattern = patterns{pati};
  elseif isa(patterns,'char')
    pattern = makehatch_plus(patterns(pati),6*hatchsc,lw);
  else
    pattern = patterns;
  end
  pattern = uint8(255*(1-pattern));

  % Make a big pattern matching size of bits
  pheight = size(pattern,2);
  pwidth = size(pattern,1);
  ratioh = ceil(bheight/pheight);
  ratiow = ceil(bwidth/pwidth);
  bigpattern = repmat(pattern,[ratioh ratiow]);
  if ratioh*pheight > bheight
    bigpattern(bheight+1:end,:) = [];
  end
  if ratiow*pwidth > bwidth
    bigpattern(:,bwidth+1:end) = [];
  end

  % Put that pattern into bits
  bits(find(I),:) = repmat(bigpattern(I),[1,3]);
end

% Put bits back into its normal shape
bits = reshape( bits, [bheight,bwidth,3] );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Replot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
newfig = figure('units',oldunits,'visible','off');
imaxes = axes('parent',newfig,'units','pixels');
im = image(bits,'parent',imaxes);
%fpos = get(newfig,'position');
%set(newfig,'position',[fpos(1:2) figsize(3) figsize(4)+1]);
set(newfig,'position',oldpos)
set(newfig,'units','pixels')
set(imaxes,'position',[0 0 figsize(3) figsize(4)+1],'visible','off');
set(newfig,'visible','on');

set(newfig,'units','normalized');
set(imaxes,'units','normalized');
set(imaxes,'DataAspectRatio',[1 1 1],'DataAspectRatioMode','manual');

if nargout > 0, im_hatch = bits; end
if nargout < 2, clear colorlist; end


function planar = spm_eeg_planarchannelset(data)
% Define the planar gradiometer channel combinations
% FORMAT planar = spm_eeg_planarchannelset(data)
%
% The output cell array contains the horizontal label, vertical label and
% the label after combining the two.
%__________________________________________________________________________
% Copyright (C) 2013-2015 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: spm_eeg_planarchannelset.m 7445 2018-10-12 13:24:48Z vladimir $

if isa(data, 'cell') && ~isempty(data) && isa(data{1}, 'char')
    input.label = data;
else
    input = data;
end

senstype = lower(ft_senstype(input));

k = strfind(senstype, '_combined');
if ~isempty(k)
    senstype(k:(k+length('_combined')-1)) = [];
end

try
    planar = ft_senslabel(senstype, 'output', 'planarcombined');
catch
    planar = ft_senslabel([senstype '_planar'], 'output', 'planarcombined');
end


function[cmap] = cmapThingsStuff()
% [cmap] = cmapThingsStuff()
%
% Returns the color map for stuff and thing labels in CocoStuff.
%
% Copyright by Holger Caesar, 2017

% Get stuff and thing color
stuffColors = cmapStuff();
thingColors = cmapThings();

% Remove duplicate backgrund
stuffColors(1, :) = [];
thingColors(1, :) = [];

% Combine unlabeled (black), things and stuff
cmap = [0, 0, 0; thingColors; stuffColors];


function [nnz,ind, val] = pennlp_congrad(i,x)

try
    f = datasaver(5,x,i+1);
    [ind,dummy,val] = find(f(:));
    nnz = length(ind);
catch

end

%[nnz,ind, val] = dg(i,x);