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

%%
clear; close all; clc;

%% Syntax
% |[varargout]=patchMarchDistMapIterative(varargin);|

%% 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 z = colon( x, y )

if ~isa( x, 'cvxdual' ),
    z = cvx( x );
    d = y;
elseif ~isa( y, 'cvxdual' ),
    z = cvx( y );
    d = x;
else
    error( 'Usage: <dual var> : <expression> or <expression> : <dual var>' );
end

if inuse( d ),
    nm = cvx_subs2str( name( d ) );
    error( [ 'Dual variable "', nm(2:end), '" has already been used.' ] );
else
    z = setdual( z, name( d ) );
end

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function s=openRawGeneralVolumeWindow
%
% Opens a new volume window and initializes the corresponding data
% structure.
%
% VOLUME is a cell array of volume structures.
% s is the index of the new one.
%
% This function should ONLY be called by either:
% openVolumeWindow or openGrayWindow.
%
% Modifications:
%
% djh and baw, 7/98
% djh, 2/99 modified to enable the window to be opened under
% either volume or gray mode
%
% djh, 4/99
% - Eliminate overlayClip sliders
% - Added mapWin sliders to show overlay only for pixels with parameter
%   map values that are in the appropriate range.
% bw, 12/29/00
% - scan slider instead of buttons
% djh 2/13/2001
% - open multiple volume windows simultaneously

% Make sure the global variables exist

mrGlobals
disp('Initializing Volume view')

% s is the index of the new volume structure.
s = getNewViewIndex(VOLUME);

% Set name, viewType, & subdir
VOLUME{s}.name=['VOLUME{',num2str(s),'}'];
VOLUME{s}.viewType='generalGray';
VOLUME{s}.subdir='generalGray';
if(isfield(mrSESSION,'sessionCode'))
  VOLUME{s}.sessionCode=mrSESSION.sessionCode;
else
  VOLUME{s}.sessionCode='';
end

% Refresh function, gets called by refreshScreen
VOLUME{s}.refreshFn = 'refreshView';

%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize data slots %
%%%%%%%%%%%%%%%%%%%%%%%%%

% Should be VOLUME{s} = viewInit('VOLUME');

%Initialize slot for anat
VOLUME{s}.anat = [];

% Initialize slots for co, amp, and ph
VOLUME{s}.co = [];
VOLUME{s}.amp = [];
VOLUME{s}.ph = [];
VOLUME{s}.map = [];
VOLUME{s}.mapName = '';
VOLUME{s}.mapUnits = '';

% Initialize slots for tSeries
VOLUME{s}.tSeries = [];
VOLUME{s}.tSeriesScan = NaN;
VOLUME{s}.tSeriesSlice = NaN;

% Initialize ROIs
VOLUME{s}.ROIs = [];
VOLUME{s}.selectedROI = 0;

% Initialize curDataType
VOLUME{s}.curDataType = 1;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make displayModes and color maps %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Initialize displayModes
VOLUME{s}=resetDisplayModes(VOLUME{s});
VOLUME{s}.ui.displayMode='anat';

%%%%%%%%%%%%%%%%%%%
% Open the window %
%%%%%%%%%%%%%%%%%%%
% Figure number for volume view window
figName = sprintf('Volume %i: %s  [%s]',s,...
                  mrSESSION.sessionCode,...
                  mrSESSION.description);

% open the figure
VOLUME{s}.ui.figNum=figure('MenuBar','none','Units','Normalized',...
                    'Color',[.9 .9 .9],'Position',[0.25 0.25 0.5 0.5],...
                    'NumberTitle','off','Name',figName);

% Handle for volume view window
VOLUME{s}.ui.windowHandle = gcf;

% Handle for main axis of volume view
VOLUME{s}.ui.mainAxisHandle = gca;

% Adjust position and size of main axes so there's room for
% buttons, colorbar, and sliders
set(VOLUME{s}.ui.mainAxisHandle,'position',[0.1 0.1 0.725 0.7]);

% Set minColormap property so there's potentially room for 128
% colors
set(VOLUME{s}.ui.windowHandle,'minColormap',128)

% Sharing of colors seems like it might be OK, but I'm turning it
% off just to be sure (djh, 1/26/98).
set(gcf,'sharecolors','off');

% Set closeRequestFcn so we can clean up when the window is closed
set(gcf,'CloseRequestFcn','closeVolumeWindow');

% Set selectedVOLUME when click in this window
set(gcf,'WindowButtonDownFcn',['selectedVOLUME =',num2str(s),';']);

%%%%%%%%%%%%%
% Add Menus %
%%%%%%%%%%%%%
disp('Attaching menus')
VOLUME{s}=filesMenu(VOLUME{s});
VOLUME{s}=editMenu(VOLUME{s});
VOLUME{s}=windowMenu(VOLUME{s});
VOLUME{s}=analysisMenu(VOLUME{s});
VOLUME{s}=viewMenu(VOLUME{s});
VOLUME{s}=roiMenu(VOLUME{s});
VOLUME{s}=plotMenu(VOLUME{s});
VOLUME{s}=colorMenu(VOLUME{s});
VOLUME{s}=xformVolumeMenu(VOLUME{s});
VOLUME{s}=segmentationMenu(VOLUME{s});

%%%%%%%%%%%%%%%%%%%%%%%%%
% Add Annotation String %
%%%%%%%%%%%%%%%%%%%%%%%%%
VOLUME{s} = makeAnnotationString(VOLUME{s});

%%%%%%%%%%%%%%%%%
% Add Color Bar %
%%%%%%%%%%%%%%%%%
% Make color bar and initialize it to 'off'
VOLUME{s}.ui.colorbarHandle=makeColorBar(VOLUME{s});
setColorBar(VOLUME{s},'off');
VOLUME{s}.ui.cbarRange = [];
% move to nicer location
set(VOLUME{s}.ui.colorbarHandle,'Position',[0.2 0.85 0.6 0.03]);

%%%%%%%%%%%%%%%
% Add Buttons %
%%%%%%%%%%%%%%%
disp('Attaching buttons')

% Buttons and editable text fields for choosing slice number and
% slice orientation
VOLUME{s} = makeVolSliceUI(VOLUME{s});
setCurSliceOri(VOLUME{s},1);

% zoom buttons
VOLUME{s} = makeZoomButtons(VOLUME{s});
VOLUME{s} = makeDomainButton(VOLUME{s});

%%%%%%%%%%%%%%%%%%%
% Add popup menus %
%%%%%%%%%%%%%%%%%%%
disp('Attaching popup menus')
VOLUME{s} = makeROIPopup(VOLUME{s});
VOLUME{s} = makeDataTypePopup(VOLUME{s});

%%%%%%%%%%%%%%%
% Add sliders %
%%%%%%%%%%%%%%%
disp('Attaching sliders')

% Scan number slider
w = 0.12; h = 0.04; l = 0; b = 0.95;
VOLUME{s} = makeSlider(VOLUME{s},'scan',[],[l b w h]);
VOLUME{s} = initScanSlider(VOLUME{s},1);
VOLUME{s} = selectDataType(VOLUME{s},VOLUME{s}.curDataType);

% correlation threshold:
VOLUME{s} = makeSlider(VOLUME{s},'cothresh',[0,1],[.85,.85,.15,.05]);
setCothresh(VOLUME{s},0);

% phase window:
VOLUME{s} = makeSlider(VOLUME{s},'phWinMin',[0,2*pi],[.85,.75,.15,.05]);
VOLUME{s} = makeSlider(VOLUME{s},'phWinMax',[0,2*pi],[.85,.65,.15,.05]);
setPhWindow(VOLUME{s},[0 2*pi]);

% parameter map window:
VOLUME{s} = makeSlider(VOLUME{s},'mapWinMin',[0,1],[.85,.55,.15,.05]);
VOLUME{s} = makeSlider(VOLUME{s},'mapWinMax',[0,1],[.85,.45,.15,.05]);
setMapWindow(VOLUME{s},[0 1]);

% anatClip: determines clipping of the anatomy base-image
%           values to fill the range of available grayscales.
VOLUME{s} = makeSlider(VOLUME{s},'anatMin',[0,1],[.85,.2,.15,.05]);
VOLUME{s} = makeSlider(VOLUME{s},'anatMax',[0,1],[.85,.1,.15,.05]);
setAnatClip(VOLUME{s},[0 .5]);

% Time or freq vals
% This is a complicated slider: It chooses values from the cell array in
% dataTYPES. These values indicate the current data to display in the
% window.
% For example, dataTYPES{1}.generalAnalysisParams(1).temporalAnalysis=[1:256];
%              dataTYPES{1}.generalAnalysisParams(1).frequencyAnalysis={[1 3 5],[2 4
%              6],[1:10],[60]}
% Depending on whether FFTCheckBox is set, this slider can assume values
% from 1 to 256 or from 1 to 4. As the slider is moved, the correct data is
% computed on the fly from the timeseries, the inverse and view.mesh.vertexGrayMap.
% It might be smart to store both the timeseries and the FFT separately in
% so that we don't have to compute the FFT each time. On the other hand,
% for reasonable size datasets (128*512 say..) the FFT takes only
% 1/10 sec.
% Note that unlike the regular gray view, this view >must< have the mesh loaded.
% You can do this (without displaying it) using meshLoad
w = 0.12; h = 0.04; l = 0; b = 0.65;
VOLUME{s} = makeSlider(VOLUME{s},'datavals',[0,1],[l b w h]);
VOLUME{s} = initDataValsSlider(VOLUME{s},1);
%VOLUME{s} = selectDataType(VOLUME{s},VOLUME{s}.curDataType);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize display parameters %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize image field
VOLUME{s}.ui.image = [];

% Show all ROIs
VOLUME{s}.ui.showROIs = 2;

%%%%%%%%%%%%%%%%%%
% Load Anatomies %
%%%%%%%%%%%%%%%%%%
VOLUME{s} = loadAnat(VOLUME{s});

%%%%%%%%%%%%%%%%%%
% Refresh screen %
%%%%%%%%%%%%%%%%%%
VOLUME{s}=refreshScreen(VOLUME{s});
disp('Done initializing Volume view')

return;


function s=mergestruct(s1,s2)
%
% s=mergestruct(s1,s2)
%
% merge two struct objects into one
%
% author: Qianqian Fang, <q.fang at neu.edu>
% date: 2012/12/22
%
% input:
%      s1,s2: a struct object, s1 and s2 can not be arrays
%
% output:
%      s: the merged struct object. fields in s1 and s2 will be combined in s.
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

if(~isstruct(s1) || ~isstruct(s2))
    error('input parameters contain non-struct');
end
if(length(s1)>1 || length(s2)>1)
    error('can not merge struct arrays');
end
fn=fieldnames(s2);
s=s1;
for i=1:length(fn)
    s=setfield(s,fn{i},getfield(s2,fn{i}));
end


function [ctf] = ctf_channel_sets(ctf);

% ctf_channel_sets - Define CTF MEG sensor regions
%
% ctf = ctf_channel_sets(ctf)
%
% This function parses the resource information in ctf.sensor,
% which is returned from ctf_read_res4
%
% INPUTS
%
%   ctf - the struct created by ctf_read_res4
%
% OUTPUTS
%
%   ctf.sensor.index - various regional sensor indices
%
%      <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%      <                                                      >
%      <                    DISCLAIMER:                       >
%      <                                                      >
%      < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. >
%      < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR   >
%      <                    OFFICIAL USE.                     >
%      <                                                      >
%      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
%

% $Revision: 1.1 $ $Date: 2009-01-30 03:49:26 $

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

% Modified: 02/2004, Darren.Weber_at_radiology.ucsf.edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%ver = '$Revision: 1.1 $';
%fprintf('\nCTF_CHANNEL_SETS [v %s]\n',ver(11:15)); tic;

if ~exist('ctf','var'),
  ctf = ctf_folder;
end

if ~isfield(ctf,'setup'),
  ctf = ctf_read_res4(ctf.folder);
end

%-------------------------------------------------------------
% Find channel types and define channel sets, see the
% System Administrators .pdf, 'Channel Sets Configuration'

%types = unique([ctf.sensor.info.index])
% 0     1     5     9    11    17
%for typeValue = types,
%  index  = find([ctf.sensor.info.index] == typeValue);
%  labels = ctf.sensor.info(index).label;
%end

% ctf.SensorNames = {...
%     'Ref Magnetometer',... % Sensor Type Index of 0
%     'Ref Gradiometer' ,... % Index of 1
%     ''  ,...               % 2
%     '' ,...                % 3
%     '' ,...                % 4
%     'MEG Sensor',...       % 5
%     '' ,...                % 6
%     '',...                 % 7
%     '',...                 % 8
%     'EEG Sensor',...       % 9
%     'ADC Input Current',...% 10 ADC Input Current (Amps)
%     'Stimulation input',...% 11
%     'Video Time',...       % 12
%     '',...                 % 13
%     '',...                 % 14
%     'SAM Sensor',...       % 15
%     'Virtual Channel',...  % 16
%     'System Clock',...     % 17 System Time Ref
%     'ADC Input Voltage',...% 18 ADC Input Voltage (Volts)
%   };

% find the indices of the MEG reference sensors

ctf.sensor.type.meg_ref = [0 1];
ctf.sensor.type.refMagnetometers = 0; % include B*
ctf.sensor.type.refGradiometers  = 1; % include G*,P*,Q*,R*

magref  = find([ctf.sensor.info.index] == 0);
gradref = find([ctf.sensor.info.index] == 1);

ctf.sensor.index.meg_ref_mag  = magref;
ctf.sensor.index.meg_ref_grad = gradref;
ctf.sensor.index.meg_ref  = [magref,gradref];

% find the indices of the MEG head sensors

ctf.sensor.type.meg_sens = 5; % include B*
ctf.sensor.index.meg_sens = find([ctf.sensor.info.index] == 5);

% find the indices of the EEG head sensors

ctf.sensor.type.eeg_sens = 9; % include EEG*
ctf.sensor.index.eeg_sens = find([ctf.sensor.info.index] == 9);

% find the indices of the ADC channels

ctf.sensor.type.adc = 10;
ctf.sensor.index.adc = find([ctf.sensor.info.index] == 10);

% find the indices of the STIM channels

ctf.sensor.type.stim_ref = 11;
ctf.sensor.index.stim_ref = find([ctf.sensor.info.index] == 11);

% find the indices of the STIM channels

ctf.sensor.type.video_time = 12;
ctf.sensor.index.video_time = find([ctf.sensor.info.index] == 12);

% find the indices of the SAM channels (Synthetic Aperture Magnetometry)

ctf.sensor.type.sam = 15;
ctf.sensor.index.sam = find([ctf.sensor.info.index] == 15);

% find the indices of the virtual channels

ctf.sensor.type.virtual_channels = 16;
ctf.sensor.index.virtual_channels = find([ctf.sensor.info.index] == 16);

% find the indices of the system clock

ctf.sensor.type.sclk_ref = 17; % include SCLK*
ctf.sensor.index.sclk_ref = find([ctf.sensor.info.index] == 17);

% combine eeg and meg channels

ctf.sensor.index.all_sens = [ ctf.sensor.index.meg_sens, ctf.sensor.index.eeg_sens ];

all = [ ctf.sensor.index.all_sens, ctf.sensor.index.meg_ref, ...
        ctf.sensor.index.stim_ref, ctf.sensor.index.sclk_ref ];

ctf.sensor.index.other = setdiff([1:ctf.setup.number_channels],all);

% define regions of MEG sensors
labels = {ctf.sensor.info.label};
ctf.sensor.index.meg_left_central    = strmatch('MLC',labels)';
ctf.sensor.index.meg_left_frontal    = strmatch('MLF',labels)';
ctf.sensor.index.meg_left_parietal   = strmatch('MLP',labels)';
ctf.sensor.index.meg_left_occipital  = strmatch('MLO',labels)';
ctf.sensor.index.meg_left_parietal   = strmatch('MLP',labels)';
ctf.sensor.index.meg_left_temporal   = strmatch('MLT',labels)';
ctf.sensor.index.meg_right_central   = strmatch('MRC',labels)';
ctf.sensor.index.meg_right_frontal   = strmatch('MRF',labels)';
ctf.sensor.index.meg_right_occipital = strmatch('MRO',labels)';
ctf.sensor.index.meg_right_parietal  = strmatch('MRP',labels)';
ctf.sensor.index.meg_right_temporal  = strmatch('MRT',labels)';
ctf.sensor.index.meg_mid_central     = strmatch('MZC',labels)';
ctf.sensor.index.meg_mid_frontal     = strmatch('MZF',labels)';
ctf.sensor.index.meg_mid_occipital   = strmatch('MZO',labels)';
ctf.sensor.index.meg_mid_parietal    = strmatch('MZP',labels)';

ctf.sensor.index.meg_left  = [ ...
    ctf.sensor.index.meg_left_central, ...
    ctf.sensor.index.meg_left_frontal, ...
    ctf.sensor.index.meg_left_occipital, ...
    ctf.sensor.index.meg_left_parietal, ...
    ctf.sensor.index.meg_left_temporal ];

ctf.sensor.index.meg_right  = [ ...
    ctf.sensor.index.meg_right_central, ...
    ctf.sensor.index.meg_right_frontal, ...
    ctf.sensor.index.meg_right_occipital, ...
    ctf.sensor.index.meg_right_parietal, ...
    ctf.sensor.index.meg_right_temporal ];

ctf.sensor.index.meg_central = [ ...
    ctf.sensor.index.meg_left_central, ...
    ctf.sensor.index.meg_right_central, ...
    ctf.sensor.index.meg_mid_central ];

ctf.sensor.index.meg_frontal = [ ...
    ctf.sensor.index.meg_left_frontal, ...
    ctf.sensor.index.meg_right_frontal, ...
    ctf.sensor.index.meg_mid_frontal ];

ctf.sensor.index.meg_occipital = [ ...
    ctf.sensor.index.meg_left_occipital, ...
    ctf.sensor.index.meg_right_occipital, ...
    ctf.sensor.index.meg_mid_occipital ];

ctf.sensor.index.meg_parietal = [ ...
    ctf.sensor.index.meg_left_parietal, ...
    ctf.sensor.index.meg_right_parietal, ...
    ctf.sensor.index.meg_mid_parietal ];

ctf.sensor.index.meg_temporal = [ ...
    ctf.sensor.index.meg_left_temporal, ...
    ctf.sensor.index.meg_right_temporal ];

%t = toc; fprintf('...done (%6.2f sec)\n\n',t);

return


% ECGKIT
% Version 0.1 01-Oct-2014
% Files

%   InstallECGkit   - Installation script of ecg-kit
%   UnInstallECGkit - Uninstallation script of ecg-kit
%   ECGkit_examples - Example of how to use the ecg-kit


classdef MimEditYellow < MimGuiPlugin
    % MimEditYellow. Gui Plugin for setting paint colour
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimEditYellow is a Gui Plugin for the MIM Toolkit.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        ButtonText = 'Yellow'
        SelectedText = 'Yellow'
        ToolTip = 'Edit with yellow label'
        Category = 'Segmentation label'
        Visibility = 'Dataset'
        Mode = 'Edit'

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 5
        ButtonHeight = 1
        Icon = 'paint.png'
        IconColour = GemMarkerPoint.DefaultColours{6}
        Location = 36
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.ImagePanel.PaintBrushColour = 6;
        end

        function enabled = IsEnabled(gui_app)
             enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ...
                isequal(gui_app.ImagePanel.SelectedControl, 'Paint');
        end

        function is_selected = IsSelected(gui_app)
            is_selected = gui_app.ImagePanel.PaintBrushColour == 6;
        end
    end
end


function [data smpr meta] = read(db,index)
%READ - returns waveform from ADT object.
%[data smpr meta] = read(ADTobj,index).
% See query function for the description of the
% output arguments.
%Exemples:
%  wave  = read(ADTobj);  -  returns wave data in the form of cell array.
%  wave = read(ADTobj,5); - returns wave data only from sentence 5;
%
%See also query, filterdb, read, play.

if ~isempty(db.enteries)
    Odata=struct();
    count = 0;
    if nargin<2 %if index not enterd reads from all sentances
        from = 1;
        to = length(db.enteries);
    else         %else read only form sentence number index
        from = index;
        to = index;
    end

    fprintf('Reading Data... \n');

    for  index=from:to  %reads data according to the database kind

        if db.kind==1 %reads sentences
            count = count + 1;
            [Odata(count).data smpr] = sentence_read(db,index);
            Odata(count).info =getmeta(db,index);
        end

        if db.kind==2 %reads words
            [data smpr] = sentence_read(db,index);
            for ii=1:length(db.enteries(index).word.b)
                if db.enteries(index).word.flag(ii)==1
                    count = count + 1;
                    b = db.enteries(index).word.b(ii);
                    e = db.enteries(index).word.e(ii);
                    Odata(count).data = data(b:e);
                    Odata(count).info = getmeta(db,index);
                    Odata(count).info.word = strrep(db.enteries(index).word.name(ii,1:end),' ','');
                    Odata(count).info.wordNumber = ii;
                end
            end
        end

        if db.kind==3 %reads phomemes
            [data smpr] = sentence_read(db,index);
            for ii=1:length(db.enteries(index).phoneme.b)
                b = db.enteries(index).phoneme.b(ii);
                e = db.enteries(index).phoneme.e(ii);
                in_word = db.enteries(index).word.flag(db.enteries(index).phoneme.from(ii));
                if(db.enteries(index).phoneme.flag(ii)==1)&&(in_word==1)
                    count = count + 1;
                    Odata(count).data = data(b:e);
                    Odata(count).info = getmeta(db,index);
                    Odata(count).info.word = strrep(db.enteries(index).word.name(db.enteries(index).phoneme.from(ii),1:end),' ','');
                    Odata(count).info.phoneme = strrep(db.enteries(index).phoneme.name(ii,1:end),' ','');
                end
            end
        end
    end
    %converts resalt in the from of struct to cellarray
    data = cell(length(Odata),1);
    meta = cell(length(Odata),1);
    for ii=1:length(Odata)
        data{ii} = Odata(ii).data;
        meta{ii} = Odata(ii).info;
    end
    fprintf('Enteries: %d\n', length(Odata));
else
    fprintf('An empty Database!\n');
    data = [];
    meta =[];
    smpr = [];
end
end


function this = finish_processing_step(this, module, varargin)
% finishes current processing step by deleting duplicate data and storing
% results of processing step
%
%   MrSeries = finish_processing_step(MrSeries, module, varargin)
%
% This is a method of class MrSeries.
%
% IN
%   module      'realign', 'smooth', ...
%
% OUT
%
% EXAMPLE
%   finish_processing_step
%
%   See also MrSeries MrSeries.init_processing_step

% Author:   Saskia Klein & Lars Kasper
% Created:  2014-07-01
% Copyright (C) 2014 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public Licence (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

% NOTE: for each new processing step added here, it has to be decided which
% files are saved additionally or which temporary files can be deleted/renamed
itemsSave = this.parameters.save.items;
doSave = ~strcmpi(itemsSave, 'none');
doSaveRaw = ismember(itemsSave, {'all'});
doSaveNifti = ismember(itemsSave, {'nii', 'all', 'processed'});
doSaveObject = ismember(itemsSave, {'object', 'all', 'processed'});

% determine where and which files have been changed from input argument
if iscell(varargin{1});
    inputImage = varargin{1}{1};
else
    inputImage = varargin{1};
end

pathSave        = inputImage.parameters.save.path;
pathRaw         = fileparts(inputImage.get_filename('prefix', 'raw'));

% delete additional, processed files...
switch module

    case 'compute_masks'
        maskImages = varargin{1};
        nImages = numel(maskImages);

        filesMask = cell(nImages,1);
        for iImage = 1:nImages
            filesMask{iImage} = ...
                maskImages{iImage}.get_filename;
            if doSaveNifti
                maskImages{iImage}.save;
            end
        end

        filesProcessed = filesMask;

    case 'compute_stat_images'
        % file names and paths already given in init_processing_step
        if doSaveNifti
            handleImageArray = this.get_all_image_objects('stats');
            for iImage = 1:numel(handleImageArray)
                handleImageArray{iImage}.save;
                filesProcessed{iImage} = ...
                    handleImageArray{iImage}.get_filename;
            end
        end

    case 'compute_tissue_probability_maps'
        createdFields = varargin{1};
        inputImage = varargin{2};
        nImages = numel(createdFields);

        filesFieldImages = cell(nImages,1);
        for iImage = 1:nImages
            filesFieldImages{iImage} = fullfile(...
                pathSave, ...
                createdFields{iImage}.parameters.save.fileName);
        end

        fileRaw     = inputImage.get_filename('prefix', 'raw');
        fileSeg8    = regexprep(fileRaw, '\.nii$', '_seg8\.mat');

        filesProcessed 	= [
            {inputImage.get_filename}
            filesFieldImages
            {fileSeg8}
            ];

    case 'coregister'
        transformedImage = varargin{1};
        equallyTransformedImages = varargin{2};

        % set files for delete
        filesProcessed = {transformedImage.get_filename};
        nImages = numel(equallyTransformedImages);
        for iImage = 1:nImages
            filesProcessed{end+1} = equallyTransformedImages{iImage}.get_filename;
            % load additionally transformed images
            handleInputImages = this.find('MrImage', 'name', ...
                equallyTransformedImages{iImage}.name);
            nameTransformed = handleInputImages{1}.name;
            handleInputImages{1}.load(equallyTransformedImages{iImage}.get_filename);
            handleInputImages{1}.name = nameTransformed;
        end

    case 'realign' % load realignment parameters into object

        fileRealignmentParameters = regexprep( ...
            tapas_uniqc_prefix_files(inputImage.get_filename('prefix', 'raw'), ...
            'rp_'), '\.nii$', '\.txt') ;
        this.glm.regressors.realign = load(fileRealignmentParameters);

        movefile(fileRealignmentParameters, pathSave);

    case 'smooth'
        filesProcessed = inputImage.get_filename();

    case 't_filter'
        if doSaveNifti
            this.data.save();
        end

    case 'specify_and_estimate_1st_level'
        % load design matrix
        spmDirectory = fullfile(this.glm.parameters.save.path, ...
            this.glm.parameters.save.spmDirectory);
        SPM = load(fullfile(spmDirectory, 'SPM.mat'));
        this.glm.designMatrix = SPM.SPM.xX.nKX;
end

% delete raw sub-folder of current processing step
if ~doSaveRaw && exist(pathRaw, 'dir')
    delete(fullfile(pathRaw, '*'));
    rmdir(pathRaw);
end

if ~doSave
    tapas_uniqc_delete_with_hdr(filesProcessed);
end

% strip object data and save ...
if doSaveObject
    fileObject = fullfile(pathSave, 'MrObject.mat');
    MrObject = this.copyobj('exclude', 'data'); % copies object without data
    save(fileObject, 'MrObject');
end


% Copyright (C) 2018  Symeon Symeonidis, Stefanos Tsantilas, Stelios Mitilineos
% simos421@gmail.com, steftsantilas@gmail.com, smitil@gmail.com
% 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.

function CstDiscretePort(mws,PortNumber,SetP1,SetP2)

DiscretePort = invoke(mws,'DiscretePort');
invoke(DiscretePort,'Reset');
invoke(DiscretePort,'PortNumber',int2str(PortNumber));
invoke(DiscretePort,'Type','SParameter');
invoke(DiscretePort,'Label','');
invoke(DiscretePort,'Impedance','50');
invoke(DiscretePort,'VoltagePortImpedance','0.0');
invoke(DiscretePort,'Voltage','1.0');
invoke(DiscretePort,'Current','1.0');
invoke(DiscretePort,'SetP1','False',int2str(SetP1(1)),int2str(SetP1(2)),int2str(SetP1(3)));
invoke(DiscretePort,'SetP2','False',int2str(SetP2(1)),int2str(SetP2(2)),int2str(SetP2(3)));
invoke(DiscretePort,'InvertDirection','False');
invoke(DiscretePort,'LocalCoordinates','False');
invoke(DiscretePort,'Monitor','True');
invoke(DiscretePort,'Radius','0.0');
invoke(DiscretePort,'Wire','');
invoke(DiscretePort,'Position','end1');
invoke(DiscretePort,'Create');
release(DiscretePort);
end


function classSymbols = prtPlotUtilClassSymbolsBW(nClasses)
% Internal function, default color specs.
% xxx Need Help xxx

classSymbols = 'os^dv';

classSymbolsInd = repmat((1:length(classSymbols))',ceil(nClasses/length(classSymbols)),1);
classSymbolsInd = classSymbolsInd(1:nClasses);

classSymbols = classSymbols(classSymbolsInd);


function dtiQuenchSaveFibersState(fiberGroupInds, stateFile, fg, pdbFile)
%
% dtiQuenchSaveFibersState(fiberGroupInds, stateFile, [fg], [pdbFile])
%
% Saves an array of fiber groups in QUENCH pdb/state format.
%
% HISTORY:
% 2009.09.22 ER: wrote it.
%

if(nargin>=4) %Dont save pdb if fg/pdb file name not supplied.
    mtrExportFibers(fg, pdbFile);
    if(numel(fiberGroupInds)~=numel(fg.fibers))
        error('fiberGroupInds does not match pdb file!');
    end
end

fid = fopen(stateFile,'wt');
% 5 header lines:
fprintf(fid,'Camera Position: -290.0,-21.0,76.0\n');
fprintf(fid,'Camera View Up: 0.2,0.02,1.0\n');
fprintf(fid,'Camera Focal Point: 0,-15,15\n');
fprintf(fid,'Volume Section''s Position: 40,40,20\n');
fprintf(fid,'Volume Section''s Visibility: 1,1,1\n');
fprintf(fid,'%d\n',length(fiberGroupInds));
fprintf(fid,'%d\n',fiberGroupInds);
fclose(fid);

return;


classdef io

methods(Static)

function result = yes_no(flag)
    if flag == 0
        result = 'No';
    else
        result = 'Yes';
    end
end

function result = true_false(flag)
    if flag == 0
        result = 'false';
    else
        result = 'true';
    end
end

function result = true_false_short(flag)
    if flag == 0
        result = 'F';
    else
        result = 'T';
    end
end

function result = tf_pair(a, b)
    a = spx.io.true_false_short(a);
    b = spx.io.true_false_short(b);
    result = [a b];
end

function result = success_failure(flag)
    if flag == 0
        result = 'Failure';
    else
        result = 'Success';
    end
end

function result = success_failure_short(flag)
    if flag == 0
        result = 'F';
    else
        result = 'S';
    end
end

function result = bytes2str(bytes)
    % Identify the scale of number of bytes
    scale = floor(log(bytes)/log(1024));
    switch scale
        case 0
            result = sprintf('%d Bytes', bytes);
        case 1
            result = sprintf('%.2f KB', bytes / (1024^1));
        case 2
            result = sprintf('%.2f MB', bytes / (1024^2));
        case 3
            result = sprintf('%.2f GB', bytes / (1024^3));
        case 4
            result = sprintf('%.2f TB', bytes / (1024^4));
        case -inf
            result = 'Not available';
        otherwise
            result = 'Too big';
    end

end

end

end


classdef TestGlob
    %TestGlob

    methods (Static)
        function test_1
            pattern = fullfile(mexopencv.root(),'test','left*.jpg');
            files = cv.glob(pattern, 'Recursive',false);
            validateattributes(files, {'cell'}, {'vector'});
            assert(iscellstr(files));
        end

        function test_error_argnum
            try
                cv.glob();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end