% pop_dipfit_settings() - select global settings for dipole fitting through a pop up window
%
% Usage:
%   >> OUTEEG = pop_dipfit_settings ( INEEG ); % pop up window
%   >> OUTEEG = pop_dipfit_settings ( INEEG, 'key1', 'val1', 'key2', 'val2' ... )
%
% Inputs:
%   INEEG	input dataset
%
% Optional inputs:
%   'hdmfile'  - [string] file containing a head model compatible with
%                the Fieldtrip dipolefitting() function ("vol" entry)
%   'mrifile'  - [string] file containing an anatomical MR head image.
%                The MRI must be normalized to the MNI brain. See the .mat
%                files used by the sphere and boundary element models
%                (For instance, select the sphere model and study 'EEG.dipfit').
%                If SPM2 software is installed, dipfit will be able to read
%                most MRI file formats for plotting purposes (.mnc files, etc...).
%                To plot dipoles in a subject MRI, first normalize the MRI
%                to the MNI brain using SPM2.
%   'coordformat' - ['MNI'|'Spherical'] Coordinates returned by the selected
%                head model. May be MNI coordinates or spherical coordinates
%                (For spherical coordinates, the head radius is assumed to be 85 mm.
%   'chanfile' - [string] template channel locations file. (This function will
%                check whether your channel locations file is compatible with
%                your selected head model).
%   'chansel'  - [integer vector] indices of channels to use for dipole fitting.
%                {default: all}
%   'coord_transform' - [float array] Talairach transformation matrix for
%                       aligning the dataset channel locations to the selected
%                       head model.
%   'electrodes'      - [integer array] indices of channels to include
%                       in the dipole model. {default: all}
% Outputs:
%   OUTEEG	output dataset
%
% Author: Arnaud Delorme, SCCN, La Jolla 2003-
%         Robert Oostenveld, SMI/FCDC, Nijmegen 2003

% MEG flag:
%   'gradfile' - [string] file containing gradiometer locations
%                ("gradfile" parameter in Fieldtrip dipolefitting() function)

% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl

% Copyright (C) 2003 arno@salk.edu, Arnaud Delorme, SCCN, La Jolla 2003-2005
%
% 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 [OUTEEG, com] = pop_dipfit_settings ( EEG, varargin )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin < 1
   help pop_dipfit_settings;
   return;
end;

OUTEEG = EEG;
com = '';

% get the default values and filenames
dipfitdefs;

if nargin < 2

    if isstr(EEG) % setmodel
        tmpdat = get(gcf, 'userdata');
        chanfile = tmpdat.chanfile;
        tmpdat   = tmpdat.template_models;
        tmpval = get(findobj(gcf, 'tag', 'listmodels'), 'value');
        set(findobj(gcf, 'tag', 'model'), 'string', char(tmpdat(tmpval).hdmfile));
        set(findobj(gcf, 'tag', 'coord'), 'value' , fastif(strcmpi(tmpdat(tmpval).coordformat,'MNI'),2, ...
                                                     fastif(strcmpi(tmpdat(tmpval).coordformat,'CTF'),3,1)));
        set(findobj(gcf, 'tag', 'mri'  ), 'string', char(tmpdat(tmpval).mrifile));
        set(findobj(gcf, 'tag', 'meg'), 'string', char(tmpdat(tmpval).chanfile));
        set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0);
        if tmpval < 3,
            set(findobj(gcf, 'userdata', 'editable'), 'enable', 'off');
        else,
            set(findobj(gcf, 'userdata', 'editable'), 'enable', 'on');
        end;
        if tmpval == 3,
            set(findobj(gcf, 'tag', 'headstr'), 'string', 'Subject CTF head model file (default.htm)');
            set(findobj(gcf, 'tag', 'mristr'),  'string', 'Subject MRI (coregistered with CTF head)');
            set(findobj(gcf, 'tag', 'chanstr'), 'string', 'CTF Res4 file');
            set(findobj(gcf, 'tag', 'manualcoreg'), 'enable', 'off');
            set(findobj(gcf, 'userdata', 'coreg'), 'enable', 'off');
        else,
            set(findobj(gcf, 'tag', 'headstr'), 'string', 'Head model file');
            set(findobj(gcf, 'tag', 'mristr'),  'string', 'MRI file');
            set(findobj(gcf, 'tag', 'chanstr'), 'string', 'Model template channel locations file');
            set(findobj(gcf, 'tag', 'manualcoreg'), 'enable', 'on');
            set(findobj(gcf, 'userdata', 'coreg'), 'enable', 'on');
        end;
        tmpl = tmpdat(tmpval).coord_transform;
        set(findobj(gcf, 'tag', 'coregtext'), 'string', '');
        set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0);
        [allkeywordstrue transform] = lookupchantemplate(chanfile, tmpl);
        if allkeywordstrue,
            set(findobj(gcf, 'tag', 'coregtext'), 'string', char(vararg2str({ transform })));
            if isempty(transform)
                 set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 1);
            else set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0);
            end;
        end;
        return;
    end;

    % detect DIPFIT1.0x structure
    % ---------------------------
    if isfield(EEG.dipfit, 'vol')
        str = [ 'Dipole information structure from DIPFIT v1.02 detected.' ...
                'Keep or erase the old dipole information including dipole locations? ' ...
                'In either case, a new dipole model can be constructed.' ];

        tmpButtonName=questdlg2( strmultiline(str, 60), 'Old DIPFIT structure', 'Keep', 'Erase', 'Keep');
        if strcmpi(tmpButtonName, 'Keep'), return; end;

    elseif isfield(EEG.dipfit, 'hdmfile')
        % detect previous DIPFIT structure
        % --------------------------------
        str = [ 'Dipole information and settings are present in the dataset. ' ...
                'Keep or erase this information?' ];
        tmpButtonName=questdlg2( strmultiline(str, 60), 'Old DIPFIT structure', 'Keep', 'Erase', 'Keep');
        if strcmpi(tmpButtonName, 'Keep'), return; end;
    end;

    % define the callbacks for the buttons
    % -------------------------------------
    cb_selectelectrodes = [ 'tmplocs = EEG.chanlocs; tmp = select_channel_list({tmplocs.label}, ' ...
                            'eval(get(findobj(gcbf, ''tag'', ''elec''), ''string'')));' ...
                            'set(findobj(gcbf, ''tag'', ''elec''), ''string'',[''[''  num2str(tmp) '']'']); clear tmplocs;' ]; % did not work
    cb_selectelectrodes = 'tmplocs = EEG.chanlocs; set(findobj(gcbf, ''tag'', ''elec''), ''string'', int2str(pop_chansel({tmplocs.labels}))); clear tmplocs;';
    cb_volmodel = [ 'tmpdat = get(gcbf, ''userdata'');' ...
                    'tmpind = get(gcbo, ''value'');' ...
                    'set(findobj(gcbf, ''tag'', ''radii''),   ''string'', num2str(tmpdat{tmpind}.r,3));' ...
                    'set(findobj(gcbf, ''tag'', ''conduct''), ''string'', num2str(tmpdat{tmpind}.c,3));' ...
                    'clear tmpdat tmpind;' ];
    cb_changeradii   = [  'tmpdat = get(gcbf, ''userdata'');' ...
                          'tmpdat.vol.r = str2num(get(gcbo, ''string''));' ...
                          'set(gcf, ''userdata'', tmpdat)' ];
    cb_changeconduct = [  'tmpdat = get(gcbf, ''userdata'');' ...
                          'tmpdat.vol.c = str2num(get(gcbo, ''string''));' ...
                          'set(gcf, ''userdata'', tmpdat)' ];
    cb_changeorigin  = [  'tmpdat = get(gcbf, ''userdata'');' ...
                          'tmpdat.vol.o = str2num(get(gcbo, ''string''));' ...
                          'set(gcf, ''userdata'', tmpdat)' ];
    % cb_fitelec = [ 'if get(gcbo, ''value''),' ...
    %                '  set(findobj(gcbf, ''tag'', ''origin''), ''enable'', ''off'');' ...
    %                'else' ...
    %                '  set(findobj(gcbf, ''tag'', ''origin''), ''enable'', ''on'');' ...
    %                'end;' ];
    valmodel     = 1;
    userdata    = [];
    if isfield(EEG.chaninfo, 'filename')
        if ~isempty(findstr(lower(EEG.chaninfo.filename), 'standard-10-5-cap385')), valmodel = 1; end;
        if ~isempty(findstr(lower(EEG.chaninfo.filename), 'standard_1005')),        valmodel = 2; end;
    end;

    geomvert = [3 1 1 1 1 1 1 1 1 1 1];

    geomhorz = {
        [1 2]
        [1]
        [1 1.3 0.5 0.5 ]
        [1 1.3 0.9 0.1 ]
        [1 1.3 0.5 0.5 ]
        [1 1.3 0.5 0.5 ]
        [1 1.3 0.5 0.5 ]
        [1 1.3 0.5 0.5 ]
        [1]
        [1]
        [1] };

    % define each individual graphical user element
    comhelp1 = [ 'warndlg2(strvcat(''The two default head models are in ''standard_BEM'' and ''standard_BESA'''',' ...
                 ''' sub-folders in the DIPFIT2 plugin folder, and may be modified there.''), ''Model type'');' ];
    comhelp3 = [ 'warndlg2(strvcat(''Any MR image normalized to the MNI brain model may be used for plotting'',' ...
                 '''(see the DIPFIT 2.0 tutorial for more information)''), ''Model type'');' ];
    comhelp2 = [ 'warndlg2(strvcat(''The template location file associated with the head model'',' ...
                 '''you are using must be entered (see tutorial).''), ''Template location file'');' ];
    commandload1 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
                    'if filename ~=0,' ...
                    '   set(findobj(''parent'', gcbf, ''tag'', ''model''), ''string'', [ filepath filename ]);' ...
                    'end;' ...
                    'clear filename filepath tagtest;' ];
    commandload2 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
                    'if filename ~=0,' ...
                    '   set(findobj(''parent'', gcbf, ''tag'', ''meg''), ''string'', [ filepath filename ]);' ...
                    'end;' ...
                    'clear filename filepath tagtest;' ];
    commandload3 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
                    'if filename ~=0,' ...
                    '   set(findobj(''parent'', gcbf, ''tag'', ''mri''), ''string'', [ filepath filename ]);' ...
                    'end;' ...
                    'clear filename filepath tagtest;' ];
    cb_selectcoreg = [ 'tmpmodel = get( findobj(gcbf, ''tag'', ''model''), ''string'');' ...
                       'tmploc2  = get( findobj(gcbf, ''tag'', ''meg'')  , ''string'');' ...
                       'tmploc1  = get( gcbo, ''userdata'');' ...
                       'tmptransf = get( findobj(gcbf, ''tag'', ''coregtext''), ''string'');' ...
                       '[tmp tmptransf] = coregister(tmploc1{1}, tmploc2, ''mesh'', tmpmodel,' ...
                       '                       ''transform'', str2num(tmptransf), ''chaninfo1'', tmploc1{2}, ''helpmsg'', ''on'');' ...
                       'if ~isempty(tmptransf), set( findobj(gcbf, ''tag'', ''coregtext''), ''string'', num2str(tmptransf)); end;' ...
                       'clear tmpmodel tmploc2 tmploc1 tmp tmptransf;' ];
    setmodel = [ 'pop_dipfit_settings(''setmodel'');' ];

    dipfitdefs; % contains template_model

    templatenames = { template_models.name };
    elements  = { ...
        { 'style' 'text'        'string'  [ 'Head model (click to select)' 10 '' ] } ...
        { 'style' 'listbox'     'string'  strvcat(templatenames{:}) ...
                                'callback' setmodel 'value' valmodel 'tag' 'listmodels' } { } ...
        { 'style' 'text'        'string' '________' 'tag' 'headstr' } ...
        { 'style' 'edit'        'string' '' 'tag'      'model' 'userdata' 'editable' 'enable' 'off'} ...
        { 'style' 'pushbutton'  'string' 'Browse'    'callback' commandload1       'userdata' 'editable' 'enable' 'off' } ...
        { 'style' 'pushbutton'  'string' 'Help'      'callback' comhelp1 } ...
        { 'style' 'text'        'string' 'Output coordinates' } ...
        { 'style' 'popupmenu'   'string' 'spherical (head radius 85 mm)|MNI|CTF' 'tag' 'coord' ...
          'value' 1  'userdata' 'editable' 'enable' 'off'} ...
        { 'style' 'text'        'string' 'Click to select' } { } ...
        { 'style' 'text'        'string' '________' 'tag' 'mristr' } ...
        { 'style' 'edit'        'string' '' 'tag' 'mri' } ...
        { 'style' 'pushbutton'  'string' 'Browse'       'callback' commandload3 } ...
        { 'style' 'pushbutton'  'string' 'Help'         'callback' comhelp3 } ...
        { 'style' 'text'        'string' '________', 'tag', 'chanstr' } ...
        { 'style' 'edit'        'string' '' 'tag' 'meg'  'userdata' 'editable' 'enable' 'off'} ...
        { 'style' 'pushbutton'  'string' 'Browse'       'callback' commandload2  'userdata' 'editable' 'enable' 'off'} ...
        { 'style' 'pushbutton'  'string' 'Help'         'callback' comhelp2 } ...
        { 'style' 'text'        'string' 'Co-register chan. locs. with head model' 'userdata' 'coreg' } ...
        { 'style' 'edit'        'string' '' 'tag' 'coregtext' 'userdata' 'coreg' } ...
        { 'style' 'pushbutton'  'string' 'Manual Co-Reg.' 'tag' 'manualcoreg' 'callback' cb_selectcoreg 'userdata' { EEG.chanlocs EEG.chaninfo } } ...
        { 'style' 'checkbox'    'string' 'No Co-Reg.'    'tag' 'coregcheckbox' 'value' 0  'userdata' 'coreg' } ...
        { 'style' 'text'        'string' 'Channels to omit from dipole fitting' } ...
        { 'style' 'edit'        'string' ''             'tag' 'elec' } ...
        { 'style' 'pushbutton'  'string' 'List' 'callback' cb_selectelectrodes } { } ...
        { } ...
        { 'style' 'text'        'string' 'Note: For EEG, check that the channel locations are on the surface of the head model' } ...
        { 'style' 'text'        'string' '(To do this: ''Set head radius'' to about 85 in the channel editor).' } ...
                };

    % plot GUI and protect parameters
    % -------------------------------
    userdata.template_models  = template_models;
    if isfield(EEG.chaninfo, 'filename')
         userdata.chanfile         = lower(EEG.chaninfo.filename);
    else userdata.chanfile         = '';
    end;
    optiongui = { 'geometry', geomhorz, 'uilist', elements, 'helpcom', 'pophelp(''pop_dipfit_settings'')', ...
                  'title', 'Dipole fit settings - pop_dipfit_settings()', ...
                  'userdata', userdata, 'geomvert', geomvert 'eval' 'pop_dipfit_settings(''setmodel'');' };
	[result, userdat2, strhalt, outstruct] = inputgui( 'mode', 'noclose', optiongui{:});
    if isempty(result), return; end;
    if ~isempty(get(0, 'currentfigure')) currentfig = gcf; else return; end;

    while test_wrong_parameters(currentfig)
    	[result, userdat2, strhalt, outstruct] = inputgui( 'mode', currentfig, optiongui{:});
        if isempty(result), return; end;
    end;
    close(currentfig);

    % decode GUI inputs
    % -----------------
    options = {};
    options = { options{:} 'hdmfile'      result{2} };
    options = { options{:} 'coordformat'  fastif(result{3} == 2, 'MNI', fastif(result{3} == 1, 'Spherical', 'CTF')) };
    options = { options{:} 'mrifile'      result{4} };
    options = { options{:} 'chanfile'     result{5} };
    if ~result{7}, options = { options{:} 'coord_transform' str2num(result{6}) }; end;
    options = { options{:} 'chansel'      setdiff(1:EEG.nbchan, str2num(result{8})) };

else
    options = varargin;
end

g = finputcheck(options, { 'hdmfile'  'string'    []         '';
                                 'mrifile'  'string'    []         '';
                                 'chanfile' 'string'    []         '';
                                 'chansel'  'integer'   []         [1:EEG.nbchan];
                                 'electrodes' 'integer'   []         [];
                                 'coord_transform' 'real' []         [];
                                 'coordformat' 'string'    { 'MNI' 'spherical' 'CTF' } 'MNI' });
if isstr(g), error(g); end;

OUTEEG = rmfield(OUTEEG, 'dipfit');
OUTEEG.dipfit.hdmfile     = g.hdmfile;
OUTEEG.dipfit.mrifile     = g.mrifile;
OUTEEG.dipfit.chanfile    = g.chanfile;
OUTEEG.dipfit.chansel     = g.chansel;
OUTEEG.dipfit.coordformat     = g.coordformat;
OUTEEG.dipfit.coord_transform = g.coord_transform;
if ~isempty(g.electrodes), OUTEEG.dipfit.chansel = g.electrodes; end;

% removing channels with no coordinates
% -------------------------------------
[tmpeloc labels Th Rd indices] = readlocs(EEG.chanlocs);
if length(indices) < length(EEG.chanlocs)
    disp('Warning: Channels removed from dipole fitting no longer have location coordinates!');
    OUTEEG.dipfit.chansel = intersect( OUTEEG.dipfit.chansel, indices);
end;

% checking electrode configuration
% --------------------------------
if 0
    disp('Checking the electrode configuration');
    tmpchan          = readlocs(OUTEEG.dipfit.chanfile);
    [tmp1 ind1 ind2] = intersect( lower({ tmpchan.labels }), lower({ OUTEEG.chanlocs.labels }));
    if isempty(tmp1)
        disp('No channel labels in common found between template and dataset channels');
        if ~isempty(findstr(OUTEEG.dipfit.hdmfile, 'BESA'))
            disp('Use the channel editor to fit a head sphere to your channel locations.');
            disp('Check for inconsistency in dipole info.');
        else
            disp('Results using standard BEM model are INACCURATE when the chan locations are not on the head surface!');
        end;
    else % common channels: performing best transformation
        TMP = OUTEEG;
        elec1 = eeglab2fieldtrip(TMP, 'elec');
        elec1 = elec1.elec;
        TMP.chanlocs = tmpchan;
        elec2 = eeglab2fieldtrip(TMP, 'elec');
        elec2 = elec2.elec;
        cfg.elec     = elec1;
        cfg.template = elec2;
        cfg.method   = 'warp';
        elec3 = electrodenormalize(cfg);

        % convert back to EEGLAB format
        OUTEEG.chanlocs = struct( 'labels', elec3.label, ...
                              'X'     , mat2cell(elec3.pnt(:,1)'), ...
                              'Y'     , mat2cell(elec3.pnt(:,2)'), ...
                              'Z'     , mat2cell(elec3.pnt(:,3)') );
        OUTEEG.chanlocs = convertlocs(OUTEEG.chanlocs, 'cart2all');
    end;

end;

com = sprintf('%s = pop_dipfit_settings( %s, %s);', inputname(1), inputname(1), vararg2str(options));

% test for wrong parameters
% -------------------------
function bool = test_wrong_parameters(hdl)

    coreg1 = get( findobj( hdl, 'tag', 'coregtext')    , 'string' );
    coreg2 = get( findobj( hdl, 'tag', 'coregcheckbox'), 'value' );
    meg    = get( findobj( hdl, 'tag', 'coord'), 'value' );

    bool = 0;
    if meg == 3, return; end;
    if coreg2 == 0 & isempty(coreg1)
         bool = 1; warndlg2(strvcat('You must co-register your channel locations', ...
                                    'with the head model (Press buttun, "Manual Co-Reg".', ...
                                    'and follow instructions); To bypass co-registration,', ...
                                    'check the checkbox " No Co-Reg".'), 'Error');
    end;


function c = double(b)
% bsarray/double: convert bsarray object to coefficient array
% usage: c = double(b)
%
% arguments:
%   b - bsarray object
%
%   c - array of bspline coefficients

% author: Nathan D. Cahill
% email: ndcahill@gmail.com
% date: 18 April 2008

c = b.coeffs;


function [visualField,corners,areaROI, retPhases, view] = atlasDefinition(atlasName, scans, fields, view)
%   [visualField,corners,areaROI, retPhases, view] = atlasDefinition(atlasName, scans, fields, view)
%
% Author: Wandell, Brewer
% Purpose:
%    Define the properties of a group of retinotopic visual areas that
%    will serve as an atlas for template matching.
%
%   scans are the scanNums of the ring (scans(1)) and
%   wedge (scans(2)) data.
%
%
% INPUTS:
%	atlasName: name of atlas to fit.
%
%	scans: [2 x 1] vector of [eccentricity, polar angle] scan numbers for
%	the current data type in the flat view.
%
%	fields: {2 x 1} cell array of {eccentricity, polar angle} field names
%	(out of 'ph', 'map', 'amp', 'co') from which to draw the data.
%
%	view: flat view we're using to fit.
%
%
% [visualField,corners,areaROI,retPhases,view] = atlasDefinition('ventralV2V3V4',[2,1],FLAT{2});
%
% History:
% 15/11/04  marking V1/V2/V3 changed by MMS (mark@ski.org) so that you no
% longer mark V1 then V2 then V3 but just mark V1 and V3. V2 is then assumed
% to lie between.
% see line 282, I think this deal with the problems adressed in 272 by
% Wandell or Brewer
%
% ras, 04/09: many changes.
% (1) takes as input parameters the field name, as well of the scan, of the
% ecc / polar angle data (to allow for pRF data fitting).
% (2) broke each atlas type into its own subfunction.
%

%% check we've passed in the proper input arguments
if ~isequal(view.viewType, 'Flat')
	error('Need a flat view.')
end

% show all ROIs
view.ui.showROIs=-2;
view = refreshView(view);

% % for some reason, we need to have the flat not rotated flipped. We should
% % fix this.
% if sum(abs([view.rotateImageDegrees,view.flipLR]))~=0
%     error('The fields ''.rotateImageDegrees'' and ''.flipLR'' of the FLAT structure must be zero.');
% end

% call the appropriate subfunction to fit the specified atlas.
switch lower(atlasName)
    case {'hemifield','hf'},
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitHemifield(view, scans, fields);
    case {'lqf','lowerquarterfield'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitLowerQuarterfield(view, scans, fields);
	case {'uqf','upperquarterfield'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitUpperQuarterfield(view, scans, fields);
    case {'hemiuppervf','hV4V3'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV3_hV4(view, scans, fields);
    case {'2hemifields','VO1VO2'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitVO1_VO2(view, scans, fields);
    case 'mt/mst circular'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitMT_MST(view, scans, fields);
	case 'v1/v2'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_V2(view, scans, fields);
    case 'v1/v2/v3'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_V2_V3(view, scans, fields);
    case 'v4/v8'
        error('Not yet implemented: v4/v8');
    case {'lo2/to1/to2' '2 hemifields + 2a manual without LO1'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitLO2_TO1_TO2(view, scans, fields);
	case '4 hemifields'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit4Hemifields(view, scans, fields);
	case '4 hemifields old'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit4HemifieldsOld(view, scans, fields);
    case 'common atlas with 4 hemifields'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit4HemifieldsCommonAtlas(view, scans, fields);
    case '2 hemifields + 2a'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit2HemifieldsPlus2a(view, scans, fields);
    case '2 hemifields + 2a common'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit2HemifieldsPlus2aCommon(view, scans, fields);
    case {'v1/v2/v3/lo1/lo2' 'v1ToLO2'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_to_LO2(view, scans, fields);
    case {'v1/v2/v3/lo1/lo22' 'v1ToLO2_alt'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_to_LO2_alt(view, scans, fields);
    case {'v1/v2/v3/lo1/lo2/to1/to2' 'v1ToTO2'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_to_TO2(view, scans, fields);
    case 'ventralv2v3v4'
        [view,visualField,corners,retPhases,areaROI] = ...
			fitVentralV2V3V4(view, scans, fields);
    otherwise
        error(sprintf('Unknown atlas name: %s', atlasName));
end

% Show the user what just happened.
view = refreshView(view);

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitHemifield(view, scans, fields);
% Fit an unspecified hemifield representation.

% set up a string to make the message strings easier.
newline = sprintf('\n');   % this will make the message strings easier.
msg = ['Select Hemifield in the data to which to fit the atlas.' newline ...
	   'Point 1: LOW eccentricity and LOW polar angle.' newline ...
	   'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
	   'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
	   'Point 4: HIGH eccentricity and LOW polar angle. '];

visualField{1} = 'hemifield';   %V1

corners = {};
msgHndl = mrMessage(msg, 'left', [], 9);

[locs, areaROI{1}, view] = atlasGraphicDefinition('quadrilateral',view);
corners{1} = locs.corners;
delete(msgHndl);

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

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

% /-----------------------------------------------------------------/ %
function [retPhases] = fitLowerQuarterfield(view, scans, fields);
% Fit an unspecified lower-quarter field representation.
newline = sprintf('\n');   % this will make the message strings easier.
msg = ['Select a Lower Quarter Field Representation in the data.' newline ...
	   'Point 1: LOW eccentricity and LOW polar angle.' newline ...
	   'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
	   'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
	   'Point 4: HIGH eccentricity and LOW polar angle. '];

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'lowerquarterfield';   % Dorsal V3, for example

corners = {};
msgHndl = mrMessage(msg{1},'left',[0.8000    0.1000    0.1800    0.1000]);

[locs, areaROI{1},view] = atlasGraphicDefinition('quadrilateral',view);
corners{1} = locs.corners;
delete(msgHndl);

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

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

% /-----------------------------------------------------------------/ %
function [retPhases] = fitUpperQuarterfield(view, scans, fields);
% Fit an unspecified upper-quarter field representation.
newline = sprintf('\n');   % this will make the message strings easier.
msg = ['Select an Upper Quarter Field Representation in the data.' newline ...
	   'Point 1: LOW eccentricity and LOW polar angle.' newline ...
	   'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
	   'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
	   'Point 4: HIGH eccentricity and LOW polar angle. '];

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'upperquarterfield';   % Dorsal V3, for example

corners = {};
msgHndl = mrMessage(msg{1},'left',[0.8000    0.1000    0.1800    0.1000]);

[locs, areaROI{1},view] = atlasGraphicDefinition('quadrilateral',view);
corners{1} = locs.corners;
delete(msgHndl);

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV3_hV4(view, scans, fields);
% Fit an upper quarter field, plus a hemifield.
% This fitting was designed to match ventral V3 and hV4.
newline = sprintf('\n');   % this will make the message strings easier.
msg{1} = ['Select the hemifield representation (e.g., hV4).' newline ...
		  'Point 1: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 2: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 3: HIGH eccentricity and LOW polar angle.' newline ...
		  'Point 4: HIGH eccentricity and HIGH polar angle. '];

msg{2}  = ['Select the quarterfield representation (e.g., V3v)' newline ...
		  'Point 1: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 2: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 3: HIGH eccentricity and LOW polar angle.' newline ...
		  'Point 4: HIGH eccentricity and HIGH polar angle. '];

visualField{1} = 'hemifield';           %hV4
visualField{2} = 'upperquarterfield';   %V3 Ventral

% load and display an example image to help guide the user in terms of
% which corners to click in which order:
codeDir = fileparts( which(mfilename) );
imgPath = fullfile(codeDir, 'Atlas_V3v_hV4_order.png');
try
	img = imread(imgPath, 'png');

	hGuide = figure('Color', 'w', 'Name', 'Click in this order', ...
					'Units', 'norm', 'Position', [0 .6 .3 .4], ...
					'NumberTitle', 'off');

	imshow(img);
	title('Select Points in the specified order.', 'FontSize', 18);
end

corners = {};
for ii=1:2

	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitVO1_VO2(view, scans, fields);
% Fit two hemifields (corresponding to VO-1 and VO-2).
newline = sprintf('\n');
msg{1} = ['Select the first hemifield representation (e.g., VO-1).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{2}  = ['Select the second hemifield representation (e.g., VO-2)' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    %VO-1
visualField{2} = 'hemifield';    %VO-2

corners = {};
for ii=1:2
	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitMT_MST(view, scans, fields);
% Fit an atlas to a circular set of visual field representations around areas MT and MST (?).
newline = sprintf('\n');
msg  = ['Select fovea.' newline ...
		'Draw line one through fovea from high to low polar angle.' newline ...
		'Draw line two roughly orthogonal.'];

msgHndl = mrMessage(msg,'left', [], 9);

[x1,y1] = getline;
x1 = x1(1:2); y1 = y1(1:2);

[x2,y2] = getline;
x2 = x2(1:2); y2 = y2(1:2);

locs.x1 = x1; locs.x2 = x2; locs.y1 = y1; locs.y2 = y2;

im=makeCircularMaps(view,locs)

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});
view = selectROI(view,areaROI{3});
view = replaceROIQuadrilateralCoords(view,corners{3});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

delete(msgHndl);

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_V2(view, scans, fields);
% Fit V1 (hemifield) and the two quarter fields of V2.
newline = sprintf('\n');
msg{1} = ['Select V1.' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{2}  = ['Select V2d (lower quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{3}  = ['Select V2v (upper quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

visualField{1} = 'hemifield';   %V1
visualField{2} = 'lowerquarterfield'; %Dorsal V2
visualField{3} = 'upperquarterfield'; %Ventral V2

corners = {};
for ii=1:3

	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});
view = selectROI(view,areaROI{3});
view = replaceROIQuadrilateralCoords(view,corners{3});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_V2_V3(view, scans, fields);
% Fit V1, V2, and V3.
newline = sprintf('\n');
msg{1} = ['Select V1.' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{2}  = ['Select V3v (upper quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{3}  = ['Select V3d (lower quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

visualField{1} = 'hemifield';   %V1
visualField{2} = 'lowerquarterfield'; % Ventral V2
visualField{3} = 'upperquarterfield'; % Dorsal V2
visualField{4} = 'lowerquarterfield'; % Ventral V3
visualField{5} = 'upperquarterfield'; % Dorsal V3

% load and display an example image to help guide the user in terms of
% which corners to click in which order:
codeDir = fileparts( which(mfilename) );
imgPath = fullfile(codeDir, 'Atlas_V1-V3_order.png');
try
	img = imread(imgPath, 'png');

	hGuide = figure('Color', 'w', 'Name', 'Click in this order', ...
					'Units', 'norm', 'Position', [0 .6 .3 .4], ...
					'NumberTitle', 'off');

	imshow(img);
	title('Select Points in the specified order.', 'FontSize', 18);
end

% get the corners of the 3 quadrilaterals (V1, V3v, V3d), which will define
% the 5 distinct field maps:
corners = {};
for ii=1:3
	msgHndl = mrMessage(msg{ii},'left',[],9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);
end

% close the guide figure as well
close(hGuide);

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

% this old merging of corner  becomes obsolet
% corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
% corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
% corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});
% corners{5} = atlasMergeAdjacentCorners(corners{3},corners{5});

%instead get V2 corners from V1 and V3
%first copy corners of V3ventral and dorsal to pos 4 ad 5
corners{4}=corners{2};
corners{5}=corners{3};

%V2v
corners{2}(1,1:2)=corners{4}(1,1:2); %from V3v
corners{2}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{2}(4,1:2)=corners{4}(4,1:2); %from V3v

%V2d
corners{3}(1,1:2)=corners{1}(1,1:2); %from V1
corners{3}(2:3,1:2)=corners{5}(2:3,1:2); %from V1
corners{3}(4,1:2)=corners{1}(4,1:2);%from V1

%add the ROIS 4 and 5 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegant way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end
roiName = sprintf('Quad-%.0f',num);
view=newROI(view,roiName,1,[0 0 0]);
areaROI=cat(2,areaROI,{roiName});
roiName = sprintf('Quad-%.0f',num+1);
view=newROI(view,roiName,1,[0 0 0]);
areaROI=cat(2,areaROI,{roiName});

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplified...
for jup=2:5
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
retPhases = [0 pi*2 pi*0.5 pi*1.5];

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitLO2_TO1_TO2(view, scans, fields);
% select MT, MST, LO2 amd the wall of MST
msg{1}  = ['Select hemifield (e.g., TO1)' newline pointSpec];

msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select quarterfield next to the first hemifield (e.g., LO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{3} = addText(msg{3},newText);

msg{4}  = sprintf('Select quarterfield next to the second hemifield\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{4},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{4} = addText(msg{4},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    % TO1
visualField{2} = 'hemifield';    % TO2
visualField{3} = 'hemifield';    % LO2
visualField{4} = 'hemifield';    % wall
visualField{5} = 'hemifield';    % wall
visualField{6} = 'hemifield';    % wall
visualField{7} = 'hemifield';    % LO1

corners = {};
for ii=1:4
	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
%         corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
%         corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
%         corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});

tmp=round((corners{1}(1,1:2)+corners{3}(1,1:2))/2);
corners{1}(1,1:2)=tmp;
corners{3}(1,1:2)=tmp;
tmp=round((corners{1}(4,1:2)+corners{3}(4,1:2))/2);
corners{1}(4,1:2)=tmp;
corners{3}(4,1:2)=tmp;

corners{7}(2:3,:) = corners{3}(2:3,:);
corners{7}(1,:) = corners{7}(2,:) + (corners{7}(2,:)-corners{3}(1,:));
corners{7}(4,:) = corners{7}(3,:) + (corners{7}(3,:)-corners{3}(4,:));

tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
corners{1}(2:3,1:2)=tmp;
corners{2}(2:3,1:2)=tmp;

tmp=round((corners{2}(1,1:2)+corners{4}(1,1:2))/2);
corners{2}(1,1:2)=tmp;
corners{4}(1,1:2)=tmp;

tmp=round((corners{2}(4,1:2)+corners{4}(4,1:2))/2);
corners{2}(4,1:2)=tmp;
corners{4}(4,1:2)=tmp;

corners{5}(1,1:2)=corners{1}(1,1:2);
corners{5}(2,1:2)=corners{2}(1,1:2);
corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.5-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.5);
corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

corners{6}(3,1:2)=corners{1}(4,1:2);
corners{6}(4,1:2)=corners{2}(4,1:2);
corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.5-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.5);
corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:3
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=1:7
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

retPhases = [0 pi*2 pi/2 pi];
%         retPhases = [0 pi*2 pi/2 -pi/2];

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit4HemifieldsOld(view, scans, fields);
% old version of the 4 hemifields fitting code (?).
% select MT, MST, LO2 amd LO1

        msg{1}  = sprintf('Select hemifield (e.g., TO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
        newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

        msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

        msg{3}  = sprintf('Select hemifield (e.g., LO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{3},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{3} = addText(msg{3},newText);

        msg{4}  = sprintf('Select hemifield (e.g., LO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{4},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{4} = addText(msg{4},newText);

        % This becomes, say, the V1/V2 function.
        % It gets its own message box and is a template for the creation of other
        % atlas creation routines.
        visualField{1} = 'hemifield';    % TO1
        visualField{2} = 'hemifield';    % TO2
        visualField{3} = 'hemifield';    % LO2
        visualField{4} = 'hemifield';    % wall
        visualField{5} = 'hemifield';    % wall
        visualField{6} = 'hemifield';    % wall
        visualField{7} = 'hemifield';    % LO1

        corners = {};
        for ii=1:4
            msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

            [locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
            corners{ii} = locs.corners;

            delete(msgHndl);

        end

        % We need a GUI for deciding who goes with what.  This ordering of the code
        % assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
        % We might make sure that we always get a certain corner match.  Sometimes,
        % two corners end up being matched to the same one ...
        %         corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
        %         corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
        %         corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});

        corners{7}=corners{4};

        % LO1 LO2 border
        tmp=round((corners{7}(2:3,1:2)+corners{3}(2:3,1:2))/2);
        corners{7}(2:3,1:2)=tmp;
        corners{3}(2:3,1:2)=tmp;

        % LO2 MT border
        tmp=round((corners{3}(1,1:2)+corners{1}(1,1:2))/2);
        corners{3}(1,1:2)=tmp;
        corners{1}(1,1:2)=tmp;
        tmp=round((corners{3}(4,1:2)+corners{1}(4,1:2))/2);
        corners{3}(4,1:2)=tmp;
        corners{1}(4,1:2)=tmp;

        % MT MST border
        tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
        corners{1}(2:3,1:2)=tmp;
        corners{2}(2:3,1:2)=tmp;

        % wall of MST
        corners{4}(1,:) = corners{2}(1,:);
        corners{4}(4,:) = corners{2}(4,:);
        corners{4}(2,:) = corners{4}(1,:) + round((corners{2}(1,:)-corners{2}(2,:))*0.3);
        corners{4}(3,:) = corners{4}(4,:) + round((corners{2}(4,:)-corners{2}(3,:))*0.3);

        % wall of MT, MST
        corners{5}(1,1:2)=corners{1}(1,1:2);
        corners{5}(2,1:2)=corners{2}(1,1:2);
        corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.3-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.3);
        corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
        corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

        % wall of MT, MST
        corners{6}(3,1:2)=corners{1}(4,1:2);
        corners{6}(4,1:2)=corners{2}(4,1:2);
        corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.3-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.3);
        corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
        corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

        % not to exceed the area
        corners{4}(find(corners{4}<1))=1;
        corners{4}(find(corners{4}>size(view.anat,1)))=size(view.anat,1);
        corners{5}(find(corners{5}<1))=1;
        corners{5}(find(corners{5}>size(view.anat,1)))=size(view.anat,1);
        corners{6}(find(corners{6}<1))=1;
        corners{6}(find(corners{6}>size(view.anat,1)))=size(view.anat,1);

%         for i=1:4
%             if norm(corners{5}(i,:)-(size(view.anat,1)+1)/2)>(size(view.anat,1)-1)/2*sqrt(2);
%                 corners{5}(i,:) = floor(corners{5}(i,:)/norm(corners{5}(i,:)-(size(view.anat,1)-1)/2)*(size(view.anat,1)+1)/2)
%             end
%         end

        found = roiExistName(view,'Quad',0)
        if found == 0, num = 1; else num = length(found)+1; end

        for newroi=1:3
            roiName = sprintf('Quad-%.0f',num+newroi-1);
            view=newROI(view,roiName,1,[0 0 0]);
            areaROI=cat(2,areaROI,{roiName});
        end

        % Now replace the ROIs with the new ROIs with appropriately
        % adjusted corners.  Simplyfied...
        for jup=1:7
            view = selectROI(view,areaROI{jup});
            view = replaceROIQuadrilateralCoords(view,corners{jup});
        end

        retPhases = [0 pi*2 pi/2 pi];
        %         retPhases = [0 pi*2 pi/2 -pi/2];

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

% /-----------------------------------------------------------------/ %
function [view, visualField, corners, retPhases, areaROI] = fit4Hemifields(view, scans, fields)
% Fit 4 adjacent hemifields -- designed as a model for
% TO1, TO2, LO2 amd LO1 + wall of LO1 and MST
        clear msg

        msg{1}  = sprintf('Select hemifield (e.g., LO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
        newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

        msg{2}  = sprintf('Select hemifield (e.g., LO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

        msg{3}  = sprintf('Select hemifield (e.g., TO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{3},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{3} = addText(msg{3},newText);

        msg{4}  = sprintf('Select hemifield (e.g., TO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{4},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{4} = addText(msg{4},newText);

        % This becomes, say, the V1/V2 function.
        % It gets its own message box and is a template for the creation of other
        % atlas creation routines.
        visualField{1} = 'hemifield';    % LO1
        visualField{2} = 'hemifield';    % LO2
        visualField{3} = 'hemifield';    % TO1
        visualField{4} = 'hemifield';    % TO2
        visualField{5} = 'upperquarterfield';    % wall of LO1
        visualField{6} = 'upperquarterfield';    % wall of TO2

        corners = {};
        for ii=1:4
            msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

            [locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
            corners{ii} = locs.corners;

            delete(msgHndl);

        end

        % LO1 LO2 border
        tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
        corners{1}(2:3,1:2)=tmp;
        corners{2}(2:3,1:2)=tmp;

        % LO2 TO1 border
        tmp=round((corners{2}(1,1:2)+corners{3}(1,1:2))/2);
        corners{2}(1,1:2)=tmp;
        corners{3}(1,1:2)=tmp;
        tmp=round((corners{2}(4,1:2)+corners{3}(4,1:2))/2);
        corners{2}(4,1:2)=tmp;
        corners{3}(4,1:2)=tmp;

        % TO1 TO2 border
        tmp=round((corners{3}(2:3,1:2)+corners{4}(2:3,1:2))/2);
        corners{3}(2:3,1:2)=tmp;
        corners{4}(2:3,1:2)=tmp;

        % wall of LO1
        corners{5}(1,:) = corners{1}(1,:);
        corners{5}(4,:) = corners{1}(4,:);
        corners{5}(2,:) = corners{5}(1,:) + round((corners{1}(1,:)-corners{1}(2,:))*0.5);
        corners{5}(3,:) = corners{5}(4,:) + round((corners{1}(4,:)-corners{1}(3,:))*0.5);

        % wall of TO2
        corners{6}(1,:) = corners{4}(1,:);
        corners{6}(4,:) = corners{4}(4,:);
        corners{6}(2,:) = corners{6}(1,:) + round((corners{4}(1,:)-corners{4}(2,:))*0.5);
        corners{6}(3,:) = corners{6}(4,:) + round((corners{4}(4,:)-corners{4}(3,:))*0.5);

        % not to exceed the area
        corners{5}(find(corners{5}<1))=1;
        corners{5}(find(corners{5}>size(view.anat,1)))=size(view.anat,1);
        corners{6}(find(corners{6}<1))=1;
        corners{6}(find(corners{6}>size(view.anat,1)))=size(view.anat,1);

        found = roiExistName(view,'Quad',0)
        if found == 0, num = 1; else num = length(found)+1; end

        for newroi=1:2
            roiName = sprintf('Quad-%.0f',num+newroi-1);
            view=newROI(view,roiName,1,[0 0 0]);
            areaROI=cat(2,areaROI,{roiName});
        end

        % Now replace the ROIs with the new ROIs with appropriately
        % adjusted corners.  Simplyfied...
        for jup=1:6
            view = selectROI(view,areaROI{jup});
            view = replaceROIQuadrilateralCoords(view,corners{jup});
        end

        retPhases = [0 pi*2 pi/2 pi];
        %         retPhases = [0 pi*2 pi/2 -pi/2];

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit4HemifieldsCommonAtlas(view, scans, fields);

        % select MT, MST, LO2 amd LO1

        visualField{1} = 'hemifield';    % TO1
        visualField{2} = 'hemifield';    % TO2
        visualField{3} = 'hemifield';    % LO2
        visualField{4} = 'hemifield';    % wall
        visualField{5} = 'hemifield';    % wall
        visualField{6} = 'hemifield';    % wall
        visualField{7} = 'hemifield';    % LO1

        corners = {};

        corners{1} = [40 50; 40 65; 80 65; 80 50];
        corners{2} = [40 80; 40 65; 80 65; 80 80];
        corners{3} = [40 50; 40 35; 80 35; 80 50];
        corners{4} = [40 80; 40 95; 80 95; 80 80];
        corners{5} = [40 50; 40 80; 20 80; 20 50];
        corners{6} = [100 80; 100 50; 80 50; 80 80];
        corners{7} = [40 20; 40 35; 80 35; 80 20];

        num=1;
        areaROI=[];
        for newroi=1:7
            roiName = sprintf('Quad-%.0f',num+newroi-1);
            view=newROI(view,roiName,1,[0 0 0]);
            areaROI=cat(2,areaROI,{roiName});
        end

        % Now replace the ROIs with the new ROIs with appropriately
        % adjusted corners.  Simplyfied...
        for jup=1:7
            view = selectROI(view,areaROI{jup});
            view = replaceROIQuadrilateralCoords(view,corners{jup});
        end

        retPhases = [0 pi*2 pi/2 pi];

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit2HemifieldsPlus2a(view, scans, fields);
% Don't know what this means. It was specified as case '2 hemifields +  2a'
% at top. I'm guessing it's just TO-1 and TO-2?
msg{1}  = sprintf('Select hemifield (e.g., TO1)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    %TO-1
visualField{2} = 'hemifield';    %TO-2
visualField{3} = 'upperquarterfield';    %LO2
visualField{4} = 'upperquarterfield';    %MST2
%         visualField{3} = 'hemifield';    %LO2
%         visualField{4} = 'hemifield';    %MST2
visualField{5} = 'hemifield';    %V3d
visualField{6} = 'hemifield';    %MST2

corners = {};
for ii=1:2
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
%         corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
%         corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
%         corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});

tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
corners{1}(2:3,1:2)=tmp;
corners{2}(2:3,1:2)=tmp;

%         corners{1}(2,1:2)=corners{1}(2,1:2)+abs(corners{1}(2,1:2)-corners{1}(3,1:2));
%         corners{1}(3,1:2)=corners{1}(3,1:2)+abs(corners{1}(3,1:2)-corners{1}(2,1:2));
%         corners{2}(2,1:2)=corners{2}(2,1:2)+abs(corners{2}(2,1:2)-corners{2}(3,1:2));
%         corners{2}(3,1:2)=corners{2}(3,1:2)+abs(corners{2}(3,1:2)-corners{2}(2,1:2));

corners{3}(1,1:2)=corners{1}(1,1:2);
corners{3}(4,1:2)=corners{1}(4,1:2);
corners{3}(2:3,1:2)=[corners{1}(1,1:2);corners{1}(4,1:2)]*2-corners{1}(2:3,1:2);

corners{4}(1,1:2)=corners{2}(1,1:2);
corners{4}(4,1:2)=corners{2}(4,1:2);
corners{4}(2:3,1:2)=[corners{2}(1,1:2);corners{2}(4,1:2)]*2-corners{2}(2:3,1:2);

corners{5}(1,1:2)=corners{1}(1,1:2);
corners{5}(2,1:2)=corners{2}(1,1:2);
corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.5-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.5);
corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

corners{6}(3,1:2)=corners{1}(4,1:2);
corners{6}(4,1:2)=corners{2}(4,1:2);
corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.5-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.5);
corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:4
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=1:6
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

retPhases = [0 pi*2 pi/2 pi];

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit2HemifieldsPlus2aCommon(view, scans, fields);
% Don't know what this means. It was specified as case '2 hemifields +  2a common'
% at top. I'm guessing it's just TO-1 and TO-2, sharing a common boundary?
msg{1}  = sprintf('Select hemifield (e.g., TO1)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    %TO-1
visualField{2} = 'hemifield';    %TO-2
visualField{3} = 'upperquarterfield';    %LO2
visualField{4} = 'upperquarterfield';    %MST2
visualField{5} = 'hemifield';    %V3d
visualField{6} = 'hemifield';    %MST2

corners = {};
for ii=1:2
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

end

corners{1}=[50 50; 50 65; 70 65; 70 50];
corners{2}=[50 80; 50 65; 70 65; 70 80];

corners{3}(1,1:2)=corners{1}(1,1:2);
corners{3}(4,1:2)=corners{1}(4,1:2);
corners{3}(2:3,1:2)=[corners{1}(1,1:2);corners{1}(4,1:2)]*2-corners{1}(2:3,1:2);

corners{4}(1,1:2)=corners{2}(1,1:2);
corners{4}(4,1:2)=corners{2}(4,1:2);
corners{4}(2:3,1:2)=[corners{2}(1,1:2);corners{2}(4,1:2)]*2-corners{2}(2:3,1:2);

corners{5}(1,1:2)=corners{1}(1,1:2);
corners{5}(2,1:2)=corners{2}(1,1:2);
corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.5-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.5);
%         corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
%         corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

corners{6}(3,1:2)=corners{1}(4,1:2);
corners{6}(4,1:2)=corners{2}(4,1:2);
corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.5-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.5);
%         corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
%         corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:4
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=1:6
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

retPhases = [0 pi*2 pi/2 pi];
%         retPhases = [0 pi*2 pi/2 -pi/2];

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_to_TO2(view, scans, fields);
% Fit 7 visual field maps: V1, V2, V3, LO-1, LO-2, TO-1, TO-2.
clear msg

newline = sprintf('\n');
pointsOrder = ['Point 1: LOW eccentricity and LOW polar angle.' newline ...
				'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
				'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
				'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{1}  = ['Select V1.' newline pointsOrder];
msg{2}  = ['Select V3v.' newline pointsOrder];
msg{3}  = ['Select V3d.' newline pointsOrder];
msg{4}  = ['Select LO2.' newline pointsOrder];
msg{5}  = ['Select TO2.' newline pointsOrder]

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';   % V1
visualField{2} = 'lowerquarterfield'; % V3v
visualField{3} = 'upperquarterfield'; % V3d
visualField{4} = 'hemifield';   % LO2
visualField{5} = 'hemifield';   % TO2
visualField{6} = 'lowerquarterfield'; % V2v
visualField{7} = 'upperquarterfield'; % V2d
visualField{8} = 'hemifield';   %LO1
visualField{9} = 'hemifield';   %TO1

corners = {};
for ii=1:5
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.200    0.1200]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

%V2v
corners{6}(1,1:2)=corners{2}(1,1:2); %from V3v
corners{6}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{6}(4,1:2)=corners{2}(4,1:2); %from V3v

%V2d
corners{7}(1,1:2)=corners{1}(1,1:2); %from V1
corners{7}(2:3,1:2)=corners{3}(2:3,1:2); %from V3d
corners{7}(4,1:2)=corners{1}(4,1:2);%from V1

%LO1
corners{8}(1,1:2)=corners{3}(1,1:2); %from V3d
corners{8}(2:3,1:2)=corners{4}(2:3,1:2); %from LO2
corners{8}(4,1:2)=corners{3}(4,1:2);%from V3d

%TO1
corners{9}(1,1:2)=corners{4}(1,1:2); %from LO2
corners{9}(2:3,1:2)=corners{5}(2:3,1:2); %from TO2
corners{9}(4,1:2)=corners{4}(4,1:2);%from LO2

%add the ROIS 6-9 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegante way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:4
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=2:9
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

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

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_to_LO2_alt(view, scans, fields);
% I'm guessing this is an alternate version of the V1->LO2 fitting?
% It fits v1/v2/v3/lo1/lo2.
msg{1}  = sprintf('Select V1.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral.\n');      msg{1} = addText(msg{1},newText);
newText = sprintf('NEW: After marking V1, continue with marking V3v, just with the same scheme.\n');msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select V3v.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select V3d.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{3} = addText(msg{3},newText);

msg{4}  = sprintf('Select LO2.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{4} = addText(msg{4},newText);

visualField{1} = 'hemifield';   % V1
visualField{2} = 'lowerquarterfield'; % V3v
visualField{3} = 'upperquarterfield'; % V3d
visualField{4} = 'hemifield';   % LO2
visualField{5} = 'lowerquarterfield'; % V2v
visualField{6} = 'upperquarterfield'; % V2d
visualField{7} = 'hemifield';   %LO1

corners = {};
for ii=1:4
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.200    0.1200]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

%V2v
corners{5}(1,1:2)=corners{2}(1,1:2); %from V3v
corners{5}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{5}(4,1:2)=corners{2}(4,1:2); %from V3v

%V2d
corners{6}(1,1:2)=corners{1}(1,1:2); %from V1
corners{6}(2:3,1:2)=corners{3}(2:3,1:2); %from V3d
corners{6}(4,1:2)=corners{1}(4,1:2);%from V1

%LO1
corners{7}(1,1:2)=corners{3}(1,1:2); %from V3d
corners{7}(2:3,1:2)=corners{4}(2:3,1:2); %from LO2
corners{7}(4,1:2)=corners{3}(4,1:2);%from V3d

%add the ROIS 6-9 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegante way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:3
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=2:9
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_to_LO2(view, scans, fields);
% fits V1, V2, V3, LO1, and LO2.
msg{1}  = sprintf('Select V1.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral.\n');      msg{1} = addText(msg{1},newText);
newText = sprintf('NEW: After marking V1, continue with marking V3v, just with the same scheme.\n');msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select lower quarter field of V3.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select upper quarter field of V3.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{3} = addText(msg{3},newText);

msg{4}  = sprintf('Select LO2.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{4} = addText(msg{4},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';   % V1
visualField{2} = 'lowerquarterfield'; % V3v
visualField{3} = 'upperquarterfield'; % V3d
visualField{4} = 'hemifield';   % LO2
visualField{5} = 'lowerquarterfield'; % V2v
visualField{6} = 'upperquarterfield'; % V2d
visualField{7} = 'hemifield';   %LO1

corners = {};
for ii=1:4
	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

%V2v
corners{5}(1,1:2)=corners{2}(1,1:2); %from V3v
corners{5}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{5}(4,1:2)=corners{2}(4,1:2); %from V3v

%V2d
corners{6}(1,1:2)=corners{1}(1,1:2); %from V1
corners{6}(2:3,1:2)=corners{3}(2:3,1:2); %from V3d
corners{6}(4,1:2)=corners{1}(4,1:2);%from V1

%LO1
corners{7}(1,1:2)=corners{3}(1,1:2); %from V3d
corners{7}(2:3,1:2)=corners{4}(2:3,1:2); %from LO2
corners{7}(4,1:2)=corners{3}(4,1:2);%from V3d

%add the ROIS 6-9 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegante way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:3
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=2:7
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

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

% /-----------------------------------------------------------------/ %
function [view, visualField, corners, retPhases, areaROI] = fitVentralV2V3V4(view, scans, fields)
% Fit the ventral V2/V3/hV4 atlas.

msg{1}  = sprintf('Select ventral V2.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select ventral V3.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n'); msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select ventral V4.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n'); msg{3} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n'); msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{3} = addText(msg{3},newText);

visualField{1} = 'upperquarterfield';   % Ventral V2
visualField{2} = 'upperquarterfield';   %Ventral V3
visualField{3} = 'upperquarterfield';   %Ventral V4

corners = {};

% Set view to show all ROI perimeters
view.ui.showROIs=-2;
view = refreshView(view);
for ii=1:3
    msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

    [locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
    corners{ii} = locs.corners;

    delete(msgHndl);
    view = refreshView(view);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
corners{3} = atlasMergeAdjacentCorners(corners{2},corners{3});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});
view = selectROI(view,areaROI{3});
view = replaceROIQuadrilateralCoords(view,corners{3});

% Use the data in the first one to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

return;


function varargout=lpcar2cc(varargin)
%
% For calling details please see v_lpcar2cc.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_lpcar2cc.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: lpcar2cc.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_lpcar2cc(varargin{:});
else
    v_lpcar2cc(varargin{:});
end


classdef PTKImageType
    % PTKImageType. An enumeration used to specify how an image should be displayed
    %
    %
    %     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
        Grayscale,  % Image is a 16-bit integer greyscale image
        Colormap,   % Image is an 8-bit integer colormap, using the Lines colormap
        Scaled,     % Image is a single-colour floating point and will be scaled between its minimum and maximum values
        Quiver      % Image is a quiver plot; each voxel has 3 component values defining a 3D vector
    end

end


% Copyright 2011 Zdenek Kalal
%
% This file is part of TLD.
%
% TLD 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.
%
% TLD 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 TLD.  If not, see <http://www.gnu.org/licenses/>.

function bb = bb_hull(bb0)

bb=[min(bb0(1,:)); ...
    min(bb0(2,:)); ...
    max(bb0(3,:)); ...
    max(bb0(4,:))];


% Read single/multi channel waveforms
% Inputs:
%   files: a cell array of files to be read. Each cell represents one
%     sentence could be a cell and could be array of files itself if it is
%     multi-channel recording. A filename may also contains the starting
%     and ending time to be read, e.g. "abc.wav 0.2 0.5" will read the
%     segment from 0.2s to 0.5s of abc.wav.
%   reader: a structure that may contains following fields
%       fs: sampling frequency, if known in advance.
%       array: set to 1 if the sentence has multiple channels
%       multiArrayFiles: set to 1 if each channel is stored in one file.
%       useChannel: an array of integers specifying which channel(s) to be
%           returned.
%
%   Author: Xiong Xiao, Nanyang Technological University, Singapore
%   Last modified: 27 Jul 2016
%
function [all_wav] = Reader_binary(files, reader)

for i=1:length(files)
    [wav] = Reader_binary_core(files{i}, reader);
    if isfield(reader, 'precision')
        switch lower(reader.precision)
            case 'int16'
                wav = StoreWavInt16(wav);
            case 'single'
                wav = single(wav);
            case 'double'
                wav = double(wav);
        end
    end
    all_wav{i} = wav;
end
end

%%
function [data] = Reader_binary_core(file, reader)

words = ExtractWordsFromString_v2(file);

selectChannel = 0;
selectTime = 0;

filename = words{1};
if length(words)==4 || length(words)==2
    channelID = str2num(words{end});
    selectChannel = 1;
end
if length(words)>=3
    time1 = str2num(words{2});
    time2 = str2num(words{3});
    selectTime = 1;
end

big_endian = ReturnFieldWithDefaultValue(reader, 'big_endian', 0);

switch lower(reader.name)
    case 'raw'
        [data] = read08(filename, big_endian);   % you have to set fs correctly in the reader.
    otherwise
        if selectTime
            [data] = reader.reader.read(filename, [time1 time2]);
        else
            [data] = reader.reader.read(filename);
        end
end

if selectChannel
    data = data(channelID,:);
end

end


function X = mohsst5_remove_land(X)

data = mohsst5_loaddata();

land = sum(~isnan(data.observations),2) == 0;

X(land,:) = [];


function [videoMeta] = readInVideoCsv(filename)
% Read the csv and convert it into a table
csvData = readtable(filename, 'Delimiter', ',');
% Initialize the tracks struct
videoMeta = {};

% Declare and initialize the extracted_meta_dictionary
videoMeta.id = int32(csvData.id);
videoMeta.frameRate = int32(csvData.frameRate);
videoMeta.locationId = int32(csvData.locationId);
videoMeta.speedLimit = double(csvData.speedLimit);
videoMeta.month = char(csvData.month);
videoMeta.weekDay = char(csvData.weekDay);
videoMeta.startTime = char(csvData.startTime);
videoMeta.duration = char(csvData.duration);
videoMeta.totalDrivenDistance = double(csvData.totalDrivenDistance);
videoMeta.totalDrivenTime = double(csvData.totalDrivenTime);
videoMeta.numVehicles = int32(csvData.numVehicles);
videoMeta.numCars = int32(csvData.numCars);
videoMeta.numTrucks = int32(csvData.numTrucks);
try
    % Extract upper Lanes
    upperCell = regexp(csvData.upperLaneMarkings, ';', 'split');
    upperCell = upperCell{1};
    cellSize = size(upperCell, 2);
    upperLanes = double.empty(cellSize, 0);
    for i = 1:size(upperCell, 2)
        cellValue = upperCell(1, i);
        upperLanes(i) = str2double(cellValue);
    end
    videoMeta.upperLanes = upperLanes;

    % Extract lower Lanes
    lowerCell = regexp(csvData.lowerLaneMarkings, ';', 'split');
    lowerCell = lowerCell{1};
    cellSize = size(lowerCell, 2);
    lowerLanes = double.empty(cellSize, 0);
    for i = 1:size(lowerCell, 2)
        cellValue = lowerCell(1, i);
        lowerLanes(i) = str2double(cellValue);
    end
    videoMeta.lowerLanes = lowerLanes;
catch
    printf("Something failed when reading the lane markings.");
end
end


function test_bug2471

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_timelockgrandaverage

load(dccnpath('/home/common/matlab/fieldtrip/data/test/bug2471.mat'));

cfg = [];
cfg.channel = 'all';
cfg.keepindividual = 'no';
cfg.method = 'within';
out_data = ft_timelockgrandaverage(cfg,block{:});


function result = hlp_cpuload
% Get the relative CPU load

% Copyright (C) Christian Kothe, SCCN, 2010, christian@sccn.ucsd.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

osbean = java.lang.management.ManagementFactory.getOperatingSystemMXBean();
result = osbean.getSystemLoadAverage() / osbean.getAvailableProcessors();


% Matlab script for RAPID equivalent commands
% please note that variables should be
% declared as global as in RAPID syntaxis
% this script demonstrates the use of functions in the matlab script. This
% script can be translated to RAPID by means of the matlab2RAPID script.
%
% IN ORDER TO SIMULATE THE PROGRAM:
%   A) FIRST, LOAD A ROBOT
%       >> robot = load_robot('abb','irb140');
%       OR
%       >> robot = load_robot('abb','irb52');
%   B) NEXT, LOAD SOME EQUIPMENT.
%       >> robot.equipment{1} = load_robot('equipment','tables/table_two_areas');
%
%   C) NOW, LOAD AN END TOOL
%       >> robot.tool= load_robot('equipment','end_tools/parallel_gripper_0');
%   D) FINALLY, LOAD A PIECE TO GRAB BY THE ROBOT
%       >> robot.piece{1}=load_robot('equipment','cylinders/cylinder_tiny');
%
%   E) IF NECESSARY, CHANGE THE POSITION AND ORIENTATION OF THE piece,
%   relative to the robot's base reference system.
%
%       >> robot.piece{1}.T0= [1 0 0 -0.1; 0 1 0 -0.5;0 0 1 0.2;0 0 0 1];
%
%   The A, B, C, D and E steps can be performed usint the 'teach' application
%   by clicking on the Load equipment, load end tool, and load piece
%   buttons.
%
% during the simulation, call simulation_open_tool; to open the tool and
% simulation_close_tool; to close it.
%
% To grip the piece, call simulation_grip_piece; and
% simulation_release_piece to release it.
%
% The call to each function must be in a correct, otherwise, the result may be
% undesired, thus, typically the correct sequence is:
% simulation_open_tool;
% (approach the piece to grab with MoveL or MoveJ)
% simulation_close_tool;
% simulation_grip_piece; --> the piece will be drawn with the robot
%
% move to a different place with MoveJ or MoveL
% simulation_open_tool;
% simulation_release_piece
%
% In RAPID, consider the use of ConfJ on, or ConfJ off, or ConfL on, or ConfL off
% in the case the controller avoids the change of configurations between target points
function practice_2_bolts
global RT_pos_ini RJ_ini RT_aprox_rec RT_pos_rec
global RT_aprox_dej RT_pos_dej TD_gripper VAR_pieza
global robot

%If desired, move the robot with respect to the world reference system
%by modifying robot.T0. Example: robot.T0(2,4)=1;

TD_gripper=[1,[[0,0,0.125],[1,0,0,0]],[0.1,[0,0,0.100],[1,0,0,0],0,0,0]];

RJ_ini=[0,0,0,0,0,0];
RT_pos_ini=[[0.044,-0.501,0.432],[0.262525,0.622008,0.673812,-0.300276],[0,0,0,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];

RT_aprox_rec=[[0.03,-0.6,0.45],[0.08,0.60337,0.79283,-0.03126],[0,0,0,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
RT_pos_rec=[[0.0345,-0.629,0.337],[0.261833,0.652321,0.67413,-0.226869],[-1,0,-1,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];

RT_aprox_dej=[[0.470,-0.460,0.500],[0.07981,0.603204,0.792983,-0.030902],[0,0,0,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];
RT_pos_dej=[[0.470,-0.460,0.450],[0.07981,0.603204,0.792983,-0.030902],[0,0,0,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];

%please: comment the following lines to avoid loading the robot and equipment in every simulation.
%Feel free to load other robots/equipments... etc.
robot = load_robot('ABB','IRB140');
%load static equipment, such as tables or
robot.equipment{1} = load_robot('equipment','tables/table_two_areas');
robot.tool= load_robot('equipment','end_tools/parallel_gripper_0');
robot.piece{1}=load_robot('equipment','objects/bolt');

%local function to init simulation variables
init_simulation;

VAR_pieza=0;
%!Reset --> abrir pinza
%!Set --> Cerrar pinza

main
end

function main()

global RJ_ini TD_gripper VAR_pieza

%inicializar pieza
VAR_pieza=0;

MoveAbsJ(RJ_ini,'vmax','z100',TD_gripper, 'wobj0');

%MoveJ(RT_pos_ini,'vmax','z100',TD_gripper, 'wobj0');

for i=1:4,
    ASIR_DEJAR();
    VAR_pieza=VAR_pieza +1;
    %local function to init simulation variables
    init_simulation;
end

end

function ASIR_DEJAR()

global  RT_aprox_rec RT_aprox_dej TD_gripper

%!Moverse a posici�n de aproximacion de recogida
MoveJ(RT_aprox_rec,'vmax','z100',TD_gripper, 'wobj0');
COGER_PIEZA;
%!Moverse a posici�n base de dejada
MoveJ(RT_aprox_dej,'vmax','z100',TD_gripper, 'wobj0');
METER_EN_CAJA;

end

function COGER_PIEZA()
global RT_aprox_rec RT_pos_rec TD_gripper

%!Ahora abrir pinza
simulation_open_tool; %Reset do1;
WaitTime(0.1);!esperar apertura
%!Coger
MoveL(RT_pos_rec,'vmax','fine',TD_gripper, 'wobj0');

%!Ahora cerrar pinza
simulation_close_tool; %Set do1;
simulation_grip_piece;

WaitTime(0.1); !esperar cierre
%!Subir por seguridad antes de ir al siguiente punto
MoveL(RT_aprox_rec,'vmax','z50',TD_gripper, 'wobj0');

end

function  METER_EN_CAJA()
global RT_pos_dej TD_gripper VAR_pieza

if VAR_pieza==0
    %Bajar para meter primera pieza
    MoveL(Offs(RT_pos_dej,0,0,-0.105),'v1000','fine',TD_gripper, 'wobj0');
elseif VAR_pieza==1
    MoveL(Offs(RT_pos_dej,-0.055,0,0),'v1000','z100',TD_gripper, 'wobj0');
    MoveL(Offs(RT_pos_dej,-0.055,0,-0.105),'v1000','fine',TD_gripper, 'wobj0');
elseif VAR_pieza==2
    MoveL(Offs(RT_pos_dej,0,-0.055,0),'v1000','fine',TD_gripper, 'wobj0');
    MoveL(Offs(RT_pos_dej,0,-0.055,-0.105),'v1000','fine',TD_gripper, 'wobj0');
else
    MoveL(Offs(RT_pos_dej,-0.055,-0.055,0),'v1000','fine',TD_gripper, 'wobj0');
    MoveL(Offs(RT_pos_dej,-0.055,-0.055,-0.105),'v1000','fine',TD_gripper, 'wobj0');
end

%Ahora abrir pinza
%yes, release the piece
simulation_open_tool; %Reset do1;
simulation_release_piece;

plot_points;

WaitTime(0.5);
%Subir por seguridad antes de ir al siguiente punto
MoveL(Offs(RT_pos_dej,0,0,0.105),'v1000','z10',TD_gripper, 'wobj0');

end

function init_simulation
global robot
robot.piece{1}.T0=eye(4);
robot.tool.Trel=eye(4);
% Now open the tool
simulation_open_tool; %Reset do1;
simulation_release_piece;
%init the position of the piece at the beginning of the simulation
robot.piece{1}.T0(1:3,4)=[0.03 -0.68 0.26]';
th=-30*pi/180;
u=[1 0 0;
   0 cos(th) -sin(th);
   0 sin(th) cos(th)];
robot.piece{1}.T0(1:3,1:3)=u;%eye(3);
%robot.tool.piece_gripped=0;
drawrobot3d(robot, robot.q);

end

function plot_points
x0=0.47;
y0=-0.46;
z0=0.45-0.155;
delta=0.055;
X=[x0 x0-delta x0 x0-delta];
Y=[y0 y0 y0-delta y0-delta];
Z=[z0 z0 z0 z0];

plot3(X', Y', Z', 'LineWidth', 5)
end


clear all;
fprintf('Compiling mex files ... ');

% Orthogonal matching pursuit
mex mex/mat_omp.c mex/perform_omp.c mex/invert.c mex/matrix_vector.c -o perform_omp_mex

disp('done.');


function l4mat_print ( m, n, a, title )

%*****************************************************************************80
%
%% L4MAT_PRINT prints an L4MAT.
%
%  Discussion:
%
%    An L4MAT is an array of L4 values.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 November 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows in A.
%
%    Input, integer N, the number of columns in A.
%
%    Input, logical A(M,N), the matrix.
%
%    Input, string TITLE, a title.
%
  l4mat_print_some ( m, n, a, 1, 1, m, n, title );

  return
end


function listString = getListString(list)
% Produce a string with list values
   listString = sprintf('%g ', list(:)');
   listString = ['[ ' listString ']'];


function kd=kronDelta(i,j)

kd=double(i==j);

%%
% _*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 idx = getDealiasingIndexes(~, N, nVars)
%GETGDEALIASINGINDEXES  % Returns indexes for dealiasing procedure (2/3-rule).
%
% See also SPINOP3.

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

toOne = floor(N/2) + 1 - ceil(N/6):floor(N/2) + ceil(N/6);
idx = false(N, N, N);
idx(toOne, toOne, toOne) = 1;
idx = repmat(idx, nVars, 1);

end


function option_num = p03_option_num ( )

%*****************************************************************************80
%
%% P03_OPTION_NUM returns the number of options for problem 3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer OPTION_NUM, the number of options.
%
  option_num = 4;

  return
end


function value = mm_header_check ( id, type, rep, field, symm )

%*****************************************************************************80
%
%% MM_HEADER_CHECK checks the header strings for a Matrix Market file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character ( len = 14 ) ID, the Matrix Market identifier.
%    This value must be '%%MatrixMarket'.
%
%    Input, character ( len = 6 ) TYPE, the Matrix Market type.
%    This value must be 'matrix'.
%
%    Input, character ( len = 10 ) REP, the Matrix Market 'representation'
%    indicator.  Possible values include:
%    'coordinate'   (for sparse data)
%    'array'        (for dense data)
%    'elemental'    (to be added)
%
%    Input, character ( len = 7 ) FIELD, the Matrix Market 'field'.
%    Possible values include:
%    'real'
%    'double'
%    'complex'
%    'integer'
%    'pattern' (for REP = 'coordinate' only)
%
%    Input, character ( len = 19 ) SYMM, the Matrix Market symmetry.
%    Possible values include:
%    'symmetric'
%    'hermitian'
%    'skew-symmetric'
%    'general'
%
%    Output, logical VALUE, is TRUE if the header checks out.
%
  FALSE = 0;
  TRUE = 1;
%
%  Test the input qualifiers.
%
  if ( s_neqi ( id, '%%MatrixMarket' ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\n' );
    fprintf ( 1, '  The value of ID was illegal:\n' );
    fprintf ( 1, '    "%s".\n', id );
    fprintf ( 1, '  Legal values are:\n' );
    fprintf ( 1, '    "%%MatrixMarket"\n' );
    value = FALSE;
    return;
  end

  if ( s_neqi ( type, 'matrix' ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\n' );
    fprintf ( 1, '  The value of TYPE was illegal:\n' );
    fprintf ( 1, '    "%s".\n', type );
    fprintf ( 1, '  Legal values are:\n' );
    fprintf ( 1, '    "matrix"\n' );
    value = FALSE;
    return
  end

  if ( ...
    s_neqi ( rep, 'coordinate' ) & ...
    s_neqi ( rep, 'array'      ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\n' );
    fprintf ( 1, '  The value of REP was illegal:\n' );
    fprintf ( 1, '    "%s".\n', rep );
    fprintf ( 1, '  Legal values are:\n' );
    fprintf ( 1, '    "array"\n' );
    fprintf ( 1, '    "coordinate"\n' );
    value = FALSE;
    return
  end

  if ( s_eqi ( rep, 'coordinate' ) )

    if ( ...
      s_neqi ( field, 'integer' ) & ...
      s_neqi ( field, 'real'    ) & ...
      s_neqi ( field, 'double'  ) & ...
      s_neqi ( field, 'complex' ) & ...
      s_neqi ( field, 'pattern' ) )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\n' );
      fprintf ( 1, '  The value of FIELD was illegal:\n' );
      fprintf ( 1, '    "%s".\n', field );
      value = FALSE;
      return
    end

  elseif ( s_eqi ( rep, 'array' ) )

    if ( ...
      s_neqi ( field, 'integer' ) & ...
      s_neqi ( field, 'real'    ) & ...
      s_neqi ( field, 'double'  ) & ...
      s_neqi ( field, 'complex' ) )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\n' );
      fprintf ( 1, '  The value of FIELD was illegal:\n' );
      fprintf ( 1, '    "%s".\n', field );
      value = FALSE;
      return
    end

  end

  if ( ...
    s_neqi ( symm, 'general'        ) & ...
    s_neqi ( symm, 'symmetric'      ) & ...
    s_neqi ( symm, 'hermitian'      ) & ...
    s_neqi ( symm, 'skew-symmetric' ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\n' );
    fprintf ( 1, '  The value of SYMM was illegal:\n' );
    fprintf ( 1, '    "%s".\n', symm );
    value = FALSE;
    return
  end

  value = TRUE;

  return
end