%% manage paths

path = strsplit(pwd,"sim_vehicle_dynamics");
path2module = strcat(path(1), "sim_vehicle_dynamics");
path2frictionmodel_folder = strcat(path2module, "\variable_friction\frictionmodel");
path2input = strcat(path2frictionmodel_folder, "\GUI\inputs");
path2output = strcat(path2frictionmodel_folder, "\GUI\outputs");

filepath2output_sldd=strcat(path2output, "\frictionmaps.sldd");
filepath2output_config=strcat(path2output, "\Gridmap_Config.txt");

%Handover Referenceline path and resolution from base workspace
Grid_mode=evalin('base', 'Grid_mode');
InterpTime=evalin('base','InterpTime');

%Set Variables

fid=fopen(filepath2output_config, 'wt');
Gridmap_Ident=zeros(3,3);

%% generate data dictionaries containing friction maps

switch Grid_mode

    case 1
        filename_1 = dir(strcat(path2input, '\1*.mat'));
    	filename_1 = filename_1.name;

        Gridmap_1 = importdata(strcat(path2input, '\', filename_1));
        Gridmap_2 = int8(zeros(size(Gridmap_1,1),size(Gridmap_1,2)));
        Gridmap_3 = Gridmap_2;
        Gridmap_4 = Gridmap_2;

        fprintf(fid, ['Gridmap_1: ', filename_1, ...
            '\nGridmap_2: 0 \nGridmap_3: 0 \nGridmap_4: 0 ']);

        fclose(fid);
        Gridmap_Ident(1:2,1:2)  = Gridmap_1(1:2,1:2);
        Gridmap_Ident(1,3)      = Gridmap_1(1,3);
        Gridmap_Ident(3,1)      = size(Gridmap_1,1);
        Gridmap_Ident(3,2)      = size(Gridmap_1,2);

    case 2
        filename_1 = dir(strcat(path2input, '\1*.mat'));
        filename_2 = dir(strcat(path2input, '\2*.mat'));
     	filename_1 = filename_1.name;
        filename_2 = filename_2.name;

        Gridmap_1 = importdata(strcat(path2input, '\', filename_1));
        Gridmap_2 = importdata(strcat(path2input, '\', filename_2));
        Gridmap_3 = int8(zeros(size(Gridmap_1,1),size(Gridmap_1,2)));
        Gridmap_4 = Gridmap_3;

        fprintf(fid, ['Gridmap_1: ', filename_1, ...
            '\nGridmap_2: ', filename_2, ...
            '\nGridmap_3: 0 \nGridmap_4: 0 ']);

        fclose(fid);
        Gridmap_Ident(1:2,1:2)  = Gridmap_1(1:2,1:2);
        Gridmap_Ident(1,3)      = Gridmap_1(1,3);
        Gridmap_Ident(3,1)      = size(Gridmap_1,1);
        Gridmap_Ident(3,2)      = size(Gridmap_1,2);

    case 3
        filename_1 = dir(strcat(path2input, '\1*.mat'));
        filename_2 = dir(strcat(path2input, '\2*.mat'));
     	filename_3 = dir(strcat(path2input, '\3*.mat'));
     	filename_1 = filename_1.name;
        filename_2 = filename_2.name;
    	filename_3 = filename_3.name;

        Gridmap_1 = importdata(strcat(path2input, '\', filename_1));
        Gridmap_2 = importdata(strcat(path2input, '\', filename_2));
        Gridmap_3 = importdata(strcat(path2input, '\', filename_3));
        Gridmap_4 = int8(zeros(size(Gridmap_1,1),size(Gridmap_1,2)));

        fprintf(fid, ['Gridmap_1: ', filename_1, ...
            '\nGridmap_2: ', filename_2, ...
            '\nGridmap_3: ', filename_3, ...
            '\nGridmap_4: 0 ']);

        fclose(fid);
        Gridmap_Ident(1:2,1:2)  = Gridmap_1(1:2,1:2);
        Gridmap_Ident(1,3)      = Gridmap_1(1,3);
        Gridmap_Ident(3,1)      = size(Gridmap_1,1);
        Gridmap_Ident(3,2)      = size(Gridmap_1,2);

    case 4
        filename_1 = dir(strcat(path2input, '\1*.mat'));
        filename_2 = dir(strcat(path2input, '\2*.mat'));
     	filename_3 = dir(strcat(path2input, '\3*.mat'));
        filename_4 = dir(strcat(path2input, '\4*.mat'));
     	filename_1 = filename_1.name;
        filename_2 = filename_2.name;
    	filename_3 = filename_3.name;
      	filename_4 = filename_4.name;

        Gridmap_1 = importdata(strcat(path2input, '\', filename_1));
        Gridmap_2 = importdata(strcat(path2input, '\', filename_2));
        Gridmap_3 = importdata(strcat(path2input, '\', filename_3));
        Gridmap_4 = importdata(strcat(path2input, '\', filename_4));

        fprintf(fid, ['Gridmap_1: ', filename_1, ...
            '\nGridmap_2: ',filename_2, ...
            '\nGridmap_3: ',filename_3, ...
            '\nGridmap_4: ',filename_4]);

        Gridmap_Ident(1:2,1:2)  = Gridmap_1(1:2,1:2);
        Gridmap_Ident(1,3)      = Gridmap_1(1,3);
        Gridmap_Ident(3,1)      = size(Gridmap_1,1);
        Gridmap_Ident(3,2)      = size(Gridmap_1,2);

end

%Create Datadict
if exist(filepath2output_sldd, 'file')==0
    myDictionaryObj = Simulink.data.dictionary.create(filepath2output_sldd);
    dDataSectObj = getSection(myDictionaryObj,'Design Data');
    addEntry(dDataSectObj,'Grid_map_1',Gridmap_1);
    addEntry(dDataSectObj,'Grid_map_2',Gridmap_2);
    addEntry(dDataSectObj,'Grid_map_3',Gridmap_3);
    addEntry(dDataSectObj,'Grid_map_4',Gridmap_4);
    addEntry(dDataSectObj,'InterpTime',InterpTime);
    addEntry(dDataSectObj,'Gridmap_Ident',Gridmap_Ident);

else
    myDictionaryObj = Simulink.data.dictionary.open(filepath2output_sldd);
    dDataSectObj = getSection(myDictionaryObj,'Design Data');
    assignin(dDataSectObj,'Grid_map_1',Gridmap_1);
    assignin(dDataSectObj,'Grid_map_2',Gridmap_2);
    assignin(dDataSectObj,'Grid_map_3',Gridmap_3);
    assignin(dDataSectObj,'Grid_map_4',Gridmap_4);
    assignin(dDataSectObj,'InterpTime',InterpTime);
    assignin(dDataSectObj,'Gridmap_Ident',Gridmap_Ident);

end

%Save Changes
saveChanges(myDictionaryObj);

%Finish
clc
"Datadict generated successfully! It is located in \frictionmodel\GUI\outputs" %#ok<NOPTS>


function kernWriteParamsToFID(kern, FID)

% KERNWRITEPARAMSTOFID Write the kernel parameters to a stream.
% FORMAT
% DESC writes kernel parameters to a stream.
% ARG kern : the kernel that the parameters are in.
% ARG FID : the stream to which parameters are written.
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2006, 2008
%
% SEEALSO : kernWriteToFID, modelWriteToFID

% KERN

if strcmp(kern.type, 'cmpnd') || strcmp(kern.type, 'tensor')
  componentKernWriteParamsToFID(kern, FID);
else
  writeIntToFID(FID, 'inputDim', kern.inputDimension);
  writeIntToFID(FID, 'numParams', kern.nParams);

  if strcmp(kern.type, 'poly') | strcmp(kern.type, 'polyard')
    writeIntToFID(FID, 'numParams', kern.degree);
  end

  fhandle = str2func([kern.type 'KernExtractParam']);
  params = fhandle(kern);
  doubleMatrixWriteToFID(params, FID);
  if isfield(kern, 'priors')
    writeIntToFID(FID, 'numPriors', length(kern.priors));
    for j=1:length(kern.priors)
      writeIntToFID(FID, 'priorIndex', kern.priors(j).index);
      priorWriteToFID(FID, prior);
    end
  else
    writeIntToFID(FID, 'numPriors', 0);
  end
end


function rx = rxOpenTSeriesFig(rx);
% rx = rxOpenTSeriesFig(rx);
%
% Open a figure to navigate across
% the currently-loaded tSeries.
%
% ras 03/05.
if ieNotDefined('rx')
    cfig = findobj('Tag','rxControlFig');
    rx = get(cfig,'UserData');
end

if ~isfield(rx,'tSeries')
    msg = 'You must load a tSeries first! See File | Load | mrVista tSeries.';
    myWarnDlg(msg);
    return
end

javaFigs=feature('javafigures');
feature('javafigures', 0);

mrGlobals;
loadSession;

% make a tSeries navigation figure
rx.ui.tSeriesFig = figure('Color','w',...
                          'Units','Normalized',...
                          'Position',[.35 .1 .3 .12],...
                          'Name','Navigate tSeries Frames');

nFrames = size(rx.tSeries,4);

labelTxt = sprintf('Session %s, Data Type %s \n Scans: %s',...
                    mrSESSION.sessionCode,dataTYPES(dt).name,num2str(scans));
rx.ui.tSeriesLabel = uicontrol('Style','text','Units','Normalized',...
                               'Position',[.1 .7 .8 .3],'String',labelTxt,...
                               'BackgroundColor',get(gcf,'Color'),...
                               'FontWeight','bold','FontAngle','italic',...
                               'FontSize',10);

rx.ui.tSeriesVol = rxMakeSlider('Current (target) frame:',[1 nFrames],[.2 .4 .6 .2],1,1);

rx.ui.tSeriesRef = rxMakeSlider('Reference (base) frame:',[1 nFrames],[.2 .1 .6 .2],1,1);

%%%%%%%%%%%%%%%%%
% set callbacks %
%%%%%%%%%%%%%%%%%
% Slider callback string (vol)
cb = 'slider = get(gcbo,''UserData'');';
cb = sprintf('%s \n val = rxSetSlider(slider);',cb);
cb = sprintf('%s \n rxSet([],''targetframe'',val);',cb);
set(rx.ui.tSeriesVol.sliderHandle,'Callback',cb);

% Edit field callback string (vol):
cb = ['val = str2num(get(gcbo,''String'')); ' cb];
set(rx.ui.tSeriesVol.editHandle,'Callback',cb);

% Slider callback string (ref)
cb = 'slider = get(gcbo,''UserData'');';
cb = sprintf('%s \n val = rxSetSlider(slider);',cb);
cb = sprintf('%s \n rxSet([],''baseframe'',val);',cb);
set(rx.ui.tSeriesRef.sliderHandle,'Callback',cb);

% Edit field callback string (ref):
cb = ['val = str2num(get(gcbo,''String'')); ' cb];
set(rx.ui.tSeriesRef.editHandle,'Callback',cb);

feature('javafigures',javaFigs);

return


clear all;
close all;
clc;
check_hopkins(@ssc_l1, 'ssc_l1');


function [meg] = read_ctf_meg4(fname, hdr, begsample, endsample, chanindx)

% READ_CTF_MEG4 reads specified samples from a CTF continous datafile
% It neglects all trial boundaries as if the data was acquired in
% non-continous mode.
%
% [meg] = read_ctf_meg4(filename, hdr, begsample, endsample)
%
% Where
%   filename	name of the datafile, including the .meg4 extension
%   header      with all data information (from read_ctf_meg4)
%   begsample   index of the first sample to read
%   endsample   index of the last sample to read
%   chanindx	index of channels to read (optional, default is all)
%
% Due to a non-dislosure agreement between CTF and the F.C. Donders Centre,
% the allowed use of this function is limited. Do not distribute this function.

% This program is provided to users of CTF MEG systems as a courtesy only. Please
% do not redistribute it without permission from CTF Systems Inc.
% This program has no warranty whatsoever.

% Copyright (C) 2003, Robert Oostenveld
%
% use global flag for feedback
global fb
if isempty(fb)
  fb = 0;
end

if begsample<1
  error('cannot read before the start of the data');
end

if endsample>hdr.nSamples*hdr.nChans*hdr.nTrials
  error('cannot read beyond the end of the data');
end

if begsample>endsample
  error('cannot read a negative number of samples');
end

if nargin<5
  % select all channels
  chanindx = 1:hdr.nChans;
end

if isempty(chanindx)
  error('no channels were specified for reading CTF data')
end

fid = fopen(fname,'r','ieee-be');

if fid == -1
  error('could not open datafile');
end

CTFformat = setstr(fread(fid,8,'char'))';
if (strcmp(CTFformat(1,1:7),'MEG41CP')==0),
    error('datafile is not in CTF MEG4 format')
end

% the data is not channel multiplexed, but stored in trials
% in each trial first all samples for channel 1 are given, then all samples of channel 2 ...
% this means that we have to read each channel for each trial

begtrial = ceil(begsample/hdr.nSamples);
endtrial = ceil(endsample/hdr.nSamples);

% this counts the files and offset if the 2GB file size boundary is encountered
multifilecount  = 0;
multifileoffset = 0;
fseek(fid, 0, 'eof');
multifilelength = ftell(fid);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read only the selected data, channel-wise
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if endtrial==begtrial
  rawbegsample = begsample - (begtrial-1)*hdr.nSamples;
  rawendsample = endsample - (begtrial-1)*hdr.nSamples;
  for chan=1:length(chanindx)
    % jump to the begin of this channel in this trial
    channeloffset = 8*(multifilecount+1)+(begtrial-1)*hdr.nSamples*4*hdr.nChans+(chanindx(chan)-1)*hdr.nSamples*4-multifileoffset;
    if channeloffset>=multifilelength
      % data goes beyond 2GB file boundary, jump to the next file
      channeloffset   = channeloffset - multifilelength+8;	% change the current offset, keep the header
      multifileoffset = multifileoffset + multifilelength;	% remember for the next trial
      multifilecount  = multifilecount + 1;			% increase the file counter
      nextname = sprintf('%s.%d_meg4', fname(1:(end-5)), multifilecount);
      fprintf('data goes beyond 2GB file boundary, continuing with %s\n', nextname);
      fclose(fid);
      fid = fopen(nextname,'r','ieee-be');
      fseek(fid, 0, 'eof');
      multifilelength = ftell(fid);				% determine the length of the current file
    end
    fseek(fid, channeloffset, 'bof');
    % jump to the first sample of interest
    fseek(fid, 4*(rawbegsample-1), 'cof');
    % read the data from this channel
    [tmp, count] = fread(fid,[(endsample-begsample+1),1],'int32');
    raw(:,chan) = tmp;
  end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read and concatenate the raw data of all trials
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else
  raw = zeros((endtrial-begtrial+1)*hdr.nSamples, length(chanindx));
  for trial=begtrial:endtrial

    if length(chanindx)==hdr.nChans & all(chanindx(:)'==1:hdr.nChans)
      % read the data from all channels
      rawbegsample = (trial-begtrial)*hdr.nSamples + 1;
      rawendsample = (trial-begtrial)*hdr.nSamples + hdr.nSamples;
      % jump to the begin of this trial
      trialoffset = 8*(multifilecount+1)+(trial-1)*hdr.nSamples*4*hdr.nChans-multifileoffset;
      if trialoffset>=multifilelength
        % data goes beyond 2GB file boundary, jump to the next file
        trialoffset   = trialoffset - multifilelength+8;	% change the current offset, keep the header
        multifileoffset = multifileoffset + multifilelength;	% remember for the next trial
        multifilecount  = multifilecount + 1;			% increase the file counter
        nextname = sprintf('%s.%d_meg4', fname(1:(end-5)), multifilecount);
        fprintf('data goes beyond 2GB file boundary, continuing with %s\n', nextname);
        fclose(fid);
        fid = fopen(nextname,'r','ieee-be');
        fseek(fid, 0, 'eof');
        multifilelength = ftell(fid);				% determine the length of the current file
      end
      fseek(fid, trialoffset, 'bof');
      [tmp, count] = fread(fid,[hdr.nSamples,hdr.nChans],'int32');
      raw(rawbegsample:rawendsample,:) = tmp;

    else
      % read the data from the selected channels
      rawbegsample = (trial-begtrial)*hdr.nSamples + 1;
      rawendsample = (trial-begtrial)*hdr.nSamples + hdr.nSamples;
      for chan=1:length(chanindx)
        % jump to the begin of this channel in this trial
        channeloffset = 8*(multifilecount+1)+(trial-1)*hdr.nSamples*4*hdr.nChans+(chanindx(chan)-1)*hdr.nSamples*4-multifileoffset;
        if channeloffset>=multifilelength
          % data goes beyond 2GB file boundary, jump to the next file
          channeloffset   = channeloffset - multifilelength+8;	% change the current offset, keep the header
          multifileoffset = multifileoffset + multifilelength;	% remember for the next trial
          multifilecount  = multifilecount + 1;			% increase the file counter
          nextname = sprintf('%s.%d_meg4', fname(1:(end-5)), multifilecount);
          fprintf('data goes beyond 2GB file boundary, continuing with %s\n', nextname);
          fclose(fid);
          fid = fopen(nextname,'r','ieee-be');
          fseek(fid, 0, 'eof');
          multifilelength = ftell(fid);				% determine the length of the current file
        end
        fseek(fid, channeloffset, 'bof');
        [tmp, count] = fread(fid,[hdr.nSamples,1],'int32');
        raw(rawbegsample:rawendsample,chan) = tmp;
      end %chan

    end %read all channels
  end %trial

  % select the raw data corresponding to the samples of interest
  rawoffset    = (begtrial-1)*hdr.nSamples;
  rawbegsample = begsample - rawoffset;
  rawendsample = endsample - rawoffset;
  raw = raw(rawbegsample:rawendsample, :);
end
fclose(fid);

% multiply the dimensionless values with the calibration value
gain = hdr.gainV(chanindx);	% only for selected channels
meg = raw';			% transpose the raw data
for i=1:size(meg,1)
  meg(i,:) = gain(i)*meg(i,:);
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D
% shape modeling and analysis toolkit.
% It is a software package developed at Shenlab in Center for Neuroimaging,
% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)
% It is available to the scientific community as copyright freeware
% under the terms of the GNU General Public Licence.
%
% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University
%
% This file is part of SPHARM-MAT.
%
% SPHARM-MAT 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.
%
% SPHARM-MAT 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 SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [inObjs1, inObjs2] = LoadObjList(inputFile)

fin = fopen(inputFile, 'rt');
inObjs1={};
inObjs2={};

[numOut, vals] = Get_Vals(fin, 'inputs', 10^6);
if numOut >0
    inObjs1 = vals;
%    set(handles.IOL_tag, 'String', handles.userdata.inObjs);
end

[numOut, vals] = Get_Vals(fin, 'inputs2', 10^6);
if numOut >0
    inObjs2 = vals;
%    set(handles.IOL_tag, 'String', handles.userdata.inObjs);
end

fclose(fin);

return;

function [numOut, vals] = Get_Vals(fInput, Keyword, NumVals)

%global userdata;

numOut = 0;
vals = {};

fseek(fInput, 0, 'bof');
delim = ' ,';

while 1
    tline = fgetl(fInput);
    if ~ischar(tline),   break,   end;
    [key, remain] = strtok(tline, delim);
    if strcmpi(strtrim(key), strtrim(Keyword))
        while numOut < NumVals
            tline = fgetl(fInput);
            if ~ischar(tline),   break,   end;
            numOut = numOut + 1;
            vals(numOut) = {deblank(tline)};
        end
        break;
    end
end

return;


classdef ReadingFilesTests < handle & matlab.unittest.TestCase

    properties (TestParameter)
        readingTests = {'testReadingGmsh'}
    end

    methods (Test, TestTags = {'ReadingFiles', 'Fast', 'Gmsh'})

        function testReading(testCase, readingTests)
            s.computerType    = 'GMSH';
            s.testName         = readingTests;
            s.variablesToStore = {'connec', 'coord', 'isElemInThisSet', ...
                                  'masterSlave', 'corners'};
            test = PrecomputedVariableTest(s);
            err = test.computeError();
            tol = 1e-13;
            testCase.verifyLessThanOrEqual(err, tol)
        end

    end

end


function anonScanS = defineAnonScan()
%
% function anonScanS = defineAnonScan()
%
% Defines the anonymous scan data structure. The fields containing PHI have
% been left out by default. In order to leave out additional fields, remove
% them from the list below.
%
% The following three operations are allowed per field of the input data structure:
% 1. Keep the value as is: listed as 'keep' in the list below.
% 2. Allow only the specific values: permitted values listed within a cell array.
%    If no match is found, a default anonymous string will be inserted.
% 3. Insert dummy date: listed as 'date' in the list below. Date will be
%    replaced by a dummy value of 11/11/1111.
%
% APA, 1/11/2018

anonScanInfoS = struct( ...
    'imageNumber', 'keep', ...
    'imageType', {{'CT SCAN'}}, ...
    'scanType', {{'TRANSVERSE'}}, ...
    'CTOffset', 'keep', ...
    'rescaleSlope', 'keep', ...
    'rescaleIntercept', 'keep', ...
    'scaleSlope', 'keep', ...
    'scaleIntercept', 'keep', ...
    'grid1Units', 'keep', ...
    'grid2Units','keep', ...
    'numberRepresentation', {{'TWO''S COMPLEMENT INTEGER'}}, ...
    'bytesPerPixel','keep', ...
    'numberOfDimensions','keep', ...
    'sizeOfDimension1', 'keep', ...
    'sizeOfDimension2', 'keep', ...
    'zValue', 'keep', ...
    'imageOrientationPatient', 'keep', ...
    'patientPosition', 'keep', ...
    'xOffset','keep', ...
    'yOffset','keep', ...
    'CTAir','keep',...
    'CTWater','keep',...
    'sliceThickness', 'keep', ...
    'scannerType', {{'GE MEDICAL SYSTEMS'}}, ...
    'headInOut', {{'In','Out'}}, ...
    'positionInScan', {{'HFS', 'HFP', 'FFS', 'FFP'}}, ...
    'bValue', 'keep', ...
    'scanDate', 'date', ...
	'CTScale', 'keep', ...
    'transferProtocol', {{'DICOM'}}, ...
    'LRflippedToMatchPACS', 'keep', ...
    'APflippedToMatchPACS', 'keep', ...
    'SIflippedToMatchPACS', 'keep', ...
    'voxelThickness', 'keep' ...
        );

anonUniformScanInfoS = struct( ...
    'sliceNumSup', 'keep', ...
    'sliceNumInf', 'keep', ...
    'supInfScansCreated', 'keep', ...
    'minCTValue', 'keep', ...
    'maxCTValue', 'keep', ...
    'sliceThickness', 'keep', ...
    'bytesPerPixel', 'keep', ...
    'grid1Units', 'keep', ...
    'grid2Units', 'keep', ...
    'numberRepresentation', {{'TWO''S COMPLEMENT INTEGER'}}, ...
    'sizeOfDimension1', 'keep', ...
    'sizeOfDimension2', 'keep', ...
    'LRflippedToMatchPACS', 'keep', ...
    'APflippedToMatchPACS', 'keep', ...
    'SIflippedToMatchPACS', 'keep', ...
    'xOffset', 'keep', ...
    'yOffset', 'keep', ...
    'CTAir', 'keep', ...
    'CTWater', 'keep', ...
    'firstZValue', 'keep' ...
        );

anonScanS = struct( ...
    'scanArray', 'keep', ...
    'scanType', {{'CT','MR','PET','US','SPECT'}}, ...
    'scanInfo', anonScanInfoS, ...
    'uniformScanInfo', anonUniformScanInfoS, ...
    'scanArraySuperior', 'keep', ...
    'scanArrayInferior', 'keep', ...
    'transM', 'keep', ...
    'scanUID', 'keep', ...
    'assocDeformUID', 'keep', ...
    'assocTextureUID', 'keep');


function [y,fs]=readflac(filename,mode)
%READWAV  Read a .FLAC format sound file [Y,FS]=(FILENAME,MODE)
%
% Input Parameters:
%
%	FILENAME gives the name of the file (with optional .WAV extension) or alternatively
%                 can be the FIDX output from a previous call to READWAV
%	MODE		specifies the following (*=default):
%
%    Scaling: 's'    Auto scale to make data peak = +-1
%             'r'    Raw unscaled data (integer values)
%             'q'    Scaled to make 0dBm0 be unity mean square
%             'p' *	 Scaled to make +-1 equal full scale
%             'o'    Scale to bin centre rather than bin edge (e.g. 127 rather than 127.5 for 8 bit values)
%                     (can be combined with n+p,r,s modes)
%             'n'    Scale to negative peak rather than positive peak (e.g. 128.5 rather than 127.5 for 8 bit values)
%                     (can be combined with o+p,r,s modes)
%
% FLAC (Free lossless audio codec) is a compressed audio file format described here:
% http://flac.sourceforge.net/

%      Copyright (C) Mike Brookes 2008
%      Version: $Id: readflac.m 8483 2016-09-13 15:48:05Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<2
    mode='p';
else
    mode = [mode(:).' 'p'];
end
dirt=voicebox('dir_temp');
[fnp,fnn,fne]=fileparts(filename);
filetemp=fullfile(dirt,[fnn '.wav']);
doscom=['"' voicebox('flac') '"' ' -d -f -o "' filetemp '" "' filename '"'];
%                     fprintf(1,'Executing: %s\n',doscom);
[doss,dosr]=dos(doscom); % run the program
if doss % test for errors
    error(sprintf('Error running DOS command: %s',doscom));
end
if exist(filetemp)~=2
    error(sprintf('No output file from: %s',doscom));
end
[y,fs]=readwav(filetemp,mode);
doscom=['del /f "' filetemp '"'];
if dos(doscom) % run the program
    error(sprintf('Error running DOS command: %s',doscom));
end


function [x,y,z,nx,ny,nz,red,green,blue] = import_3D_model(FileName,prefer_mat_file)

if(~exist(FileName,'file'))
    error('Specified file does not exist:%s',FileName);
end

if(~exist('prefer_mat_file','var'))
    prefer_mat_file = 0;
end

[pathstr, name, ext] = fileparts(FileName);

if(strcmpi(ext,'.ply'))

    % check to see if there's a .mat file corresponding to the .ply file
    ply_info = dir(FileName);
    ply_date = datenum(ply_info.date);

    [pathstr, name, ext] = fileparts(FileName);
    mat_file = [pathstr, '/' ,name, '.mat'];
    mat_info = dir(mat_file);

    mat_file_is_there = 0;
    if(length(mat_info) ~= 0) %if there is a mat file (and it is newer than the ply file)
        mat_date = datenum(mat_info.date);
        if  mat_date>ply_date
            mat_file_is_there = 1;
        end
    end

    %now try to open the right file
    if(prefer_mat_file)
        if(mat_file_is_there)
            load(mat_file);
        else
            data = nplyRead(FileName);
            save([pathstr, '/' ,name, '.mat'],'data');
            msgbox('A .mat version of your .ply file is now saved in the same location. You can use that instead!','replace');
        end
    else
        data = nplyRead(FileName);
    end

elseif(strcmpi(ext,'.mat'))
    load(FileName);
else
    error('Invalid file extension');
end

x = data.vertex.x;
y = data.vertex.y;
z = data.vertex.z;

try
    nx = data.vertex.nx;
    ny = data.vertex.ny;
    nz = data.vertex.nz;
catch
    try
        nx = data.vertex.vsfm_cnx;
        ny = data.vertex.vsfm_cny;
        nz = data.vertex.vsfm_cnz;
    catch
        nx = [];
        ny = [];
        nz = [];
    end
end

try
    red = data.vertex.r/255;
    green = data.vertex.g/255;
    blue = data.vertex.b/255;
catch
    try
        red = data.vertex.red/255;
        green = data.vertex.green/255;
        blue = data.vertex.blue/255;
    catch
        try
            red = data.vertex.diffuse_red/255;
            green = data.vertex.diffuse_green/255;
            blue = data.vertex.diffuse_blue/255;
        catch
            red = .2;
            green = .2;
            blue = .2;
        end
    end
end

if(nargout == 1)
    model.x = x;
    model.y = y;
    model.z = z;
    model.nx = nx;
    model.ny = ny;
    model.nz = nz;
    model.r = red;
    model.g = green;
    model.b = blue;

    if(isfield(data,'face'))
        model.face = data.face;
    end

    x = model;
end


function r = isinf(a)
%ISINF        Array of 1's for inf components
%
%   r = isinf(a)
%

% written  05/21/09     S.M. Rump
%

  r = reshape(any(isinf(a.t)),a.size);


global CURRENT_PROJECT
projpath = 0;
while 1
    menulist = {'Keyboard input'
        'Quit'
        'Open help'
        'Choose/create project folder\n'};
    if any(projpath) && ~isempty(CURRENT_PROJECT)
        menulist(5) = {'Load specifications from Requirements.xls\n'};
        try %#ok<TRYNC>
            load ([projpath '\Requirements.mat'])
            menulist(6) = {'Iteration menu'};
        end
    end
    mainchoice = txtmenu(['Main Menu | Current Project: '....
        CURRENT_PROJECT],menulist);

    switch mainchoice
        case 0 % keyboard
            disp('Type ''return'' or hit F5 to exit keyboard mode and return to main menu')
            disp(' ')
            keyboard;

        case 1 %quit
            break

        case 2 %help
            open([CORE_PARENT_DIR '\CORE\core_help.html'])

        case 3 % Choose or create a project to work on
            [CURRENT_PROJECT projpath] = COREchooseproject();
            %sets current directory to project folder

        case 4 % Create mission parameters and objective functions
            try
                COREmkrequirements();
            catch ME
                disp('FAILURE: error creating requirements')
                disp(ME)
                beep;
            end

        case 5 % Iterate to find the best aircraft for the job
            CORE_ITERATE(Spec);

    end

end


%RGB2HSV Dataset overload
%
%  B = RGB2HSV(A)


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

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

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

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

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

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

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

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

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

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

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

  else

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

  end

  return
end


% erplab_eegscanner
%
% PURPOSE: checks EEG dataset according to set of criteria
% Format:
% serror = erplab_eegscanner(EEG, funcname, chckmultieeg, chckemptyeeg, chckepocheeg, chckeventlist)
%
% Inputs:
%
% EEG           - EEGLAB dataset
% funcname      - function name that calls erplab_eegscanner.
%
% Criteria:
% chckmultieeg  = check for multiple dataset (md).    0= do not accept md;    1=accept only md;  2=do not care
% chckemptyeeg  = check for empty dataset (ed).       0= do not accept ed;    1=accept only ed;  2=do not care
% chckepocheeg  = check for epoched dataset (epd).    0= do not accept epd;   1=accept only epd; 2=do not care
% chcknoevents  = check for no event codes (ev).      0= do not accept if no event   1=accept if no events;
% chckeventlist = check for EVENTLIST structure (ES). 0= do not accept ES;    1=accept only ES;  2=do not care
%
% Option (parameter-value)
%
% 'ErrorMsg'   - 'popup': display popup window with error message when criteria are not met
%              - 'error': display error message (command window) when criteria are not met
%              - 'off'  ; % do not display error msg (just get outcome through "serror")
%
%
% Output:
% serror        - 0 means Ok.no problem found. 1 means criteria were not met.
%
%
% *** This function is part of ERPLAB Toolbox ***
% Author: Javier Lopez-Calderon
% Center for Mind and Brain
% University of California, Davis,
% Davis, CA
% 2009

function serror = erplab_eegscanner(EEG, funcname, chckmultieeg, chckemptyeeg, chckepocheeg, chcknoevents, chckeventlist, varargin)

serror = 0; % no problem by default
if nargin<1
        help erplab_eegscanner
        return
end

%
% Parsing inputs
%
p = inputParser;
p.FunctionName  = mfilename;
p.CaseSensitive = false;
p.addRequired('EEG');
p.addRequired('funcname',@ischar);
p.addRequired('chckmultieeg', @isnumeric);
p.addRequired('chckemptyeeg', @isnumeric);
p.addRequired('chckepocheeg', @isnumeric);
p.addRequired('chcknoevents', @isnumeric);
p.addRequired('chckeventlist',@isnumeric);
% Parameters
p.addParamValue('ErrorMsg', 'popup', @ischar);
p.parse(EEG, funcname, chckmultieeg, chckemptyeeg, chckepocheeg, chcknoevents, chckeventlist, varargin{:});

if strcmpi(p.Results.ErrorMsg, 'popup') || strcmpi(p.Results.ErrorMsg, 'on')
        errormsg = 1; % popup window with error message
elseif strcmpi(p.Results.ErrorMsg, 'error')
        errormsg = 2;       % error message
else % off
        errormsg = 0; % do not display error msg
end

title = sprintf('ERPLAB: Error at %s', funcname);
N = length(EEG);
if chckmultieeg==0 && N>1
        serror = 1;
        msgboxText =  'Unfortunately, %s does not work with multiple datasets';
        if errormsg==1
                errorfound(sprintf(msgboxText, funcname), title);
                return
        elseif errormsg==2
                error('prog:input', msgboxText, funcname)
        end
        return
end
if chckmultieeg==1 && N<2
        serror = 1;
        msgboxText =  'Unfortunately, %s only works with multiple datasets';
        if errormsg==1
                errorfound(sprintf(msgboxText, funcname), title);
                return
        elseif errormsg==2
                error('prog:input', msgboxText, funcname)
        end
        return
end

for k=1:N
        if chckemptyeeg==0 && isempty(EEG(k).data)
                msgboxText =  '%s cannot read an empty dataset!';
                serror = 1;
                break
        end
        if chckemptyeeg==1 && ~isempty(EEG(k).data)
                msgboxText =  '%s only works with empty dataset(s)';
                serror = 1;
                break
        end
        if chckepocheeg==0 && ~isempty(EEG(k).epoch)
                msgboxText =  '%s only works with continuous data';
                serror = 1;
                break
        end
        if chckepocheeg==1 && isempty(EEG(k).epoch)
                msgboxText =  '%s only works with epoched data';
                serror = 1;
                break
        end
        if chcknoevents==0 && isempty(EEG(k).event)
                msgboxText =  '%s : There is not event codes in this dataset!';
                serror = 1;
                break
        end
        if chcknoevents==1 && ~isempty(EEG(k).event)
                msgboxText =  '%s : This dataset has event codes already!';
                serror = 1;
                break
        end
        if chckeventlist~=2
                if isfield(EEG(k), 'EVENTLIST')
                        if chckeventlist==1 % accept only
                                if isempty(EEG(k).EVENTLIST)
                                        msgboxText = '%s : EEG.EVENTLIST structure is empty!';
                                        serror = 1;
                                        break
                                end
                                if isfield(EEG(k).EVENTLIST, 'eventinfo')
                                        if chckeventlist==1 && isempty(EEG(k).EVENTLIST.eventinfo)
                                                msgboxText = '%s : EVENTLIST.eventinfo structure is empty!';
                                                serror = 1;
                                                break
                                        end
                                else
                                        msgboxText =  '%s : EVENTLIST.eventinfo structure was not found!';
                                        serror = 1;
                                        break
                                end
                        else % do not accept EVENTLIST
                                if ~isempty(EEG(k).EVENTLIST)
                                        msgboxText = '%s does not work with EEG.EVENTLIST structure.';
                                        serror = 1;
                                        break
                                end
                        end
                else
                        if chckeventlist==1 % accept only
                                msgboxText =  '%s : EVENTLIST structure was not found!';
                                serror = 1;
                                break
                        end
                end
        end
end
if serror>0
        if errormsg==1
                errorfound(sprintf(msgboxText, funcname), title);
                return
        elseif errormsg==2
                error('prog:input', ['ERPLAB says: ' msgboxText], funcname)
        end
end
return


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

%%
clear; close all; clc;

%% Syntax
% |[indInternal]=getInnerVoxel(L,searchRadius,plotOn);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function incilta() % autogenerated function wrapper
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals
    report_this_filefun(mfilename('fullpath'));
    %
    %
    % make another dialog interface and call cin_lta
    %
    %initial values
    iwl3 = 1;
    nustep = 10;

    figure(mess);
    clf
    set(gcf,'Name','Movie Parameter Input ');
    set(gca,'visible','off');
    set(gcf,'pos',[ ZG.welcome_pos 400 250]);

    % creates a dialog box to input some parameters
    %
    freq_field=uicontrol('Style','edit',...
        'Position',[.80 .60 .12 .10],...
        'Units','normalized','String',num2str(iwl3),...
        'callback',@callbackfun_001);

    inp2_field=uicontrol('Style','edit',...
        'Position',[.80 .40 .12 .10],...
        'Units','normalized','String',num2str(nustep),...
        'callback',@callbackfun_002);

    close_button=uicontrol('Style','Pushbutton',...
        'Position', [.60 .05 .15 .15 ],...
        'Units','normalized','callback',@callbackfun_003,'String','Cancel');

    go_button=uicontrol('Style','Pushbutton',...
        'Position',[.25 .05 .15 .15 ],...
        'Units','normalized',...
        'callback',@callbackfun_004,...
        'String','Go');

    txt1 = text(...
        'Position',[0. 0.65 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Please input window length in years (iwl):');

    txt2 = text(...
        'Position',[0. 0.40 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Please input number of movie-frames:');

    set(gcf,'visible','on')

    function callbackfun_001(mysrc,myevt)
        % automatically created callback function from text
        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        iwl3=str2double(freq_field.String);
        freq_field.String=num2str(iwl3);
    end

    function callbackfun_002(mysrc,myevt)
        % automatically created callback function from text
        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        nustep=str2double(inp2_field.String);
        inp2_field.String=num2str(nustep);
    end

    function callbackfun_003(mysrc,myevt)
        % automatically created callback function from text
        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        zmapmenu;
    end

    function callbackfun_004(mysrc,myevt)
        % automatically created callback function from text
        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        zmap_message_center();
        runcilta;
    end

end


function [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx)

% READ_YOKAGAWA_DATA_NEW reads continuous, epoched or averaged MEG data
% that has been generated by the Yokogawa MEG system and software
% and allows that data to be used in combination with FieldTrip.
%
% Use as
%   [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx)
%
% This is a wrapper function around the function
% getYkgwData
%
% See also READ_YOKOGAWA_HEADER_NEW, READ_YOKOGAWA_EVENT

% Copyright (C) 2005, Robert Oostenveld and 2010, Tilmann Sander-Thoemmes
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

if ~ft_hastoolbox('yokogawa_meg_reader')
    ft_error('cannot determine whether Yokogawa toolbox is present');
end

% hdr = read_yokogawa_header(filename);
hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header

% default is to select all channels
if nargin<5
  chanindx = 1:hdr.channel_count;
end

handles = definehandles;

switch hdr.acq_type
  case handles.AcqTypeEvokedAve
    % dat is returned as double
    start_sample  = begsample - 1; % samples start at 0
    sample_length = endsample - begsample + 1;
    epoch_count   = 1;
    start_epoch   = 0;
    dat = getYkgwData(filename, start_sample, sample_length);

  case handles.AcqTypeContinuousRaw
    % dat is returned as double
    start_sample  = begsample - 1; % samples start at 0
    sample_length = endsample - begsample + 1;
    epoch_count   = 1;
    start_epoch   = 0;
    dat = getYkgwData(filename, start_sample, sample_length);

  case handles.AcqTypeEvokedRaw
    % dat is returned as double
    begtrial = ceil(begsample/hdr.sample_count);
    endtrial = ceil(endsample/hdr.sample_count);
    if begtrial<1
      ft_error('cannot read before the begin of the file');
    elseif endtrial>hdr.actual_epoch_count
      ft_error('cannot read beyond the end of the file');
    end
    epoch_count = endtrial-begtrial+1;
    start_epoch = begtrial-1;
    % read all the necessary trials that contain the desired samples
    dat = getYkgwData(filename, start_epoch, epoch_count);
    if size(dat,2)~=epoch_count*hdr.sample_count
      ft_error('could not read all epochs');
    end
    rawbegsample = begsample - (begtrial-1)*hdr.sample_count;
    rawendsample = endsample - (begtrial-1)*hdr.sample_count;
    sample_length = rawendsample - rawbegsample + 1;
    % select the desired samples from the complete trials
    dat = dat(:,rawbegsample:rawendsample);

  otherwise
    ft_error('unknown data type');
end

if size(dat,1)~=hdr.channel_count
  ft_error('could not read all channels');
elseif size(dat,2)~=(endsample-begsample+1)
  ft_error('could not read all samples');
end

% select only the desired channels
dat = dat(chanindx,:);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this defines some usefull constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = definehandles
handles.output = [];
handles.sqd_load_flag = false;
handles.mri_load_flag = false;
handles.NullChannel         = 0;
handles.MagnetoMeter        = 1;
handles.AxialGradioMeter    = 2;
handles.PlannerGradioMeter  = 3;
handles.RefferenceChannelMark = hex2dec('0100');
handles.RefferenceMagnetoMeter       = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter );
handles.RefferenceAxialGradioMeter   = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter );
handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter );
handles.TriggerChannel      = -1;
handles.EegChannel          = -2;
handles.EcgChannel          = -3;
handles.EtcChannel          = -4;
handles.NonMegChannelNameLength = 32;
handles.DefaultMagnetometerSize       = (4.0/1000.0);       % Square of 4.0mm in length
handles.DefaultAxialGradioMeterSize   = (15.5/1000.0);      % Circle of 15.5mm in diameter
handles.DefaultPlannerGradioMeterSize = (12.0/1000.0);      % Square of 12.0mm in length
handles.AcqTypeContinuousRaw = 1;
handles.AcqTypeEvokedAve     = 2;
handles.AcqTypeEvokedRaw     = 3;
handles.sqd = [];
handles.sqd.selected_start  = [];
handles.sqd.selected_end    = [];
handles.sqd.axialgradiometer_ch_no      = [];
handles.sqd.axialgradiometer_ch_info    = [];
handles.sqd.axialgradiometer_data       = [];
handles.sqd.plannergradiometer_ch_no    = [];
handles.sqd.plannergradiometer_ch_info  = [];
handles.sqd.plannergradiometer_data     = [];
handles.sqd.eegchannel_ch_no   = [];
handles.sqd.eegchannel_data    = [];
handles.sqd.nullchannel_ch_no   = [];
handles.sqd.nullchannel_data    = [];
handles.sqd.selected_time       = [];
handles.sqd.sample_rate         = [];
handles.sqd.sample_count        = [];
handles.sqd.pretrigger_length   = [];
handles.sqd.matching_info   = [];
handles.sqd.source_info     = [];
handles.sqd.mri_info        = [];
handles.mri                 = [];


function model = destroyDummyModel(model, dummyMetBool, dummyRxnBool, metsOrig, rxnsOrig)
% Remove all traces of dummy metabolites and reactions
%
% INPUT
% model     COBRA model
%
% OPTIONAL INPUT
% dummyMetBool      m x 1 boolean vector indicating dummy metabolites
% dummyRxnBool      n x 1 boolean vector indicating dummy reactions
% metsOrig          Array indicating the metabolites before creating a dummyModel
% rxnsOrig          Array indicating the reactions before creating dummyModel
%
% OUTPUT
% model     COBRA model without dummy metabolites or reactions
%

if nargin < 2 || isempty(dummyMetBool)
    % remove dummy metabolites
    dummyMetBool = contains(model.mets, 'dummy_Met_');
end
if nargin < 3 || isempty(dummyRxnBool)
    % Remove dummy reactions
    dummyRxnBool = contains(model.rxns, 'dummy_Rxn_');
end
% if nargin < 4 || isempty(metsOrig)
%     % Original metabolites
%     metsOrig = model.mets;
% end
% if nargin < 5 || isempty(rxnsOrig)
%     % Original reactions
%     rxnsOrig = model.rxns;
% end

if any(dummyRxnBool) || any(dummyMetBool)
    model.mets = model.mets(~dummyMetBool);
    model.S = model.S(~dummyMetBool, ~dummyRxnBool);
    model.b = model.b(~dummyMetBool);
    model.rxns = model.rxns(~dummyRxnBool);
    model.rxnNames = model.rxnNames(~dummyRxnBool);
    model.lb = model.lb(~dummyRxnBool);
    model.ub = model.ub(~dummyRxnBool);
    model.c = model.c(~dummyRxnBool);

    if isfield(model, 'csense')
        model.csense = model.csense(~dummyMetBool);
    end
    if isfield(model, 'ctrs')
        model.C = model.C(:, ~dummyRxnBool);
    end
    if isfield(model, 'rxnGeneMat')
        model.rxnGeneMat = model.rxnGeneMat(~dummyRxnBool, :);
    end
    if isfield(model, 'rules')
        model.rules = model.rules(~dummyRxnBool);
    end
    if isfield(model, 'subSystems')
        model.subSystems = model.subSystems(~dummyRxnBool);
    end
    if isfield(model, 'SIntMetBool')
        model.SIntMetBool = model.SIntMetBool(~dummyMetBool);
    end
    if isfield(model, 'SIntRxnBool')
        model.SIntRxnBool = model.SIntRxnBool(~dummyRxnBool);
    end
    if isfield(model, 'SConsistentMetBool')
        model.SConsistentMetBool = model.SConsistentMetBool(~dummyMetBool);
    end
    if isfield(model, 'SConsistentRxnBool')
        model.SConsistentRxnBool = model.SConsistentRxnBool(~dummyRxnBool);
    end
    if isfield(model, 'fluxConsistentMetBool')
        model.fluxConsistentMetBool = model.fluxConsistentMetBool(~dummyMetBool);
    end
    if isfield(model, 'fluxConsistentRxnBool')
        model.fluxConsistentRxnBool = model.fluxConsistentRxnBool(~dummyRxnBool);
    end
    if isfield(model, 'thermoFluxConsistentMetBool')
        model.thermoFluxConsistentMetBool = model.thermoFluxConsistentMetBool(~dummyMetBool);
    end
    if isfield(model, 'thermoFluxConsistentRxnBool')
        model.thermoFluxConsistentRxnBool = model.thermoFluxConsistentRxnBool(~dummyRxnBool);
    end
end

if isfield(model,'dummyMetBool')
    model = rmfield(model, 'dummyMetBool');
end
if isfield(model,'dummyRxnBool')
    model = rmfield(model, 'dummyRxnBool');
end

% model.S = model.S(~model.dummyMetBool,~model.dummyRxnBool);
% model.b = model.b(~model.dummyMetBool,1);
% model.csense = model.csense(~model.dummyMetBool,1);
% model.mets = model.mets(~model.dummyMetBool);
% model.rxns = model.rxns(~model.dummyRxnBool);
% model.rxnNames = model.rxnNames(~model.dummyRxnBool);
% model.lb = model.lb(~model.dummyRxnBool);
% model.ub = model.ub(~model.dummyRxnBool);
% model.c = model.c(~model.dummyRxnBool);
% if isfield(model, 'ctrs')
%     model.C = model.C(:,~model.dummyRxnBool);
% end
% if isfield(model, 'rxnGeneMat')
%     model.rxnGeneMat = model.rxnGeneMat(~model.dummyRxnBool,:);
% end
% if isfield(model, 'rules')
%     model.rules = model.rules(~model.dummyRxnBool);
% end
% if isfield(model,'subSystems')
%     model.subSystems = model.subSystems(~model.dummyRxnBool);
% end
% if isfield(model,'SIntRxnBool')
%     model.SIntRxnBool = model.SIntRxnBool(~model.dummyRxnBool);
% end
% if isfield(model,'SConsistentRxnBool')
%     model.SConsistentRxnBool = model.SConsistentRxnBool(~model.dummyRxnBool);
% end
% if isfield(model,'fluxConsistentRxnBool')
%     model.fluxConsistentRxnBool = model.fluxConsistentRxnBool(~model.dummyRxnBool);
% end
% if isfield(model,'thermoFluxConsistentRxnBool')
%     model.thermoFluxConsistentRxnBool = model.thermoFluxConsistentRxnBool(~model.dummyRxnBool);
% end

if exist('metsOrig','var')
    % Remove deleted mets/rxns in all the fields
    if ~isequal(model.mets, metsOrig) || ~isequal(model.rxns, rxnsOrig)
        warning('mets/rxns were not consistently deleted in all fields!')
        cbFields = fieldnames(model);
        mets2Delete = ~ismember(metsOrig, model.mets);
        rxns2Delete = ~ismember(rxnsOrig, model.rxns);
        for i = 1:length(cbFields)
            if length(metsOrig) == length(model.(cbFields{i}))
                model.(cbFields{i})(mets2Delete) = [];
            elseif length(rxnsOrig) == length(model.(cbFields{i}))
                model.(cbFields{i})(rxns2Delete) = [];
            end
        end
    end
end


function [update_flag, latest_version, latest_release_date, local_version] = check_update(local_version)

    if nargin < 1
        local_version = nmflibrary_version();
    end

    update_flag = 0;

    site_url = 'https://raw.githubusercontent.com/hiroyuki-kasai/NMFLibrary/master/auxiliary/nmflibrary_version.m';
    filename_full_local = 'dl_nmflibrary_version.m';

    connection_available = check_network_connection();
    if connection_available
        websave(filename_full_local, site_url);

        [latest_version, latest_release_date] = dl_nmflibrary_version();

        if str2double(latest_version) > str2double(local_version)
            update_flag = 1;
            %fprintf('Latest: %s, Local: %s\n', latest_version, local_version);
        else
            %fprintf('This version is latest (%s)\n', local_version);
        end

        delete dl_nmflibrary_version.m
    else
        update_flag = -1;
        latest_version = [];
        latest_release_date = [];
    end

end

function available = check_network_connection()
    available = false;
    if ispc
        [~, b] = system('ping -n 1 www.google.com');
    elseif isunix
        [~, b] = system('ping -c 1 www.google.com');
    else
        error('how did you even get Matlab to work?')
    end

    n = strfind(b, 'cannot resolve');
    if n > 0
    else
        available = true;
    end
end


function h = mrvPanel(loc, sz, par, units, varargin);
%
% h = mrvPanel([loc], [sz], [par], [units], [other properties]);
%
% UI tool for mrVista 2.0:
% Add a uipanel (for a group of related controls
% or axes) to a parent figure/other object in the
% specified position,  while maintaining the size of
% the other objects in the figure. Returns a handle
% to the panel.
%
% loc: string specifying where to add the panel. Can be
% 'top', 'bottom', 'left', 'right'. [Default 'right'] The
% panel will cover the entire width (for 'top' or 'bottom')
% or height (for 'left' or 'right') of the object,  and will
% make the figure larger.
%
% sz: number specifying the width or height of the panel,  in the
% panel's units (see below). [Default 0.1,  normalized]
%
% par: parent object. Usually a figure,  but could theoretically
% be another uipanel (nesting panels within panels). [Default gcf]
%
% units: units to specify for the panel. [Default 'normal',  normalized
% to par object] But could be e.g. 'char' for characters
% or 'pixels' for pixels relative to corner of par object.
%
% NOTE: if 'normalized' units are specified,  this is taken
% to mean 'normalized with respect to parent object',
% rather than 'normalized w.r.t. screen': e.g.,  if sz=0.25,
% this means the panel size will be a quarter the size of
% the figure,  not make the figure take up a quarter more
% of the screen.
%
%
% OPTIONAL PROPERTIES:
% There are many other properties of uipanels which may
% be useful to GET/SET; see HELP UIPANEL or DOC UIPANEL
% for more info. You may set these properties when you call
% mrvPanel by specifying them in the optional arguments, in pairs
% of 'PropertyName', [Value], ... See the example below.
%
% EXAMPLES:
%
% h = mrvPanel('below', 2, gcf, 'char');
%
% adds a panel 2 characters high beneatch the current
% figure,  colored white and with a frame titled 'My Panel'.
%
% h2 = mrvPanel('right', .3, gcf, 'char', 'BackgroundColor', 'w', ...
%              'Title', 'My Panel');
%
% adds a panel to the right side of the current figure, at 30% its length,
% colored white and with a frame titled 'My Panel'.
%
% SEE ALSO:
% uipanel,  uicontrol,  uibuttongroup,  mrvShowPanel.
%
% ras,  07/05/05.
% ras,  09/25/06: allows panel properties to be set at creation.

% default arguments
if ~exist('loc', 'var') | isempty(loc),  loc = 'right';               end
if ~exist('sz', 'var') | isempty(sz),  sz = 0.1;                      end
if ~exist('par', 'var') | isempty(par),  par = gcf;                   end
if ~exist('units', 'var') | isempty(units),  units = 'normalized';    end

% check that the location arg makes sense
if ~ismember(lower(loc), {'above' 'below' 'left' 'right'})
    help(mfilename);
    error('Unrecognized location argument.');
end

% get the dimension along which the figure will be
% added (index into position vector):
switch lower(loc)
    case {'above', 'below'},  dim = 4;
    case {'left', 'right'},  dim = 3;
end
corner = dim-2; % index into position vector of corner

% get size of parent object in same units as panel:
exUnits = get(par,  'Units'); % existing units
set(par,  'Units',  units);
exPos = get(par,  'Position'); % existing position in same units as panel
exSize = exPos(dim); % size in same units as panel

% parse 'normalized' units to be w.r.t. figure;
% also,  set it so that the specified size is the
% fraction the figure takes after resizing:
% E.g.,  if sz is 1/2,  make the figure twice as big,
% one half of which is the new panel; NOT make it
% one-and-a-half times as big,  with one third being the
% new panel:
if strncmp(lower(units),  'norm',  4)
    sz = 1 / (1/sz - 1); % makes the specified sz proportion of final size
    sz = sz * exSize;
end

% figure out how much bigger the par will need to be
% to accommodate the new panel
newSize = exSize + sz; % fig size after adding panel

% meanwhile,  the 'panelSize' variable will describe the
% panel's size in normalized units relative to the parent.
% Also set this such that the
panelSize = sz/newSize; % if units were 'norm',  this should = the original
                        % value of sz

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% resize the parent object %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get new size -- make larger
newPos = exPos;
newPos(dim) = newSize;

% for panels in the below or left locations,  move the corner  back,
% so existing objects% stay in the same place on the screen
if ismember(lower(loc), {'left' 'below'})
    newPos(corner) = exPos(corner) - exPos(dim)/(1/panelSize+1);
end

% set the new parent position
set(par, 'Position', newPos);

% check that the new size doesn't push the figure off the
% screen edge -- if so,  move back:
figOffscreenCheck(gcf);

% get all existing child objects of the par object,
% so we can adjust their relative sizes
objs = findobj('Parent',  par,  'Type',  'uicontrol');
objs = [objs; findobj('Parent',  par,  'Type',  'axes')];
objs = [objs; findobj('Parent',  par,  'Type',  'uipanel')];

% existing objects in the parent will need to be shrunk
% along the relevant dimension by an amount corresponding
% to the growth of the par:
for i = 1:length(objs)
    objUnits = get(objs(i),  'Units');
    set(objs(i),  'Units',  'normalized'); % deal in normalized units for now
    objPos = get(objs(i),  'Position');   % pre-shrinking position
    objPos(dim) = objPos(dim) * (1-panelSize);

    % to keep existing panels flush with one another,
    % even after shrinking,  we need to nudge panels back:
    if objPos(corner) > 0
        objPos(corner) = objPos(corner) * (1-panelSize);
    end

    % for these locations,  need to move the corners
    % of existing objects forward as well:
    if ismember(lower(loc),  {'left' 'below'})
        objPos(corner) = objPos(corner) + panelSize;
    end

    set(objs(i),  'Position',  objPos);
    set(objs(i),  'Units',  objUnits); % restore previous unit convention
end

% figure out the position of the new panel
set(par, 'Units', 'normalized');
switch lower(loc)
    case 'above',  pos = [0 exSize/newSize 1 panelSize];
    case 'below',  pos = [0 0 1 panelSize];
    case 'left',  pos = [0 0 panelSize 1];
    case 'right',  pos = [exSize/newSize 0 panelSize 1];
end
set(par, 'Units', exUnits); % restore previous unit convention

% finally,  add the new panel
h = uipanel('Units', 'Normalized', 'Position', pos, ...
            'UserData', lower(loc), 'FontSize', 14, ...
			'BackgroundColor', get(gcf, 'Color'), ...
            'BorderType', 'none', 'Parent', par);
set(h, 'Units', units);

% set properties according to any optional arguments
for i = 1:2:length(varargin)
    set(h, varargin{i}, varargin{i+1});
end

return


% Script: call_bootfitF.m
% -----------------------
% Script to input parameters for a single Omori law fit
% Calculation is done in function calc_bootfitF
% The function works on the catalog newt2!!!
% J.Woessner
% last update: 10.07.03

report_this_filefun(mfilename('fullpath'));
% Get input parameters
prompt  = {,'Enter length of learning period (days)','Enter forecast period (days):','Enter number of bootstraps:'};
title   = 'Parameters ';
lines= 1;
def     = {'50','50','100'};
answer  = inputdlg(prompt,title,lines,def);
time = str2double(answer{1});
timef = str2double(answer{2});
bootloops = str2double(answer{3});

% maepi is the mainshock of sequence
calc_bootfitF(newt2,time,timef,bootloops,maepi)


function status=mrInitRetFromFSL_NIC(procScans,SessionName,subjectName)
%   status=mrInitRetFromFSL(foundScans,SessionName,subjectName)
%   creates a MLR session out of a mixture of Dicom and analyze files
%   this mixture is the result of the prepareUCSF script that preprocesses
%   the functional data from the UCSF scanner, but leaves the inplanes
%   as Dicom.
%   2006.04.20 Mark Schira (mark@ski.org) wrote it.
% 061407: ARW Modified it to use the new pipeline for processing data from
% the NIC.
% Found scans will contain a sparse list of processed scans that can be
% found in ./Reconned.
% The functional data will be in _4d.hdr files. The inplanes will be in a
% _3d file. There may be other data sets there (T1s etc taken during the
% same session).
% First we will identify the inplane scans. Then we will do the
% functionals.

mrGlobals
HOMEDIREC = pwd;

doCrop=0;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get the inplane anatomies
% We can read the volume siye from the header. Maybe other info as well.
% The inplane data should be in the dataPath named anat.hdr/img

InplaneDir=0;
% find the InplaneDir
for thisScan=1:length(procScans)
    if (~isempty(procScans{thisScan}))
    if strcmp(procScans{thisScan}.Action,'Inplanes')
        InplaneDir=thisScan; %take the last if several are set
    end
    end

end
%get the anatomy
%anatDir=[HOMEDIREC,filesep,procScans{InplaneDir}.DirName];
if (~InplaneDir)
    % Prompt for an analyze file that serves as an inplane ref
    [fname,pathname]=uigetfile('*.img','Pick Analyze/Nifti format 3d file');
	 if isnumeric(fname)
		 % try again?
	    [fname,pathname]=uigetfile('*.img','Pick Analyze/Nifti format 3d file');
		 if isnumeric(fname)
			 return
% 			 keyboard		% sometimes dialog never shows up??? fname=pathname=0 then GetAnatomyFromAnalyze crashes
		 end
	 end
    fname=fullfile(pathname,fname);
else
    fname=[procScans{InplaneDir}.Filename3d,'.img'];
end

[anat, inplanes] = GetAnatomyFromAnalyze(fname);
% %since cropping is anoying
inplanes.cropSize=inplanes.fullSize;
inplanes.crop=cat(1,[1 1],inplanes.fullSize);

%AnatomySize=size(anat);
% Save anat
anatFile = fullfile(HOMEDIREC, 'Inplane', 'anat.mat');
save(anatFile, 'anat', 'inplanes');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get the functionals
functScans=[];
for thisScan=1:length(procScans)
    if (~isempty(procScans{thisScan}))
        if strcmp(procScans{thisScan}.Action,'Functional')
            functScans=cat(2,functScans,thisScan); %take the last if several are set

        end
    end

end

% put information about the functionals here. I tried to make this independent of the DICOM format but in the end I needed to get at least the TR from that header.
% I know that the individual analyze vols should have the TR as the 4th
% dimension. Something to work on...

timesRot90 = 1;
for thisScan=1:length(functScans)
    scanParams(thisScan).hdr=spm_vol([procScans{functScans(thisScan)}.Filename4d,'.img']);
    scanParams(thisScan).imatrix=spm_imatrix(scanParams(thisScan).hdr(1).mat); % imatrix decomposes the analyze (nifti) header into its components.
    scanParams(thisScan).fullSize=scanParams(thisScan).hdr(1).dim; %#ok<AGROW>
	 if rem(timesRot90,2)
		 scanParams(thisScan).fullSize = scanParams(thisScan).fullSize([2 1 3]);
     end
%      if (ieNotDefined('procScans{functScans(thisScan)}.SkipVols'))
%          disp('Warning - we did not find a .SkipVols field in procScans');
%
%          procScans{functScans(thisScan)}.SkipVols=0;
%      else
          fprintf('\nSkipping %d vols\n',procScans{functScans(thisScan)}.SkipVols);
%      end

    scanParams(thisScan).junkFirstFrames=procScans{functScans(thisScan)}.SkipVols;
    scanParams(thisScan).nFrames=procScans{functScans(thisScan)}.Volumes-procScans{functScans(thisScan)}.SkipVols;
% We don't crop these days. Perhaps we could get rid of that crop param
% altogether?
    scanParams(thisScan).cropSize=scanParams(thisScan).fullSize(1:2);
    scanParams(thisScan).crop=cat(1,[1 1],scanParams(1).fullSize(1:2));
    scanParams(thisScan).TR=procScans{functScans(thisScan)}.hdr{1}.RepetitionTime;
    scanParams(thisScan).PfileName=procScans{functScans(thisScan)}.hdr{1}.SeriesNumber;
    scanParams(thisScan).framePeriod=scanParams(thisScan).TR/1000; % this is in seconds
    scanParams(thisScan).slices=1:procScans{functScans(thisScan)}.Slices;
	 scanParams(thisScan).effectiveResolution = abs(scanParams(thisScan).imatrix(7:9));		% voxel dimensions (mm)
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create/load mrSESSION and dataTYPES, modify them, and save

% If mrSESSION already exits, load it.
sessionFile = fullfile(HOMEDIREC, 'mrSESSION.mat');
if exist(sessionFile, 'file')
    loadSession;
    % if docrop, make sure that the mrSESSION is up-to-date
    if doCrop
        mrSESSION.inplanes = inplanes;
        mrSESSION = UpdateSessionFunctionals(mrSESSION,scanParams);
        saveSession;
    end
end

% If we don't yet have a session structure, make a new one.
if (~exist('mrSESSION','var'))
    mrSESSION = CreateNewSession(HOMEDIREC, inplanes, mrLoadRetVERSION);
end

if isempty(mrSESSION)
    mrSESSION = CreateNewSession(HOMEDIREC, inplanes, mrLoadRetVERSION);
end

% Update mrSESSION.functionals with scanParams corresponding to any new Pfiles.
% Set mrSESSION.functionals(:).crop & cropSize fields
mrSESSION = UpdateSessionFunctionals(mrSESSION,scanParams,0);

% this lines replace then EditSession command. One gui-window less to bother
mrSESSION.description=SessionName;
mrSESSION.subject=subjectName;

saveSession;

% Create/edit dataTYPES
if ieNotDefined('dataTYPES')
    dataTYPES = CreateNewDataTypes(mrSESSION);
else
    dataTYPES = UpdateDataTypes(dataTYPES,mrSESSION);
end

% Save any changes that may have been made to mrSESSION & dataTYPES
saveSession;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extract time series
mrVista('inplane');
v=getSelectedInplane;

for thisScan=1:length(functScans)
    analyzeNum=functScans(thisScan);
    inFile=procScans{analyzeNum}.Filename4d; % This has a trailing .hdr part
    %make sure there is a .hdr at the end...
    [pathstr, name, ext, versn]=fileparts(inFile);
    inFile=[pathstr,filesep,name,'.hdr'];
    disp(inFile)
    volsToSkip=mrSESSION.functionals(thisScan).junkFirstFrames;
    scaleFact=[1];
    v=read4dAnalyzeToTseries(v,inFile,thisScan,volsToSkip,0,timesRot90,0); % No slice flip, 3 90 deg rotations
end

% When we only recon some of thedata, this will crash because functScans
% does not contain entries for the missing data set but we try to access
% them three lines lower down from here.
for thisScan=1:length(dataTYPES(1).blockedAnalysisParams)
    dataTYPES(1).blockedAnalysisParams(thisScan).temporalNormalization=0;
    dataTYPES(1).blockedAnalysisParams(thisScan).nCycles=procScans{functScans(thisScan)}.Cycles;
    dataTYPES(1).eventAnalysisParams(thisScan).eventAnalysis=0;
end
saveSession;

status=1;


function test_bug896

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_multiplotTFR ft_prepare_layout ft_datatype ft_datatype_freq

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

ft_checkdata(stat_coh, 'datatype', 'freq');
ft_checkdata(stat_coh_full, 'datatype', 'freq');
ft_checkdata(stat_coh, 'datatype', 'freq', 'cmbstyle', 'full');
ft_checkdata(stat_coh_full, 'datatype', 'freq', 'cmbstyle', 'full');

if ~ft_datatype(stat_coh, 'freq')
  error('ft_datatype failed on the "stat_coh" input data');
end

if ~ft_datatype(stat_coh_full, 'freq')
  error('ft_datatype failed on the "stat_coh_full" input data');
end

figure
ft_multiplotTFR(cfg, stat_coh);
close

figure
ft_multiplotTFR(cfg, stat_coh_full);
close


%% Template Matlab script to create an BIDS compatible _bold.json file
% This example lists all required and optional fields.
% When adding additional metadata please use CamelCase
% Use version of DICOM ontology terms whenever possible.
%
% DHermes, 2017

% Writing json files relies on the JSONio library
% https://github.com/bids-standard/bids-matlab
%
% Make sure it is in the matab/octave path
try
    bids.bids_matlab_version;
catch
    warning('%s\n%s\n%s\n%s', ...
            'Writing the JSON file seems to have failed.', ...
            'Make sure that the following library is in the matlab/octave path:', ...
            'https://github.com/bids-standard/bids-matlab');
end

%%

clear;

this_dir = fileparts(mfilename('fullpath'));
root_dir = fullfile(this_dir, '..', filesep, '..');

project = 'templates';

sub_label = '01';
ses_label = '01';
task_label = 'FullExample';
run_label = '01';

name_spec.modality = 'func';
name_spec.suffix = 'bold';
name_spec.ext = '.json';
name_spec.entities = struct('sub', sub_label, ...
                            'ses', ses_label, ...
                            'task', task_label, ...
                            'run', run_label);

% using the 'use_schema', true
% ensures that the entities will be in the correct order
bids_file = bids.File(name_spec, 'use_schema', true);

% Contrust the fullpath version of the filename
json_name = fullfile(root_dir, project, bids_file.bids_path, bids_file.filename);

%% Adding metadata
% to get the definition of each metadata,
% you can use the bids.Schema class from bids matlab

% For example
schema = bids.Schema;
def = schema.get_definition('TaskName');
fprintf(def.description);

%% Required fields
json.TaskName = 'FullExample';
json.RepetitionTime = [];

%% Required fields if using a fieldmap
json.PhaseEncodingDirection = '';
json.EffectiveEchoSpacing = [];
json.EchoTime = [];

%% Recommended fields:

%% Scanner Hardware metadata fields
json.Manufacturer = '';
json.ManufacturersModelName = '';
json.MagneticFieldStrength = [];
json.DeviceSerialNumber = '';
json.StationName = ' ';
json.SoftwareVersions = ' ';
json.HardcopyDeviceSoftwareVersion = '';
json.ReceiveCoilName = ' ';
json.ReceiveCoilActiveElements = '';
json.GradientSetType = '';
json.MRTransmitCoilSequence = '';
json.MatrixCoilMode = '';
json.CoilCombinationMethod = '';

%% Sequence Specifics metadata fields
json.PulseSequenceType = '';
json.ScanningSequence = '';
json.SequenceVariant = '';
json.ScanOptions = '';
json.SequenceName = '';
json.PulseSequenceDetails = '';
json.NonlinearGradientCorrection = '';

%% In-Plane Spatial Encoding metadata fields
json.NumberShots = [];
json.ParallelReductionFactorInPlane = '';
json.ParallelAcquisitionTechnique = '';
json.PartialFourier = '';
json.PartialFourierDirection = '';
json.WaterFatShift = '';
json.EchoTrainLength = '';

%% Timing Parameters metadata fields
json.InversionTime = [];
json.SliceEncodingDirection = '';
json.DwellTime = [];
json.TotalReadoutTime = [];
json.DelayAfterTrigger = [];
json.NumberOfVolumesDiscardedByScanner = [];
json.NumberOfVolumesDiscardedByUser = [];

%% RF & Contrast metadata field
json.FlipAngle = [];

%% Slice Acceleration metadata field
json.MultibandAccelerationFactor = [];

%% Task metadata field
json.Instructions = '';
json.TaskDescription = '';
json.CogAtlasID = 'https://www.cognitiveatlas.org/FIXME';
json.CogPOID = 'http://www.cogpo.org/ontologies/CogPOver1.owl#FIXME';

%% Institution information metadata fields
json.InstitutionName = '';
json.InstitutionAddress = '';
json.InstitutionalDepartmentName = '';

%% Write JSON
% Make sure the directory exists
bids.util.mkdir(fileparts(json_name));
bids.util.jsonencode(json_name, json);


function data = getSubSet(data, id_subset)
% SYNTAX
%   data = getSubSet(data, id_subset)
%
% DESCRIPTION
%   return the array with the given ids

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     Andrea Gatti ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

    data = data(id_subset);
end


function sonorobot(r,ns,ds,mapoff)
if nargin<4
mapoff=false;
if nargin<3
ds=.1;
if nargin<2
ns=24;
if nargin<1;
r=.37;
end
end
end
end
clf reset
shg
set(gcf,'menubar','none',...%[0    0.2850    0.3985]
    'numbertitle','off','name','Sono Robot');
t_n=uicontrol('style','toggle','position',[35,65,25,25],...
    'string','N');
t_s=uicontrol('style','toggle','position',[35,5,25,25],...
    'string','S');
t_w=uicontrol('style','toggle','position',[5,35,25,25],...
    'string','W');
t_e=uicontrol('style','toggle','position',[65,35,25,25],...
    'string','E');
t_ne=uicontrol('style','toggle','position',[65,65,25,25],...
    'string','NE');
t_se=uicontrol('style','toggle','position',[65,5,25,25],...
    'string','SE');
t_sw=uicontrol('style','toggle','position',[5,5,25,25],...
    'string','SW');
t_nw=uicontrol('style','toggle','position',[5,65,25,25],...
    'string','NW');
t_start=uicontrol('style','toggle','position',[505,35,50,25],...
    'string','Auto');
t_quit=uicontrol('style','toggle','position',[505,5,50,25],...
    'string','Quit');
msg1=uicontrol('style','text','position',[120,5,345,55]);
msg2=uicontrol('style','text','position',[120,65,345,25],...
    'string','Measurement results...','fontsize',11.5,...
    'horizontal','left');
% orderdisp=['1st';'2nd';'3th';'4th';'5th';'6th';'7th';'8th';'9th';'0th'];
drawnow
hold on
axisx=12.5;
axisy=10;
axis([0 axisx 0 axisy]);
axis off

%Note:
%distance from one point to line:
%x=(x0*(x1-x2)^2+(x2*(-y0+y1)+x1*(y0-y2))*(y1-y2))/(x1^2-2*x1*x2+x2^2+(y1-y2)^2);
%y=(x2^2*y1+y0*y1^2+x0*(x1-x2)*(y1-y2)+x1^2*y2-2*y0*y1*y2+y0*y2^2-x1*x2*(y1+y2))/(x1^2-2*x1*x2+x2^2+(y1-y2)^2);

%Input environment & robot position
%Environment
nmax=50;
stpmax=100;
segset=zeros(nmax,4);%line segment set:[Ax,Ay,Bx,By]
areax=1;
areay=.5;
dftarea=[axisx-areax,axisy-areay;axisx-areax,axisy;axisx,axisy;axisx,axisy-areay];
okarea=[axisx-areax,axisy-2*areay;axisx-areax,axisy-areay;axisx,axisy-areay;axisx,axisy-2*areay];
fill(okarea(:,1),okarea(:,2),'k')
fill(dftarea(:,1),dftarea(:,2),'w')
stt=true;%true: on, ready to insert; false: off, waiting for the 2nd point
polygon=false;%%
n=0;%number of segments
%debug%
mdldisp=['A_1';'A_2';'A_3';'B_1';'B_2';'B_3';'B_4';'B_5';'B_6';'C  ';...
    'D_1';'D_2';'D_3';'D_4';'E  ';'nil';'DK '];
%--%
while n<=nmax
    %display current operation
    if n==0
        set(msg1,'string',['Insert the first edge. Or click the white '...
            'area and load default data.'],'fontsize',11.5,'horizontal','left');
    else
        if stt
            set(msg1,'string',['Insert a new line: The ',orderdisp(n+1),...
                ' edge. First end point. Or click the black area to finish.'],...
                'fontsize',11.5,'horizontal','left');
        else
            set(msg1,'string',['Insert a new line: The ',orderdisp(n),...
                ' edge. Second end point.'],'fontsize',11.5,...
                'horizontal','left');
        end
    end
    %ginput
    [x,y]=ginput(1);
    if (x-(axisx-areax))*(x-axisx)<0&&(y-(axisy-2*areay))*(y-(axisy-areay))<0||((x-(axisx-areax))*(x-axisx)<0&&(y-(axisy-areay))*(y-axisy)<0&&n==0)
        break
    end
    plot(x,y,'ro')
    if stt
        n=n+1;
        segset(n,1:2)=[x,y];
    else
        segset(n,3:4)=[x,y];
        plot(segset(n,[1,3]),segset(n,[2,4]),'b');
    end
    stt=~stt;
end
if n~=nmax
    segset=segset(1:n,:);
end

%default map
dftmap=[2,2,2,7;2,7,3,8;3,8,8,8;8,8,8,2;8,2,4,2;4,2,4,6;4,6,6,6;6,6,6,4];
if n==0
    segset=dftmap;
    n=8;
end

%Robot
% display current operation
set(msg1,'string','Set original position of the robot. Or click the white area and load default data.',...
    'fontsize',11.5,'horizontal','left');
[rx,ry]=ginput(1);
if (rx-(axisx-areax))*(rx-axisx)<0&&(ry-(axisy-areay))*(ry-axisy)<0
    rx=5;
    ry=5;
end
plot(rx,ry,'ro')
a=2*pi/ns;

%Probing & Moving
set(msg1,'string','Looking for exit...','fontsize',11.5,'horizontal','left');
rtrack=zeros(stpmax,2);rtrack(1,:)=[rx,ry];
start=false;
stp=0;
istouch=false;
while ~get(t_quit,'value')
    if ~get(t_start,'value')
        v_n=get(t_n,'value');
        v_s=get(t_s,'value');
        v_w=get(t_w,'value');
        v_e=get(t_e,'value');
        v_ne=get(t_ne,'value');
        v_se=get(t_se,'value');
        v_sw=get(t_sw,'value');
        v_nw=get(t_nw,'value');
        if any([v_n,v_s,v_w,v_e,v_ne,v_se,v_sw,v_nw])||~start
            start=true;
            dir=find([v_n,v_s,v_w,v_e,v_ne,v_se,v_sw,v_nw]);
            if dir
            %movement detected
            rxo=rx;
            ryo=ry;
            switch dir(1)
                case 1
                    ry=ry+ds;
                    set(t_n,'value',0)
                case 2
                    ry=ry-ds;
                    set(t_s,'value',0)
                case 3
                    rx=rx-ds;
                    set(t_w,'value',0)
                case 4
                    rx=rx+ds;
                    set(t_e,'value',0)
                case 5
                    rx=rx+ds;
                    ry=ry+ds;
                    set(t_ne,'value',0)
                case 6
                    rx=rx+ds;
                    ry=ry-ds;
                    set(t_se,'value',0)
                case 7
                    rx=rx-ds;
                    ry=ry-ds;
                    set(t_sw,'value',0)
                case 8
                    rx=rx-ds;
                    ry=ry+ds;
                    set(t_nw,'value',0)
            end
            if approachwall(segset,[rx,ry],2*r)
                set(msg1,'string','Approaching wall...',...
                    'fontsize',11.5,'horizontal','left');
            else
                set(msg1,'string','Searching exit...',...
                    'fontsize',11.5,'horizontal','left');
            end
            [istouch,~]=approachwall(segset,[rx,ry],r);
            if istouch
                set(msg1,'string','Robot has touched wall... Move back.',...
                    'fontsize',11.5,'horizontal','left');
                rx=rxo;
                ry=ryo;
            end
            end
            if ~istouch
                stp=stp+1;
                if stp>stpmax
                    rtrack=[rtrack;zeros(stpmax,2)];
                    stpmax=2*stpmax;
                end
%                 %debug%
%                 disp(stp)
%                 %--%
                rtrack(stp,:)=[rx,ry];
                %reprobe
                rs=sonomeasure(segset,[rx,ry],polygon,ns);
                [modelpt,mptadd,finished,mdl]=sonomodel(rs,r);%!!
                %redraw
                cla
                % environment
                if ~mapoff
                    for k=1:n
                        plot(segset(k,[1,3]),segset(k,[2,4]),'--r','LineWidth',2)
                    end
                end
                % probing data
                for k=1:ns
                    plot(rx+rs(k)*cos(((k-1):.1:k)*a),ry+rs(k)*sin(((k-1):.1:k)*a),'b:')
                end
                plot(rx,ry,'ro');%text(rx-.15,ry-.15,'Robot');
                plot(rx+r*cos((0:.1:2)*pi),ry+r*sin((0:.1:2)*pi),'b','LineWidth',1.45);
                % model report
                mdlrpt=[0 0];
                for k=1:ns
                    if finished(k)
                        plot(rx+modelpt(k,[1,3]),ry+modelpt(k,[2,4]),'k','LineWidth',1.5)
                        switch mdl(k)
                            case {1,2,3}
                                plot(rx+(rs(k)-.2)*cos((k-1:.1:k)*a),ry+(rs(k)-.2)*sin((k-1:.1:k)*a),'c','LineWidth',2.5);
                                mdlrpt(1)=1;
                            case {4,5,6,7,8,9}
                                plot(rx+(rs(k)-.2)*cos((k-1:.1:k)*a),ry+(rs(k)-.2)*sin((k-1:.1:k)*a),'g','LineWidth',2.5);
                                mdlrpt(2)=1;
                        end
                    end
                end
                for k=1:size(mptadd,1)
                    plot(rx+mptadd(k,[1,3]),ry+mptadd(k,[2,4]),'k','LineWidth',1.5)
                end
                if mdlrpt(1)&&mdlrpt(1)
                    set(msg2,'string','Faultages found...',...
                        'fontsize',11.5,'horizontal','left');
                elseif mdlrpt(1)
                    set(msg2,'string','Faultages on two sides...',...
                        'fontsize',11.5,'horizontal','left');
                elseif mdlrpt(2)
                    set(msg2,'string','Faultages on one side...',...
                        'fontsize',11.5,'horizontal','left');
                else
                    set(msg2,'string','Measurement results...',...
                        'fontsize',11.5,'horizontal','left');
                end
                % robot track
                plot(rtrack(1:stp,1),rtrack(1:stp,2),'b:')
                %debug%
                % report model
                for k=1:ns
                    text(rx+rs(k)*cos((k-.5)*a),ry+rs(k)*sin((k-.5)*a),mdldisp(mdl(k),:))
                end
            end
        end
    else
%         %test
%         pause(0.5)
%         beep
        %--%
        %Auto Move

    end
    pause(0.01);
end
close
end


function []=v2structDemo2()
%  V2STRUCTDEMO2 is a usage example demo function for the function V2STRUCT. This demo
%  shows a suggestion for how to use v2struct in managing input to other functions with
%  improved usability.
%
%% Last update:
%    30.06.2011, Adi N.

fprintf(['Running usage demo function for vs2truct function:\n',...
         '\nThis demo shows a suggestion for how to use v2struct in managing input to',...
         ' other functions\nwith improved usability. Please read comments in the .m file for explanations\n',...
         'Press any key between breaks.\n']);
pause()

fprintf('\nOutput from four statements:\n');
pause()
% See the differences between calling foo and fooSmart using v2struct
% Note that we expect the same results in the following statements

% regular call to foo
foo(1,2,3,4);

% pack to structure and call with fooSmart
S = v2struct(1,2,3,4,{'fieldNames','num1','denum1','num2','denum2'});
fooSmart(S);

% regular call to fooSmartParamOrder
fooSmartParamOrder(1,2,3,4);

% call with structure to fooSmartParamOrder
fooSmartParamOrder(S);

% Consider the following functions

% foo is a function with regular construction using arguments passed in a defined order
% the result is that you have to call it with 4 arguments, and you must remember their order.
 function isFirstBiggerThanSecond = foo(num1,denum1,num2,denum2)
 isFirstBiggerThanSecond = (num1/denum1>num2/denum2);
 fprintf('\n using foo with a regular call:\n')
 if isFirstBiggerThanSecond
    fprintf('  %d/%d is bigger than %d/%d\n',num1,denum1,num2,denum2);
 else
    fprintf('  %d/%d is not bigger than %d/%d\n',num1,denum1,num2,denum2);
 end

% Now consider the function fooSmart which is modified just slightly to accept input
% packed in a structure. You get the same result but you can use a structure.
    function isFirstBiggerThansSecond = fooSmart(num1,denum1,num2,denum2)
 if isstruct(num1) % unpack if called with a structure
    v2struct(num1);
 end
 isFirstBiggerThansSecond = (num1/denum1>num2/denum2);
 fprintf('\n using fooSmart with a structure:\n')
 if isFirstBiggerThansSecond
    fprintf('  %d/%d is bigger than %d/%d\n',num1,denum1,num2,denum2);
 else
    fprintf('  %d/%d is not bigger than %d/%d\n',num1,denum1,num2,denum2);
 end

% Lastly the function fooSmartParamOrder represent a situation in which the order of the
% parameters is changed in relation to foo. Here calling regularly with the same variables
% as before leads to an erroneous result. However when using the structure as input the
% order is not important and you get the correct result.
     function isFirstBiggerThansSecond = fooSmartParamOrder(num1,num2,denum1,denum2)
 if isstruct(num1) % unpack if called with a structure
    v2struct(num1);
    fprintf('\n using fooSmartParamOrder with structure:\n')
 else
     fprintf('\n using fooSmartParamOrder with same variables:\n')
 end
 isFirstBiggerThansSecond = (num1/denum1>num2/denum2);
 if isFirstBiggerThansSecond
    fprintf('  %d/%d is bigger than %d/%d\n',num1,denum1,num2,denum2);
 else
    fprintf('  %d/%d is not bigger than %d/%d\n',num1,denum1,num2,denum2);
 end


function handles = dtiCmapInit(handles)
% Initialize color maps for mrDiffusion (dtiFiberUI)
%
% handles:  The dtiFiberUI handles
%
%   handles = dtiCmapInit(handles)
%
% Called in dtiFiberUI startup.  Not elsewhere.
%
% Brian (c) VISTASFOT Team, 2012

% I wonder if we need a cmap structure for the future?

handles.cmaps(1).name = 'autumn';
handles.cmaps(1).rgb = autumn(256);
handles.cmaps(2).name = 'winter';
handles.cmaps(2).rgb = winter(256);
handles.cmaps(3).name = 'spring';
handles.cmaps(3).rgb = spring(256);
handles.cmaps(4).name = 'summer';
handles.cmaps(4).rgb = summer(256);
handles.cmaps(5).name = 'hot';
handles.cmaps(5).rgb = hot(256);
handles.cmaps(6).name = 'cool';
handles.cmaps(6).rgb = cool(256);
handles.cmaps(7).name = 'gray';
handles.cmaps(7).rgb = gray(256);
handles.cmaps(8).name = 'red';
handles.cmaps(8).rgb = vividColormap(256,[0.15 0.85],'r');
handles.cmaps(9).name = 'green';
handles.cmaps(9).rgb = vividColormap(256,[0.15 0.85],'g');
handles.cmaps(10).name = 'blue';
handles.cmaps(10).rgb = vividColormap(256,[0.15 0.85],'b');
handles.cmaps(11).name = 'cyan';
handles.cmaps(11).rgb = vividColormap(256,[0.15 0.85],'c');
handles.cmaps(12).name = 'magenta';
handles.cmaps(12).rgb = vividColormap(256,[0.15 0.85],'m');
handles.cmaps(13).name = 'yellow';
handles.cmaps(13).rgb = vividColormap(256,[0.15 0.85],'y');

end


function install_sedumi( varargin )

%SeDuMi installation script
%
% Heavy rewrite by Michael C. Grant for SeDuMi 1.34
% Now detects if binaries are already
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA

need_rebuild = any( strcmp( varargin, '-rebuild' ) );

targets64={...
    'bwblkslv.c sdmauxFill.c sdmauxRdot.c',...
    'choltmpsiz.c',...
    'cholsplit.c',...
    'dpr1fact.c auxfwdpr1.c sdmauxCone.c  sdmauxCmp.c sdmauxFill.c sdmauxScalarmul.c sdmauxRdot.c blkaux.c',...
    'symfctmex.c symfct.c',...
    'ordmmdmex.c ordmmd.c',...
    'quadadd.c',...
    'sqrtinv.c sdmauxCone.c',...
    'givensrot.c auxgivens.c sdmauxCone.c',...
    'urotorder.c auxgivens.c sdmauxCone.c sdmauxTriu.c sdmauxRdot.c',...
    'psdframeit.c reflect.c sdmauxCone.c sdmauxRdot.c sdmauxTriu.c sdmauxScalarmul.c',...
    'psdinvjmul.c reflect.c sdmauxCone.c sdmauxRdot.c sdmauxTriu.c sdmauxScalarmul.c blkaux.c',...
    'bwdpr1.c sdmauxCone.c sdmauxRdot.c',...
    'fwdpr1.c auxfwdpr1.c sdmauxCone.c sdmauxScalarmul.c',...
    'fwblkslv.c sdmauxScalarmul.c',...
    'qblkmul.c sdmauxScalarmul.c',...
    'blkchol.c blkchol2.c sdmauxFill.c sdmauxScalarmul.c',...
    'vecsym.c sdmauxCone.c',...
    'qrK.c sdmauxCone.c sdmauxRdot.c sdmauxScalarmul.c',...
    'finsymbden.c sdmauxCmp.c',...
    'symbfwblk.c',...
    'ddot.c sdmauxCone.c sdmauxRdot.c sdmauxScalarmul.c',...
    'partitA.c sdmauxCmp.c',...
    'getada1.c sdmauxFill.c',...
    'getada2.c sdmauxCone.c sdmauxRdot.c sdmauxFill.c',...
    'getada3.c spscale.c sdmauxCone.c sdmauxRdot.c sdmauxScalarmul.c sdmauxCmp.c',...
    'adendotd.c sdmauxCone.c',...
    'adenscale.c',...
    'extractA.c',...
    'sortnnz.c sdmauxCmp.c',...
    'iswnbr.c',...
    'incorder.c',...
    'findblks.c sdmauxCone.c sdmauxCmp.c',...
    'invcholfac.c triuaux.c sdmauxCone.c sdmauxRdot.c sdmauxTriu.c sdmauxScalarmul.c blkaux.c',...
    };

fs = filesep;
mpath = mfilename('fullpath');
mpath = mpath( 1 : max([1,strfind(mpath,fs)]) - 1 );
ISOCTAVE = exist('OCTAVE_VERSION','builtin');
VERSION  = [1,0.01]*sscanf(version,'%d.%d');
if ISOCTAVE, prog = 'Octave'; else prog = 'Matlab'; end
COMPUTER = computer;
mext = mexext;

%
% We don't want to rebuild the binaries if they're already present, unless
% the user has specifically asked for a rebuild. Frankly, we can't
% guarantee that rebuilding will work.
%

if ISOCTAVE,
    page_output_immediately( true, 'local' );
end

line = '---------------------------------------------------------------------------';
fprintf( '\n%s\nSeDuMi installation script\n   Directory: %s\n   %s %s on %s\n%s\n', ...
    line, mpath, prog, version, COMPUTER, line );

if ~need_rebuild,
    fprintf( 'Looking for existing binaries...' );
    mdir = '';
    if ISOCTAVE && VERSION > 3.08,
        if ispc,
            mdir = 'o_win32';
        elseif ismac,
            mdir = 'o_mac32';
        elseif isunix && any( strfind( COMPUTER, 'linux' ) ),
            mdir = 'o_lin32';
        end
        if ~isempty(mdir) && strncmpi( COMPUTER, 'x86_64', 6 ),
            mdir(end-1:end) = '64';
        end
        if ~exist( [ mpath, fs, mdir ], 'dir' ),
            mdir = '';
        end
    end
    nfound = [ 0, 0 ];
    for k = 1 : length(targets64),
        targ = targets64{k};
        targ = [ targ(1:min(strfind(targ,'.'))), mext ];
        if exist( [ mpath, fs, targ ], 'file' ),
            nfound(1) = nfound(1) + 1;
        elseif ~isempty(mdir) && exist( [ mpath, fs, mdir, fs, targ ], 'file' ),
            nfound(2) = nfound(2) + 1;
        end
    end
    if sum(nfound) == 0,
        fprintf( 'none found; building...\n' );
        need_rebuild = true;
    elseif sum(nfound) < length(targets64),
        fprintf( 'incomplete set found.\n' );
        disp( line );
        disp( 'Some of the binaries for this platform were found, but some' );
        disp( 'were missing as well. This may mean your download was corrupt;' );
        disp( 'consider downloading and unpacking SeDuMi again. Otherwise, to' );
        disp( 'try rebuilding the MEX files yourself, run this command:' );
        disp( '    install_sedumi -rebuild' );
        fprintf( '%s\n\n', line );
        return;
    else
        fprintf( 'found!\n' );
        fprintf( '   If for some reason you need to rebuild the binaries, use this command:\n' );
        fprintf( '      install_sedumi -rebuild\n' );
    end
else
    nfound = [1,0];
end

if need_rebuild,
    disp( 'Attempting to recompile the SeDuMi binaries:' );
    % Note the use of 0.01 here. That's because version 7 had more than 10
    % minor releases, so 7.10-7.14 need to be ordered after 7.01-7.09.
    IS64BIT  = ~ISOCTAVE & strcmp(COMPUTER(end-1:end),'64');
    if ispc,
        flags = {'-DPC'};
    elseif isunix,
        flags = {'-DUNIX'};
    end
    libs = {};
    if ISOCTAVE,
        % Octave has mwSize and mwIndex hardcoded in mex.h as ints.
        % There is no definition for mwSignedIndex so include it here.
        % This means that Octave ignores the -largeArrayDims flag.
        if VERSION < 3.08,
            flags{end+1} = '-DmwSignedIndex=int';
        end
        libs{end+1} = '-lblas';
    else
        flags{end+1} = '-O';
        if IS64BIT && ( VERSION >= 7.03 ),
            flags{end+1} = '-largeArrayDims';
        elseif VERSION < 7.03,
            flags{end+1} = '-DmwIndex=int';
            flags{end+1} = '-DmwSize=int';
            flags{end+1} = '-DmwSignedIndex=int';
        end
        if VERSION >= 7 && ispc,
            if IS64BIT, dirval = 'win64'; else dirval = 'win32'; end
            libdir = [ matlabroot, fs, 'external', fs, 'lib', fs, dirval, fs ];
            if exist( [ libdir, 'microsoft' ], 'dir' ),
                libdir = [ libdir, 'microsoft' ];
                found = true;
            elseif exist( [ libdir, 'msvc60' ], 'dir' ),
                libdir = [ libdir, 'msvc60' ];
                found = true;
            elseif exist( [ libdir, 'lcc' ], 'dir' ),
                libdir = [ libdir, 'lcc' ];
                found = true;
            end
            if found,
                libs{end+1} = [ '-L"', libdir, '"' ];
            end
        end
        if VERSION >= 7.05,
            libs{end+1} = '-lmwblas';
        else
            libs{end+1} = '-lmwlapack';
        end
    end
    libs = sprintf( ' %s', libs{:} );
    flags = sprintf( ' %s', flags{:} );
    olddir = pwd;
    cd( mpath );
    failed = false;
    fprintf( 'Template: mex%s <sources>%s\n', flags, libs );
    for i=1:length(targets64),
        targ = targets64{i};
        mfile = [ targ(1:min(strfind(targ,'.'))), mext ];
        temp = [ 'mex ', flags, ' ', targets64{i}, libs ];
        fprintf( '   %s: %s\n', mfile, targ );
        eval( temp, 'failed=true;' ); %#ok
    end
    cd( olddir );
    if failed,
        fprintf( 'At least one compilation failure occurred.\n' );
        nfound = [0,0];
    else
        fprintf( 'Compilation successful.\n' );
        nfound = [1,0];
    end
end

if any(nfound),
    disp( line );
    fprintf( 'Adding SeDuMi to the %s path:\n', prog );
    ps = pathsep;
    pp = [ ps, path, ps ];
    already = true;
    fprintf( '   Base directory...' );
    if ~any(strfind(pp,[ps,mpath,ps])),
        already = false;
        pp = [ pp, mpath, ps ];
        fprintf( 'added.\n' );
    else
        fprintf( 'already there.\n' );
    end
    if nfound(2),
        fprintf( '   Binaries directory...' );
        if nfound(2) && ~any(strfind(pp,[ps,mpath,fs,mdir,ps])),
            already = false;
            pp = [ pp, mpath, fs, mdir, ps ];
            fprintf( 'added.\n' );
        else
            fprintf( 'already there.\n' );
        end
    end
    fprintf( '   Conversion directory...' );
    if ~any(strfind(pp,[ps,mpath,fs,'conversion',ps])),
        already = false;
        pp = [ pp, mpath, fs, 'conversion', ps ];
        fprintf( 'added.\n' );
    else
        fprintf( 'already there.\n' );
    end
    fprintf( '   Examples directory...'  );
    if ~any(strfind(pp,[ps,mpath,fs,'examples',ps])),
        already = false;
        pp = [ pp, mpath, fs, 'examples', ps ];
        fprintf( 'added.\n' );
    else
        fprintf( 'already there.\n' );
    end
    if ~already,
        path(pp);
        fprintf( 'Please save the %s path if you want to use SeDuMi from any directory.\n', prog );
    end
    disp( line );
    disp('SeDuMi has been succesfully installed.' );
    disp( 'For more information, type "help sedumi" or see the user guide.')
else
    disp( line );
    disp( 'SeDuMi was not successfully installed.' );
    disp( 'Please attempt to correct the errors and try again.' );
end

fprintf('%s\n\n',line);


%% string get_algorithm_name_by_number(int)
% algorithm_id - int
% algorithm_name - string
%
function [algorithm_name] = get_algorithm_name_by_id(algorithm_id)
  %clear all; clc; algorithm_id = 'FPCP';
  L = load_algorithm_list();
  [m,n] = size(L{1,1});
  algorithm_name = '';
  for i = 1 : m
    a_id = strtrim(char(L{1,2}(i)));
    a_name = strtrim(char(L{1,3}(i)));
    %disp([algorithm_id '<->' a_id]);
    if(strcmp(algorithm_id,a_id))
      algorithm_name = a_name;
      break;
    end
  end
end


function truth = isexpandable2row(obj, n)

truth = isscalar(obj) || (isvector(obj) && length(obj)==n);