classdef ImageNet < datasets.ImageFolder
%IMAGENET ImageNet dataset
%   Encapsulates the ImageNet dataset for training.
%
%   D = datasets.ImageNet('dataDir', '/data/imagenet') loads the ImageNet
%   dataset from the directory '/data/imagenet'.
%   Detailed instructions on how to set it up are below.
%
%   D.train() returns a cell array with mini-batches, from the shuffled
%   training set. Each mini-batch consists of a set of indexes.
%
%   D.val() returns a cell array with mini-batches, from the validation set
%   (without shuffling). Each mini-batch consists of a set of indexes.
%
%   [IMAGES, LABELS] = D.get(BATCH) returns a tensor of images and the
%   corresponding labels for the given mini-batch BATCH.
%
%   datasets.ImageNet(...,'option', value, ...) sets several properties,
%   which are all inherited from the datasets.ImageFolder class.
%   See 'help datasets.ImageFolder' for more information.
%
%   See 'autonn/examples/cnn/imagenet_example.m' for a full example.
%
%
%   * ImageNet data setup:
%
%   The ImageNet/ILSVRC data ships in several TAR archives that can be
%   obtained from the ILSVRC challenge website. You will need:
%
%   ILSVRC2012_img_train.tar
%   ILSVRC2012_img_val.tar
%   ILSVRC2012_img_test.tar
%   ILSVRC2012_devkit.tar
%
%   Note that images in the CLS-LOC challenge are the same for the 2012,
%   2013, and 2014 edition of ILSVRC, but that the development kit is
%   different. However, all devkit versions should work.
%
%   Create the following hierarchy:
%
%   <dataDir>/images/train/ : content of ILSVRC2012_img_train.tar
%   <dataDir>/images/val/ : content of ILSVRC2012_img_val.tar
%   <dataDir>/images/test/ : content of ILSVRC2012_img_test.tar
%   <dataDir>/ILSVRC2012_devkit : content of ILSVRC2012_devkit.tar
%
%   In order to speedup training and testing, it is a good idea to
%   preprocess the images to have a fixed size (e.g. 256 pixels high).
%   There is a script in MatConvNet (utils/preprocess-imagenet.sh) that
%   achieves this. It may also be necessary to store the images in RAM
%   disk. Reading images off disk with a sufficient speed is crucial for
%   fast training.

% Copyright (C) 2018 Joao F. Henriques, Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

  properties
    labels
    sets
    classes
  end

  methods
    function o = ImageNet(varargin)
      % call parent class's constructor, but delay initialization
      o = o@datasets.ImageFolder('skipInitialization', true) ;

      % parse generic ImageFolder arguments
      varargin = o.parseGenericArgs(varargin) ;
      assert(isempty(varargin), 'Unknown arguments.') ;

      assert(~isempty(o.dataDir), 'Must specify dataset.dataDir.') ;

      cache = [o.dataDir '/imagenet.mat'] ;
      if exist(cache, 'file')
        % load from cache file
        s = load(cache) ;
        o.filenames = s.filenames ;
        o.labels = s.labels ;
        o.sets = s.sets ;
        o.classes = s.classes ;
      else
        % use matconvnet's example imagenet imdb as-is (see below)
        imdb = cnn_imagenet_setup_data('dataDir', o.dataDir) ;

        % read info from imdb
        o.filenames = strcat(['images' filesep], imdb.images.name) ;
        o.labels = imdb.images.label ;
        o.sets = imdb.images.set ;
        o.classes = imdb.classes ;

        % save to cache file
        [filenames, labels, sets, classes] = deal(o.filenames, o.labels, o.sets, o.classes) ;  %#ok<ASGLU>
        save(cache, 'filenames', 'labels', 'sets', 'classes', '-v6') ;  % no compression, < 2 GB
      end

      o.trainSet = find(o.sets == 1) ;
      o.valSet = find(o.sets == 2) ;

      o.initialize() ;
    end

    function [images, labels] = get(o, batch)
      % return a single batch of images, with optional prefetching
      [images, idx] = o.get@datasets.ImageFolder(batch) ;
      labels = o.labels(idx) ;
    end
  end
end

function imdb = cnn_imagenet_setup_data(varargin)
% CNN_IMAGENET_SETUP_DATA  Initialize ImageNet ILSVRC CLS-LOC challenge data
%    This function creates an IMDB structure pointing to a local copy
%    of the ILSVRC CLS-LOC data.

opts.dataDir = fullfile('data','imagenet12') ;
opts = vl_argparse(opts, varargin) ;

% -------------------------------------------------------------------------
%                                                  Load categories metadata
% -------------------------------------------------------------------------

d = dir(fullfile(opts.dataDir, '*devkit*')) ;
if numel(d) == 0
  error('Make sure that ILSVRC data is correctly installed in %s', ...
    opts.dataDir) ;
end
devkitPath = fullfile(opts.dataDir, d(1).name) ;

% find metadata
mt = dir(fullfile(devkitPath, 'data', 'meta_clsloc.mat')) ;
if numel(mt) == 0
  mt = dir(fullfile(devkitPath, 'data', 'meta.mat')) ;
end
metaPath = fullfile(devkitPath, 'data', mt(1).name) ;

% find validation images labels
tmp = dir(fullfile(devkitPath, 'data', '*_validation_ground_truth*')) ;
valLabelsPath = fullfile(devkitPath, 'data', tmp(1).name) ;

% find validation images blacklist
tmp = dir(fullfile(devkitPath, 'data', '*_validation_blacklist*')) ;
if numel(tmp) > 0
  valBlacklistPath = fullfile(devkitPath, 'data', tmp(1).name) ;
else
  valBlacklistPath = [] ;
  warning('Could not find validation images blacklist file');
end

fprintf('using devkit %s\n', devkitPath) ;
fprintf('using metadata %s\n', metaPath) ;
fprintf('using validation labels %s\n', valLabelsPath) ;
fprintf('using validation blacklist %s\n', valBlacklistPath) ;

meta = load(metaPath) ;
cats = {meta.synsets(1:1000).WNID} ;
descrs = {meta.synsets(1:1000).words} ;

imdb.classes.name = cats ;
imdb.classes.description = descrs ;
imdb.imageDir = fullfile(opts.dataDir, 'images') ;

% -------------------------------------------------------------------------
%                                                           Training images
% -------------------------------------------------------------------------

fprintf('searching training images ...\n') ;
names = {} ;
labels = {} ;
for d = dir(fullfile(opts.dataDir, 'images', 'train', 'n*'))'
  [~,lab] = ismember(d.name, cats) ;
  ims = dir(fullfile(opts.dataDir, 'images', 'train', d.name, '*.JPEG')) ;
  names{end+1} = strcat([d.name, filesep], {ims.name}) ;
  labels{end+1} = ones(1, numel(ims)) * lab ;
  fprintf('.') ;
  if mod(numel(names), 50) == 0, fprintf('\n') ; end
  %fprintf('found %s with %d images\n', d.name, numel(ims)) ;
end
names = horzcat(names{:}) ;
labels = horzcat(labels{:}) ;

if numel(names) ~= 1281167
  warning('Found %d training images instead of 1,281,167. Dropping training set.', numel(names)) ;
  names = {} ;
  labels =[] ;
end

names = strcat(['train' filesep], names) ;

imdb.images.id = 1:numel(names) ;
imdb.images.name = names ;
imdb.images.set = ones(1, numel(names)) ;
imdb.images.label = labels ;

% -------------------------------------------------------------------------
%                                                         Validation images
% -------------------------------------------------------------------------

ims = dir(fullfile(opts.dataDir, 'images', 'val', '*.JPEG')) ;
names = sort({ims.name}) ;
labels = textread(valLabelsPath, '%d') ;

if numel(ims) ~= 50e3
  warning('Found %d instead of 50,000 validation images. Dropping validation set.', numel(ims))
  names = {} ;
  labels =[] ;
else
  if ~isempty(valBlacklistPath)
    black = textread(valBlacklistPath, '%d') ;
    fprintf('blacklisting %d validation images\n', numel(black)) ;
    keep = setdiff(1:numel(names), black) ;
    names = names(keep) ;
    labels = labels(keep) ;
  end
end

names = strcat(['val' filesep], names) ;

imdb.images.id = horzcat(imdb.images.id, (1:numel(names)) + 1e7 - 1) ;
imdb.images.name = horzcat(imdb.images.name, names) ;
imdb.images.set = horzcat(imdb.images.set, 2*ones(1,numel(names))) ;
imdb.images.label = horzcat(imdb.images.label, labels') ;

% -------------------------------------------------------------------------
%                                                               Test images
% -------------------------------------------------------------------------

ims = dir(fullfile(opts.dataDir, 'images', 'test', '*.JPEG')) ;
names = sort({ims.name}) ;
labels = zeros(1, numel(names)) ;

if numel(labels) ~= 100e3
  warning('Found %d instead of 100,000 test images', numel(labels))
end

names = strcat(['test' filesep], names) ;

imdb.images.id = horzcat(imdb.images.id, (1:numel(names)) + 2e7 - 1) ;
imdb.images.name = horzcat(imdb.images.name, names) ;
imdb.images.set = horzcat(imdb.images.set, 3*ones(1,numel(names))) ;
imdb.images.label = horzcat(imdb.images.label, labels) ;

% -------------------------------------------------------------------------
%                                                            Postprocessing
% -------------------------------------------------------------------------

% sort categories by WNID (to be compatible with other implementations)
[imdb.classes.name,perm] = sort(imdb.classes.name) ;
imdb.classes.description = imdb.classes.description(perm) ;
relabel(perm) = 1:numel(imdb.classes.name) ;
ok = imdb.images.label >  0 ;
imdb.images.label(ok) = relabel(imdb.images.label(ok)) ;

end


function [ out ] = func_featureExtraction_filterbank( dat, varargin )

if iscell(varargin)
    opt=opt_cellToStruct(varargin{:});
elseif isstruct(varargin{:})
    opt=varargin{:};
end

for ii=1:length(dat)
    FT{ii}=func_featureExtraction(dat{ii}, {'feature',opt.feature});
end

out=FT;
end


function H=prh(H)
%function H=prh(H)
%
% sets the current figure to print on full page in LANDSCAPE mode.
%
% By Michael Wu  --  waftingpetal@yahoo.com (Oct 2001)
%
% ====================

if ~exist('H','var');
  H = gcf;
end;

papMarg=0.1;
set(H,'PaperOrientation','landscape','PaperPosition',[0+papMarg, 0+papMarg, 11-2*papMarg, 8.5-2*papMarg]);


function str = cstring(x)
%
%CSTRING Print to a string like c
%  CSTRING(x) takes an array x, of type char, and prints it to
%  a string the way C would.
%  the first null, or non-ascii character is the terminator

i=1;
while (x(i)>0 & x(i)<128 & i<length(x))
  i=i+1;
end

if i==1
  str = char(0);
else
  str = char(x(1:i-1));
end

str = sprintf(str,'%s');

return


clearvars; clearvars -global; clc; close all;

%% settings
addpath(genpath('Functions'));
addpath(genpath('./Libraries/'));

InitParam();

% fprintf('Preparing the training data\n');
% fprintf('***************************\n\n');
% PrepareTrainData();

fprintf('Preparing the test data\n');
fprintf('***********************\n\n');
PrepareTestData();


function write_sicd_imsubhdr(obj, n)
%WRITE_SICD_IMSUBHDR Writes the NITF image segment sub-header for SICD file
%
% It's not expected that the typical user would call this function, rather
% it is called as part of a bigger NITF/SICD writer.
%
% Inputs:
%       obj:       This is the 'hidden' object-specific handle.  It is
%                  similar to 'this' in Java.
%
% Outputs:
%       lengthWritten: The number of bytes written to disk
%
% References:
%       MIL-STD-2500C, Department of Defense Interface Standard
%                      National Imagery Transmission Format version 2.1
%                      01 May 2006
%
% Written by: Tom Krauss and Wade Schwartzkopf, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

% Always writing version 2.1 NITF

fwriten(obj.FID, 'IM', 2);
if obj.NumIS==1
    IID1 = 'SICD000';
else
    IID1 = ['SICD' num2str(n,'%03d')];
end
fwriten(obj.FID, IID1, 10); % IID1

if isfield(obj.sicdmeta,'ImageCreation')&&isfield(obj.sicdmeta.ImageCreation,'DateTime')
    fdt = datestr(obj.sicdmeta.ImageCreation.DateTime,'yyyymmddHHMMSS');
else
    fdt = '';
end
fwriten(obj.FID, fdt, 14); % IDATIM

fwriten(obj.FID, '', 17); % TGTID

if isfield(obj.sicdmeta,'CollectionInfo')&&isfield(obj.sicdmeta.CollectionInfo,'CoreName')
    IID2 = obj.sicdmeta.CollectionInfo.CoreName;
else
    IID2 = 'Unknown';
end
fwriten(obj.FID, ['SICD: ' IID2], 80); % IID2

obj.write_sicd_security_tags();  % Security tags go here
fwriten(obj.FID, '0', 1);  % ENCRYPT
if isfield(obj.sicdmeta,'CollectionInfo')&&isfield(obj.sicdmeta.CollectionInfo,'CollectorName')
    ISORCE = obj.sicdmeta.CollectionInfo.CollectorName;
else
    ISORCE = '';
end
fwriten(obj.FID, ['SICD: ' ISORCE], 42); % ISORCE
fwriten(obj.FID, uint64(obj.NumRowsIS(n)), 8); % NROWS
fwriten(obj.FID, uint64(obj.sicdmeta.ImageData.NumCols), 8); % NCOLS

switch obj.sicdmeta.ImageData.PixelType
    case 'RE32F_IM32F'
        PVTYPE = 'R';
        ABPP = 32;
        ISUBCAT1 = 'I';
        ISUBCAT2 = 'Q';
    case 'RE16I_IM16I'
        PVTYPE = 'SI';
        ABPP = 16;
        ISUBCAT1 = 'I';
        ISUBCAT2 = 'Q';
    case 'AMP8I_PHS8I'
        PVTYPE = 'INT';
        ABPP = 8;
        ISUBCAT1 = 'M';
        ISUBCAT2 = 'P';
end
fwriten(obj.FID, PVTYPE, 3); % PVTYPE (here signed integer)
fwriten(obj.FID, 'NODISPLY',8); % IREP
fwriten(obj.FID, 'SAR', 8); % ICAT
fwriten(obj.FID, uint64(ABPP),2);  % ABPP
fwriten(obj.FID, 'R', 1);  % PJUST
fwriten(obj.FID, 'G', 1);  % ICORDS
if isfield(obj.sicdmeta,'GeoData')&&isfield(obj.sicdmeta.GeoData,'ImageCorners')
    geo_format = {'num_units',3,'include_symbols',false};
    % TODO: Adjust to handle multiple image segments
    geolo = [latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.FRFC.Lat,'lat',geo_format{:}) ...
        latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.FRFC.Lon,'lon',geo_format{:}) ...
        latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.FRLC.Lat,'lat',geo_format{:}) ...
        latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.FRLC.Lon,'lon',geo_format{:}) ...
        latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.LRLC.Lat,'lat',geo_format{:}) ...
        latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.LRLC.Lon,'lon',geo_format{:}) ...
        latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.LRFC.Lat,'lat',geo_format{:}) ...
        latlonstr(obj.sicdmeta.GeoData.ImageCorners.ICP.LRFC.Lon,'lon',geo_format{:})];
else
    geolo = '';
end
fwriten(obj.FID, geolo, 60); % IGEOLO

fwriten(obj.FID, uint64(0), 1);  % NICOM (# image comments)
fwriten(obj.FID, 'NC', 2);  % IC (No image compression)
fwriten(obj.FID, uint64(2), 1);  % NBANDS

% 'Band' 1: in phase
fwriten(obj.FID, '',  2); % IREPBAND1
fwriten(obj.FID, ISUBCAT1, 6); % ISUBCAT1
fwriten(obj.FID, 'N', 1); % IFC1
fwriten(obj.FID, '',  3); % IMFLT1
fwriten(obj.FID, '0', 1); % NLUTS1

% 'Band' 2: quadrature
fwriten(obj.FID, '',  2); % IREPBAND2
fwriten(obj.FID, ISUBCAT2, 6); % ISUBCAT2
fwriten(obj.FID, 'N', 1); % IFC2
fwriten(obj.FID, '',  3); % IMFLT2
fwriten(obj.FID, '0', 1); % NLUTS2

fwriten(obj.FID, '0', 1); % ISYNC, always 0
fwriten(obj.FID, 'P', 1);  % IMODE (band interleaved by pixel)
fwriten(obj.FID, uint64(1), 4);  % NBPR - blocks per row
fwriten(obj.FID, uint64(1), 4);  % NBPC - blocks per column
if obj.sicdmeta.ImageData.NumCols>8192
    NPPBH = 0; % (zero means "use NCOLS")
else
    NPPBH = obj.sicdmeta.ImageData.NumCols;
end
fwriten(obj.FID, uint64(NPPBH), 4);  % NPPBH - Number of Pixels Per Block Horizontal
if obj.NumRowsIS(n)>8192
    NPPBV = 0; % (zero means "use NROWS")
else
    NPPBV = obj.NumRowsIS(n);
end
fwriten(obj.FID, uint64(NPPBV), 4);  % NPPBV - Number of Pixels Per Block Vertical
fwriten(obj.FID, uint64(ABPP),2);  % NBPP
fwriten(obj.FID, uint64(n), 3);  % IDLVL
fwriten(obj.FID, uint64(n-1), 3);  % IALVL
if n==1
    fwriten(obj.FID, uint64(0), 5); % ILOC (row) - Image location offsets
else
    fwriten(obj.FID, uint64(obj.NumRowsIS(n-1)), 5); % ILOC (row) - Image location offsets
end
fwriten(obj.FID, uint64(0), 5); % ILOC (column) - Image location offsets
fwriten(obj.FID, '1.0 ', 4);     % IMAG - image magnification
fwriten(obj.FID, uint64(0), 5);  % UDIDL - Generally not used for SICD
fwriten(obj.FID, uint64(0), 5);  % IXSHDL - Generally not used for SICD

end

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


function table = postproc_norm(table)

nrows = size(table, 1);

for nri = 1:nrows
  split = 'none';
  norm = 'none';
  descriptor = table{nri, 'descriptor'}{1};
  pos = strfind(descriptor, 'nsplit');
  if ~isempty(pos)
    split = descriptor(pos+7);
    norm = descriptor(pos+9:end);
    descriptor = descriptor(1:pos-2);
  end
  table.descriptor(nri) = {descriptor};
  table.norm_split(nri) = {split};
  table.norm_type(nri) = {norm};
end

end


% This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix
function make()
try
	% This part is for OCTAVE
	if (exist ('OCTAVE_VERSION', 'builtin'))
		mex libsvmread.c
		mex libsvmwrite.c
		mex -I.. svmtrain.c ../svm.cpp svm_model_matlab.c
		mex -I.. svmpredict.c ../svm.cpp svm_model_matlab.c
	% This part is for MATLAB
	% Add -largeArrayDims on 64-bit machines of MATLAB
	else
		mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmread.c
		mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmwrite.c

        % Activate this if we want OMP implementation
% 		mex CFLAGS="\$CFLAGS -std=c99" CXXFLAGS="\$CXXFLAGS -fopenmp" -largeArrayDims -I.. -lgomp svmtrain.c ../svm.cpp svm_model_matlab.c
% 		mex CFLAGS="\$CFLAGS -std=c99" CXXFLAGS="\$CXXFLAGS -fopenmp" -largeArrayDims -I.. -lgomp svmpredict.c ../svm.cpp svm_model_matlab.c

        % Normal CFlage without OMP
        mex CFLAGS="\$CFLAGS -std=c99"  -largeArrayDims -I.. svmtrain.c ../svm.cpp svm_model_matlab.c
		mex CFLAGS="\$CFLAGS -std=c99"  -largeArrayDims -I.. svmpredict.c ../svm.cpp svm_model_matlab.c

	end
catch err
	fprintf('Error: %s failed (line %d)\n', err.stack(1).file, err.stack(1).line);
	disp(err.message);
	fprintf('=> Please check README for detailed instructions.\n');
end


report_this_filefun(mfilename('fullpath'));

SA = 1;

ste = [bvg(:,2) bvg(:,1)+180  bvg(:,4) bvg(:,3)+180 bvg(:,6) bvg(:,5)+180 bvg(:,7) ];
sor = ste;
ste2 = ste;
sor(:,SA*2) = sor(:,SA*2)+90;

normlap2=ones(length(tmpgri(:,1)),1)*nan;

re3=reshape(normlap2,length(yvect),length(xvect));
s11 = re3;

normlap2(ll)= bvg(:,8);
rama=reshape(normlap2,length(yvect),length(xvect));

normlap2(ll)= bvg(:,7);
r=reshape(normlap2,length(yvect),length(xvect));

normlap2(ll)= bvg(:,1);
s11=reshape(normlap2,length(yvect),length(xvect));

normlap2(ll)= bvg(:,4);
s31=reshape(normlap2,length(yvect),length(xvect));

normlap2(ll)= bvg(:,2);
s12=reshape(normlap2,length(yvect),length(xvect));

old1 = re3;

figure_w_normalized_uicontrolunits('visible','on')
plq = quiver(newgri(:,1),newgri(:,2),-cos(sor(:,1)*pi/180),sin(sor(:,1)*pi/180),0.6,'.')
set(plq,'LineWidth',0.5,'Color','k')
hold on

%pl = quiver(newgri(:,1),newgri(:,2),-cos(s(:,2)*pi/180/3),-sin(s(:,2)*pi/180),2)
%set(pl,'LineWidth',2,'Color','r')

px = get(plq,'Xdata'); py = get(plq,'Ydata');
close
figure_w_normalized_uicontrolunits('pos',[100 100 860 600])
watchon;
%whitebg(gcf);
set(gcf,'color','w');
axes('pos',[0.12 0.12 0.8 0.8]);
hold on
n = 0;
l0 = []; l1 = []; l2 = []; l3 = []; l4 = []; l5 = [];
for i = 1:3:length(px)-1
    n = n+1;j = jet;
    col = floor(ste(n,SA*2-1)/60*62)+1;
    if col > 64 ; col = 64; end
    pl = plot(px(i:i+1),py(i:i+1),'k','Linewidth',1.,'Markersize',1,'color',[ 0 0 0  ] );
    hold on
    dx = px(i)-px(i+1);
    dy = py(i) - py(i+1);
    pl2 = plot(px(i),py(i),'ko','Markersize',0.1,'Linewidth',0.5,'color',[0 0 0] );
    l0 = pl;
    pl3 = plot([px(i) px(i)+dx],[py(i) py(i)+dy],'k','Linewidth',1.,'color',[0 0 0] );

  if ste(n,1) < 40  && ste(n,3) > 45  && ste(n,5) < 20 ; set([pl pl3],'color',[0.2 0.8 0.2]); set(pl2,'color',[0.2 0.8 0.2]); l3 = pl; end
   if ste(n,1) > 52  &&                 ste(n,5) < 35 ;                 set([pl pl3],'color','r'); set(pl2,'color','r'); l1 = pl; end
  if ste(n,1) < 20  && ste(n,3) > 45  && ste(n,5) < 40 ;  set([pl pl3],'color',[0.2 0.8 0.2]); set(pl2,'color',[0.2 0.8 0.2]);l3 = pl; end
  if ste(n,1) > 40  &&                 ste(n,1) < 52  && ste(n,5) < 20 ;  set([pl pl3],'color','m'); set(pl2,'color','m'); l2 = pl; end
  if ste(n,1) < 20  &&                 ste(n,5) > 40  &&  ste(n,5) <  52 ; set([pl pl3],'color','c'); set(pl2,'color','c');l4 = pl; end
   if ste(n,1) < 35  && ste(n,5) > 52  ; set([pl pl3],'color','b'); set(pl2,'color','b');l5 = pl;  end

end

if isempty(l1) == 1; pl2 = plot(px(i),py(i),'kx','Linewidth',1.,'color','r'); l1 = pl2; set(l1,'visible','off'); end
if isempty(l2) == 1; pl2 = plot(px(i),py(i),'kx','Linewidth',1.,'color','m'); l2 = pl2; set(l2,'visible','off'); end
if isempty(l3) == 1; pl2 = plot(px(i),py(i),'kx','Linewidth',1.,'color',[0.2 0.8 0.2] ); l3 = pl2; set(l3,'visible','off'); end
if isempty(l4) == 1; pl2 = plot(px(i),py(i),'kx','Linewidth',1.,'color','c' ); l4 = pl2; set(l4,'visible','off'); end
if isempty(l5) == 1; pl2 = plot(px(i),py(i),'kx','Linewidth',1.,'color','b' ); l5 = pl2; set(l5,'visible','off'); end
if isempty(l0) == 1; l0 = plot(px(i),py(i),'kx','Linewidth',1.,'color',[0 0 0 ] );  set(l0,'visible','off'); end

legend([l1 l2 l3 l4 l5 l0],'NF','NS','SS','TS','TF','U');

hold on
axis('equal')
axis('tight')

title2([name ';  '   num2str(t0b) ' to ' num2str(teb) ],'FontSize',ZmapGlobal.Data.fontsz.s,...
    'Color','k','FontWeight','normal')

xlabel('Distance along projection [km] ','FontWeight','normal','FontSize',ZmapGlobal.Data.fontsz.s)
ylabel('Depth [km] ','FontWeight','normal','FontSize',ZmapGlobal.Data.fontsz.s)

set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','normal',...
    'FontWeight','normal','LineWidth',1.,...
    'Box','on','TickDir','out','Ticklength',[0.01 0.01])

matdraw

watchoff;

% view the variance map
re3 = r;sha = 'in';
%view_varmap


%% Example
% Controlling KUKA iiwa from V-rep simulation using MATLAB and KST as a
% middle-ware.
% This script works together with V-rep scene: iiwaFromVrep.ttt

%% To run this example do the following:
% 1- Run the Vrep simulation: iiwaFromVrep.ttt
% 2- Run the (MarlabToolboxServer) application on the robot
% 3- Run this script from MATLAB.

% Copyright: Mohammad SAFEEA, 19th-April-2018

%% Initiation part of the code
disp('Program started');
kst_Path=getTheKSTDirectory(pwd);
addpath(kst_Path);
vrep=remApi('remoteApi');
vrep.simxFinish(-1);
clientID=vrep.simxStart('127.0.0.1',19999,true,true,5000,5);
ip='172.31.1.147';
global t_Kuka;
if (clientID>-1)
    t_Kuka=net_establishConnection( ip );
    if ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')
      warning('Connection could not be establised, script aborted');
      return;
    end
    jHandles=zeros(7,1);
    for i=1:7
            s=['LBR_iiwa_7_R800_joint',num2str(i)];
            [res, daHandle]=vrep.simxGetObjectHandle(clientID,s,vrep.simx_opmode_oneshot_wait);
            jHandles(i)=daHandle;
    end
else
    return;
end
jPos={0., pi / 180 * 20., 0., -pi / 180 * 70., 0.,...
                        pi / 180 * 90., 0.};
relVel=0.25;
movePTPJointSpace( t_Kuka , jPos, relVel);
%% Control loop
realTime_startDirectServoJoints( t_Kuka );
pause(10);
counter=0;
tic;
totalTimeSecs=60; % 60 seconds of execution time
vrep.simxStartSimulation(clientID,vrep.simx_opmode_oneshot_wait);
for i=1:7
        [res,tempPos]=vrep.simxGetJointPosition(clientID,jHandles(i),...
            vrep.simx_opmode_streaming);
end
vrep.simxWriteStringStream(clientID,'path_velocity','0.07',vrep.simx_opmode_oneshot_wait);
jpos=zeros(7,25000);
t_0=toc;
while(t_0<totalTimeSecs)
    for i=1:7
            [res,tempPos]=vrep.simxGetJointPosition(clientID,jHandles(i),...
                vrep.simx_opmode_buffer);
            jPos{i}=tempPos;
    end

    if(toc-t_0>0.003)
        counter=counter+1;
        sendJointsPositionsf( t_Kuka ,jPos);
        for i=1:7
            jpos(i,counter)=jPos{i};
        end
        t_0=toc;
	end
end
%% Turn off KST server
net_turnOffServer( t_Kuka );
%% Stop simulation
vrep.simxStopSimulation(clientID,vrep.simx_opmode_oneshot_wait);
%% End simulation
vrep.simxFinish(clientID);
vrep.delete();


any(cellfun(@exist,{'add_one_source_c', 'find_existing_source_transpose', 'find_existing_source_transpose_min', 'find_sources_complement_grid_fast_int_all_active_c', 'find_sources_complement_grid_fast_int_c', 'vectorize_quad_single'})==3)


function a = setvalues(a, v)

%tstoolbox/@achse/setvalues
%   Syntax:
%     * a = setvalues(a, v)
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

a.values = v;


classdef dl_list_node < handle

% Copyright (C) 2012 Jean-Pierre de la Croix
% see the LICENSE file included with this software

    properties
        key_
        next_
        prev_
    end

    methods
        function obj = dl_list_node(key)
            obj.key_ = key;
            obj.next_ = [];
            obj.prev_ = obj.next_;
        end
    end

end


function res = rcnn_all(task, model_typ, trainset, testset)
  global RUNNAME
  RUNNAME = 'release';
  p = get_paths(RUNNAME);
  c = benchmarkPaths();
  NYU_ROOT_DIR = c.dataDir;
  REGIONDIR = fullfile(p.box_dir, 'release');
  SALT = 'release';
  MAX_BOXES = 2000;

  imdb = imdb_from_nyud2(NYU_ROOT_DIR, trainset, task, REGIONDIR, SALT, MAX_BOXES);
  imdb.roidb_func = @roidb_from_nyud2;

  feat_opts = struct('featDir', '');
  feat_opts(1) = [];
  global RCNN_CONFIG_OVERRIDE;
  switch model_typ
    case 'rgb_hha',
      conf_override.sub_dir = sprintf('rgb_hha_%d_%s', 30000, trainset);
      feat_opts(end+1) = struct('featDir', fullfile(p.cnnF_cache_dir, 'rgb_30000', imdb.dataset_name));
      feat_opts(end+1) = struct('featDir', fullfile(p.cnnF_cache_dir, 'hha_30000', imdb.dataset_name));
    case 'rgb',
      conf_override.sub_dir = sprintf('rgb_%d_%s', 30000, trainset);
      feat_opts(end+1) = struct('featDir', fullfile(p.cnnF_cache_dir, 'rgb_30000', imdb.dataset_name));
    case 'hha',
      conf_override.sub_dir = sprintf('hha_%d_%s', 30000, trainset);
      feat_opts(end+1) = struct('featDir', fullfile(p.cnnF_cache_dir, 'hha_30000', imdb.dataset_name));
    case 'disparity',
      conf_override.sub_dir = sprintf('disparity_%d_%s', 30000, trainset);
      feat_opts(end+1) = struct('featDir', fullfile(p.cnnF_cache_dir, 'disparity_30000', imdb.dataset_name));
  end
  RCNN_CONFIG_OVERRIDE = @() conf_override;
  rcnn_train_opts = {'feat_opts', feat_opts};

  rcnn_models = rcnn_train(imdb, rcnn_train_opts{:});

  if(isstr(testset)), testset = {testset}; end
  for i = 1:length(testset),
    imdb = imdb_from_nyud2(NYU_ROOT_DIR, testset{i}, task, REGIONDIR, SALT, MAX_BOXES);
    imdb.roidb_func = @roidb_from_nyud2;
    res{i} = rcnn_test(rcnn_models, imdb, '');
  end
end


function [dat] = read_nmc_archive_k_data(datafile, hdr, begsample, endsample, channelsel)

% READ_NMC_ARCHIVE_K_DATA reads data from nmc_archive_k datasets
%
% Used in read_data as
%   dat = read_nmc_archive_k_data(datafile, hdr, begsample, endsample, channelsel);
%
%
% This function specifically only reads data from one of the archived
% datasets of the Neurophysiological Mechanisms of Cognition group of
% Eric Maris, at the Donders Centre for Cognition, Radboud University,
% Nijmegen, the Netherlands. It should not be used for any other data
% format.
%
%
%

% Copyright (C) 2009, Roemer van der Meij
%
% 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$

% Sanity checks (to be added)

% Getting data-directory out of data-filename and check
datadir = datafile(1:(strfind(datafile, 'eeg.noreref')+11));
if exist(datadir,'dir') ~= 7
    ft_error('no proper data-directory provided, please check your paths');
end

% Getting session name + path out of data-filename
sessionpath = datafile(1:(end-4));

% Build array containing channel file extensions to be used in reading the data
channelext = [];
% Remove the 'CH' from channel labels
chanlabnum = hdr.label;
for ichan = 1:length(chanlabnum)
    chanlabnum{ichan} = chanlabnum(3:end);
end
for ichan = 1:length(channelsel)
    if length(hdr.label{channelsel(ichan)}) == 3
        channelext{ichan} = ['.00' hdr.label{channelsel(ichan)}(3:end)];
    elseif length(hdr.label{channelsel(ichan)}) == 4
        channelext{ichan} = ['.0' hdr.label{channelsel(ichan)}(3:end)];
    elseif  length(hdr.label{channelsel(ichan)}) == 5
        channelext{ichan} = ['.' hdr.label{channelsel(ichan)}(3:end)];
    end
end

% Loop over channels while reading in data from file, 1 file per channel
dat = zeros(length(channelsel),(endsample-begsample+1));
for ichan = 1:length(channelsel)
    channelfile = [sessionpath channelext{ichan}];
    datafid = fopen_or_error(channelfile,'r','l');
    fseek(datafid,(hdr.nBytes*(begsample-1)),'bof');
    dat(ichan,:) = fread(datafid,(endsample-begsample+1),hdr.dataformat)';
    fclose(datafid);
end


% Compiles all mex routines that are part of toolbox.
%
% USAGE
%  toolboxCompile
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Image&Video Toolbox      Version 3.01
% Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

disp('Compiling.......................................');
rd=fileparts(mfilename('fullpath')); rd=rd(1:end-9);

% general compile options (can make architecture specific)
opts = {'-output'};
if(exist('OCTAVE_VERSION','builtin')), opts={'-o'}; end

% if you get warnings on linux, you can set the gcc version using:
% opts = {'CXX=g++-4.1' 'CC=g++-4.1' 'LD=g++-4.1' '-l' ...
%   'mwlapack' '-l' 'mwblas' '-output' };

% compile c functions
fs={'assignToBins1','histc2c','ktHistcRgb_c','ktComputeW_c',...
  'nlfiltersep_max','nlfiltersep_sum','imtransform2_c',...
  'meanShift1','fernsInds1'};
ds=[repmat({'images'},1,7),repmat({'classify'},1,2)];
for i=1:length(fs), fs{i}=[rd '/' ds{i} '/private/' fs{i}]; end
for i=1:length(fs), mex([fs{i} '.c'],opts{:},[fs{i} '.' mexext]); end

% compile c++ functions
try
  fs={'convConst','gradientMex','rgbConvertMex','imResampleMex',...
    'imPadMex','opticalFlowHsMex','forestFindThr','forestInds'};
  ds=[repmat({'channels'},1,5) 'images' repmat({'classify'},1,2)];
  for i=1:length(fs), fs{i}=[rd '/' ds{i} '/private/' fs{i}]; end
  for i=1:length(fs), mex([fs{i} '.cpp'],opts{:},[fs{i} '.' mexext]); end
catch ME
  fprintf(['C++ mex failed, likely due to lack of a C++ compiler.\n' ...
    'Run ''mex -setup'' to specify a C++ compiler if available.\n'...
    'Or, one can specify a specific C++ explicitly (see mex help).\n']);
end

disp('..................................Done Compiling');


function [names,isdirs] = glob(pattern,prefix)
%GLOB   Filename expansion via wildcards.
% GLOB(PATTERN) returns a cell array of file/directory names which match the
% PATTERN.
% [NAMES,ISDIRS] = GLOB(PATTERN) also returns a logical vector indicating
% which are directories.
%
% Two types of wildcards are supported:
% * matches zero or more characters, besides /
% ** matches zero or more characters, including /, ending with a /
% *** is interpreted as ** followed by *, which means it matches zero or
% more characters, including /
%
% For example, 'a*b' matches 'ab','acb','acdb', but not 'a/b'.
% 'a**b' matches 'ab','a/b','ac/b','ac/d/b', but not 'acb' or 'a/cb'.
% 'a***b' matches all of the above plus 'a/cb','ac/d/cb',etc.
%
% 'a//b' is not considered a valid filename, so 'a/*/b' will not return
% 'a//b' or 'a/b'.
%
% Examples:
%   % if 'work' is a subdirectory, this returns only 'work', not its contents:
%   glob('work')
%   % returns 'work/fun.m' (not 'fun.m'):
%   glob('work/fun.m')
%   % all m-files in 'work', prefixed with 'work/':
%   glob('work/*.m')
%   % all files named 'fun.m' in 'work' or any subdirectory of 'work':
%   glob('work/**fun.m')
%   % all m-files in 'work' or any subdirectory of 'work':
%   glob('work/***.m')
%   % all files named 'fun.m' any subdirectory of 'work' (but not 'work'):
%   glob('work/**/fun.m')
%   % all files named 'fun.m' in any subdirectory of '.':
%   glob('**fun.m')
%   % all files in all subdirectories:
%   glob('***')
%
% See also globstrings.

% Written by Tom Minka, 28-Apr-2004
% (c) Microsoft Corporation. All rights reserved.

if nargin < 2
  prefix = '';
end

names = {};
isdirs = [];
if isempty(pattern)
  return
end

% break the pattern into path components
[first,rest] = strtok(pattern,'/');

i = strfind(first,'**');
if ~isempty(i)
  % double-star pattern
  i = i(1); % process first occurrence
  rest = fullfile(first((i+2):end),rest);
  first = first(1:(i-1));
  new_pattern = [first rest];
  % if the pattern was 'a**b/c', new_pattern is 'ab/c'
  [names,isdirs] = glob(new_pattern,prefix);
  first = [first '*'];
  rest = ['**' rest];
  % if the pattern was 'a**b/c', it is now 'a*/**b/c'
end

% expand the first component
fullfirst = fullfile(prefix,first);
if ~iswild(fullfirst) & isdir(fullfirst)
  first_files = struct('name',first,'isdir',1);
else
  first_files = stripdots(dir(fullfirst));
end
% for each match, add it to the results or recurse on the rest of the pattern
for i = 1:length(first_files)
  new_prefix = fullfile(prefix,first_files(i).name);
  if isempty(rest)
    names{end+1} = new_prefix;
    isdirs(end+1) = first_files(i).isdir;
  elseif first_files(i).isdir
    [new_names, new_isdirs] = glob(rest,new_prefix);
    names = cellcat(names, new_names);
    isdirs = [isdirs; new_isdirs];
  end
end
names = names(:);
isdirs = isdirs(:);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function files = stripdots(files)
% omit . and .. from the results of DIR

names = {files.name};
ok = (~strcmp(names,'.') & ~strcmp(names,'..'));
files = files(ok);

function c = cellcat(c,c2)

c = {c{:} c2{:}};

function tf = iswild(pattern)

tf = ~isempty(strfind(pattern,'*'));

function s = regexp_quote(s)

regexprep(s,'[!#]^','#^');
regexprep(s,'[!#]$','#$');


function [inpts,volpts]=mrClearPoints(inpts,volpts)
%function [inpts,volpts]=mrClearPoints(inpts,volpts)
%
%Clear all alignment points

%6/16/96	gmb	wrote it.

ynstr=input('Clear all points (y/n)? ','s');

if ynstr(1)=='y'
	inpts=[];
	volpts=[];
end

npoints = size(volpts,1);
disp([num2str(npoints),' pairs of points selected.']);


function atlas = ft_read_atlas(filename, varargin)

% FT_READ_ATLAS reads an template/individual segmentation or parcellation from disk.
% The volumetric segmentation or the surface-based parcellation can either represent
% a template atlas (e.g. AAL or the Talairach Daemon), it can represent an
% individualized atlas (e.g. obtained from FreeSurfer) or it can represent an
% unlabeled parcellation/segmentation obtained from an individual's DTi, anatomical,
% or resting state fMRI scan.
%
% Use as
%   atlas = ft_read_atlas(filename, ...)
% or
%   atlas = ft_read_atlas({filenamelabels, filenamemesh}, ...)
%
% Additional options should be specified in key-value pairs and can include
%   'format'      = string, see below
%   'unit'        = string, e.g. 'mm' (default is to keep it in the native units of the file)
%   'map'         = string, 'maxprob' (default), or 'prob', for FSL-based atlases, providing
%                   either a probabilistic segmentation or a maximum a posterior probability map
%   'labelfile'   = string, point to a (generic) text or xml file for interpretation of the values in the atlas
%
% For individual surface-based atlases from FreeSurfer you should specify two
% filenames as a cell-array: the first points to the file that contains information
% with respect to the parcels' labels, the second points to the file that defines the
% mesh on which the parcellation is defined.
%
% The 'format' variable, if not specified, will be determined automatically. In general
% it will not be needed to specify it. The following formats are supported:
%
% Volumetric atlases based on a (gzipped) nifti-file with an companion txt-file for interpretation
%   'aal'               assumes filename starting with 'ROI_MNI'
%   'brainnetome'       assumes companion lookuptable txt-file starting with 'Brainnetome Atlas'
%   'simnibs_v4'        assumes filename starting with 'final_tissues', with companion freesurfer-style lookuptable txt-file
%   'wfu'               assumes specific formatting of companion lookuptable txt-file
%
% Volumetric atlases based on a (gzipped) nifti-file with hard coded assumption on the labels
%   'yeo7'
%   'yeo17'
%
% Volumetric atlases based on a folder with (gzipped) nifti-files with a companion xml-file for interpretation
%   'fsl'               assumes path to folder with data mentioned in the xml-file. Use xml-file as filename
%
% Volumetric atlases based on the freesurfer mgz format with standard lookuptable txt-file for interpretation
%   'freesurfer_volume' assumes the freesurfer LUT file for interpretation, and assumes aparc or aseg in the
%                       filename, used for subject-specific parcellations
%
% Volumetric atlases based on the afni software
%   'afni'              assumes filename containing BRIK or HEAD, assumes generic interpretation of the labels
%                       for the TTatlas+tlrc, or otherwise the interpretation should be in the file
%
% Volumetric atlas based on the spm_anatomy toolbox
%   'spm_anatomy'       pair of .hdr/.img files, and an associated mat-file for the interpretation
%                       Specify the associated mat-file with MPM in filename
%
% Surface based atlases, requiring a pair of files, containing the labels, and the associated geometry
%   'caret_label'       hcp-workbench/caret style .gii, with .label. in filename, requires additional file describing the geometry
%   'freesurfer_surface' freesurfer style annotation file, requires additional file describing the geometry
%
% Miscellaneous formats
%   'mat'               mat-file, with FieldTrip style struct, other matlab data that FieldTrip knows to handle, can also be
%                       Brainstorm derived surfaces
%   'vtpm'
%
% For volume data for whicth the format cannot be automatically detected, or if the volume data does not have a companion file
% for the interpretation of the labels, a list of 'fake' labels will be generated.
%
% The output atlas will be represented as structure according to FT_DATATYPE_SEGMENTATION or
% FT_DATATYPE_PARCELLATION.
%
% The 'lines' and the 'colorcube' colormaps may be useful for plotting the different
% patches, for example using FT_PLOT_MESH, or FT_SOURCEPLOT.
%
% See also FT_READ_MRI, FT_READ_HEADSHAPE, FT_PREPARE_SOURCEMODEL, FT_SOURCEPARCELLATE, FT_PLOT_MESH

% Copyright (C) 2005-2019, Robert Oostenveld, Ingrid Nieuwenhuis, Jan-Mathijs Schoffelen, Arjen Stolk
% Copyright (C) 2023, Jan-Mathijs Schoffelen
%
% 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$

% deal with multiple filenames, if the geometry and labels are stored
% in different files, as with freesurfer/caret
if isa(filename, 'cell')
  if numel(filename)==2
    filenamemesh = filename{2};
    filename     = filename{1};
  else
    ft_error('with multiple filenames, only 2 files are allowed');
  end % if precisely two input files
end % iscell

% optionally get the data from an URL and make a temporary local copy
filename = fetch_url(filename);

[p, f, x] = fileparts(filename);

labelfile = ft_getopt(varargin, 'labelfile', []);
ftype     = ft_filetype(filename);

% if the original file was a .gz
if isequal(x,'.gz')
  [p, f, x] = fileparts(filename(1:end-3));
end

% do an educated guess of the format based on the input, ensure that the
% required additional functions are available, and specify the companion labelfile
if contains(filename, 'BRIK') || contains(filename, 'HEAD')
  % the above is needed to correctly detect zipped files
  ft_hastoolbox('afni', 1);

  % this is robust for both compressed or uncompressed afni atlases.
  format = 'afni';
elseif startsWith(ftype, 'nifti')

  % first handle the ones for which the labels are implicit in the filename
  if contains(f, 'Yeo2011_7Networks')
    % assume to be conform the shared atlas, with hardcoded index-to-label mapping
    format = 'yeo7';
  elseif contains(f, 'Yeo2011_17Networks')
    % assume to be conform the shared atlas, with hardcoded index-to-label mapping
    format = 'yeo17';
  end

  % try for different conventions of the naming of a potential companion labelfile
  if isempty(labelfile)
    labelfile = fullfile(p, sprintf('%s.txt', f));
    if ~exist(labelfile, 'file')
      % in case the volume was zipped, and the txt only replaced the gz
      labelfile = fullfile(p, sprintf('%s.nii.txt', f));
    end
    if ~exist(labelfile, 'file')
      labelfile = ''; % revert back to empty
    end
  end

  if ~isempty(labelfile)
    % do a quick check on the companion labelfile to specify the format
    fid = fopen_or_error(labelfile, 'rt');
    l1  = fgetl(fid);
    if strcmp(l1(1),'[') && strcmp(l1(end),']')
      % specific to this one is that some of the wakeforest atlases contain non-human data, so no fixed coordsys can be assumed
      format   = 'wfu';
      coordsys = 'unknown';
    elseif strcmp(l1,'Brainnetome Atlas')
      % specific to this one is the coordinate system it seems
      format   = 'brainnetome';
      coordsys = 'mni'; % apparently the image is in radiological convention,
      % so the voxel-axes are left-handed. The even valued parcels should end
      % up in the right hemisphere
    elseif contains(filename, 'ROI_MNI') || contains(filename, 'AAL')
      % newer versions of AAL also exist with a companion .xml file, this is not yet supported
      format   = 'aal';
      coordsys = 'mni';
    end
    fclose(fid);
  end
  if contains(filename, 'final_tissues')
    ft_hastoolbox('freesurfer', 1); % required to read lookuptable

    % assume to be from SimNIBS version 4
    format = 'simnibs_v4';

    labelfile = fullfile(p, sprintf('%s_LUT.txt', f));
  end

  if isempty(labelfile)
    % just a nifti file without interpretation of labels
    format = 'nifti_no_label';
  end

elseif isequal(ftype, 'freesurfer_mgz') && contains(f, 'aparc') || contains(f, 'aseg')
  ft_hastoolbox('freesurfer', 1);

  % individual volume based segmentation from freesurfer
  format = 'freesurfer_volume';

  if isempty(labelfile)
    % use the version for freesurfer that is in fieldtrip/external/freesurfer
    [ftver, ftpath] = ft_version;
    labelfile  = fullfile(ftpath, 'external/freesurfer', 'FreeSurferColorLUT.txt');
  end

elseif isequal(ftype, 'freesurfer_annot')
  ft_hastoolbox('freesurfer', 1);

  % individual volume based segmentation from freesurfer
  format = 'freesurfer_surface';

elseif isequal(ftype, 'caret_label')
  ft_hastoolbox('gifti', 1);

  % this is a gifti file that contains both the values for a set of vertices as well as the labels.
  format = 'caret_label';

elseif contains(filename, 'MPM.mat')
  ft_hastoolbox('spm8up', 1);

  % assume to be from the spm_anatomy toolbox
  format = 'spm_anatomy';

elseif exist(fullfile(p, [f '_MPM.mat']), 'file')
    ft_warning('please specify the corresponding MPM.mat file as the filename');
    filename = fullfile(p, [f '_MPM.mat']); % update the filename
    [p, f, x] = fileparts(filename);

    ft_hastoolbox('spm8up', 1);

    % assume to be from the spm_anatomy toolbox
    format = 'spm_anatomy';

elseif strcmp(x, '.xml')
  ft_hastoolbox('gifti', 1); % required to read the xml

  % fsl-style atlas, this is assumed to consist of an .xml file that specifies the labels, as well as a pointer
  % to the file/folder with the volume data.
  format = 'fsl';

  labelfile = fullfile(p, sprintf('%s.xml',f));

elseif strcmp(x, '.mat')
  % mat-file to contain a well-defined structure
  format = 'mat';

else

  format = 'unknown';
end

% get the optional input arguments
fileformat = ft_getopt(varargin, 'format', format);
unit       = ft_getopt(varargin, 'unit');

switch fileformat
  case {'aal' 'brainnetome' 'freesurfer_volume' 'nifti_no_label' 'simnibs_v4' 'wfu'}
    atlas = ft_read_mri(filename, 'outputfield', 'tissue');

    % interpret the format specific labelfile
    if isequal(fileformat, 'aal')
      % The labelfile is a combination of nii+txt file, where the txt file may contain three columns like this
      %   FAG	Precentral_L	2001
      %   FAD	Precentral_R	2002
      %   ...

      fid = fopen_or_error(labelfile, 'rt');
      C = textscan(fid, '%s%s%d');
      lab = C{2};
      idx = C{3};
      fclose(fid);
    elseif isequal(fileformat, 'wfu')
      % the download from http://fmri.wfubmc.edu comes with pairs of nii and txt files
      % the text file looks like this, with tabs between the colums
      % the section at the end with three times 191 does not always exist
      %
      % [ TD Labels]
      % 53	Angular Gyrus         191 191 191
      % 39	Anterior Cingulate		191 191 191
      % ...

      fid = fopen_or_error(labelfile, 'rt');
      C = textscan(fid, '%d%s%*[^\n]', 'HeaderLines', 1, 'Delimiter', '\t');
      lab = C{2};
      idx = C{1};
      fclose(fid);
    elseif any(strcmp(fileformat, {'simnibs_v4' 'freesurfer_volume'}))
      [idx, lab, rgba] = read_fscolorlut(labelfile);
      lab = cellstr(lab);
    elseif isequal(fileformat, 'brainnetome')
      % Brainnetome Atlas: L. Fan, et al.The Human Brainnetome Atlas: A New Brain Atlas Based on
      % Connectional Architecture. Cereb Cortex 2016; 26 (8): 3508-3526. doi: 10.1093/cercor/bhw157
      fid = fopen_or_error(labelfile, 'rt');
      fgetl(fid); % this reads: 'Brainnetome Atlas'
      lab = cell(246,1);
      for i=1:246
        lab{i,1}=fgetl(fid);
      end
      idx = (1:246)';
      fclose(fid);

    elseif isequal(fileformat, 'nifti_no_label')
      % the file does not exist
      ft_warning('cannot locate a labelfile, making default tissue labels');

      idx = (1:max(atlas.tissue(:)))';
      lab = cell(size(idx));
      for i = 1:numel(lab)
        % this is consistent with FIXSEGMENTATION
        lab{i} = sprintf('tissue %d', i);
      end
    end

    if ~isfield(atlas, 'coordsys') && exist('coordsys', 'var')
      atlas.coordsys = coordsys;
    end

    uval = unique(atlas.tissue(:));
    sel  = find(ismember(idx, uval));
    fprintf('subselecting %d labels from the total list of %d\n', numel(sel), numel(lab));
    idx  = idx(sel);
    lab  = lab(sel);
    if exist('rgba', 'var')
      tmprgba = rgba(sel,:);
      rgba = zeros(0,4);
    end

    % remap the values in the data, if needed
    if ~isequal(idx(:)', 1:numel(idx))
      dat = zeros(atlas.dim);
      cnt = 0;
      for k = 1:numel(idx)
        sel = atlas.tissue==idx(k);
        if sum(sel(:))
          cnt = cnt+1;
          fprintf('re-indexing label %s to a value of %d (was %d)\n', lab{k}, cnt, idx(k));
          dat(sel)           = cnt;
          tissuelabel{cnt,1} = lab{k};
          if exist('rgba', 'var')
            rgba(cnt,:) = tmprgba(k,:);
          end
        end
      end
      atlas.tissue = dat;
    else
      tissuelabel = lab;
    end

    atlas.tissuelabel = tissuelabel;
    if exist('rgba', 'var'), atlas.rgba = rgba; end

    % reduce memory footprint
    if numel(tissuelabel)<=intmax('uint8')
      atlas.tissue = uint8(atlas.tissue);
    elseif numel(tissuelabel)<=intmax('uint16')
      atlas.tissue = uint16(atlas.tissue);
    elseif numel(tissuelabel)<=intmax('uint32')
      atlas.tissue = uint32(atlas.tissue);
    end

  case 'afni'

    tmp     = ft_read_mri(filename);
    if isfield(tmp, 'coordsys') && ~strcmp(tmp.coordsys, 'unknown')
      coordsys = tmp.coordsys;
    elseif isfield(tmp.hdr, 'TEMPLATE_SPACE') && ~isempty(tmp.hdr.TEMPLATE_SPACE)
      coordsys = lower(tmp.hdr.TEMPLATE_SPACE); % FIXME this is based on AFNI conventions, not easily decodable by FT
    else
      coordsys = 'tal'; % FIXME could be different in other atlases
    end

    if isfield(tmp.hdr, 'ATLAS_LABEL_TABLE') && ~isempty(tmp.hdr.ATLAS_LABEL_TABLE)
      if isfield(tmp.hdr.ATLAS_LABEL_TABLE(1), 'sb_label') && ~all(tmp.anatomy(:)==round(tmp.anatomy(:)))
        % probabilistic atlas
        isprobabilistic = true;
      else
        % indexed atlas
        isprobabilistic = false;
      end
      labels  = {tmp.hdr.ATLAS_LABEL_TABLE.struct}';
      values  = [tmp.hdr.ATLAS_LABEL_TABLE.val]';

    elseif contains(filename, 'TTatlas+tlrc')
      isprobabilistic = false;

      [labels, values] = TTatlas_labels;

    else
      ft_error('no information about the atlas labels is available');
    end

    atlas     = [];
    atlas.dim = tmp.dim(1:3);
    atlas.transform = tmp.transform;
    atlas.hdr = tmp.hdr;
    atlas.coordsys = coordsys;

    nbrick  = size(tmp.anatomy,4);
    for k = 1:nbrick

      if ~isprobabilistic
        brickname = sprintf('brick%d',k-1);
        brick     = tmp.anatomy(:,:,:,k);
        ulabel    = setdiff(unique(brick(:)), 0);
        label     = cell(size(ulabel));
        nlabel    = numel(label);

        % renumber the brick from 1:N and keep track of the label
        newbrick  = zeros(size(brick));
        for i = 1:nlabel
          sel = find(values==ulabel(i));
          if ~isempty(sel)
            label(i) = labels(sel);
            newbrick(brick==ulabel(i)) = i;
          else
            ft_warning('the value %d does not have a label according to the ATLAS_LABEL_TABLE and will be discarded', ulabel(i));
          end
        end
        atlas.(brickname) = newbrick;
        atlas.([brickname 'label']) = label;
      else
        atlas.(labels{k}) = tmp.anatomy(:,:,:,values(k)+1); % indexing is 0-based in this case
      end

    end

  case {'freesurfer_surface'}

    if contains(filename, 'a2009s')
      parcelfield = 'a2009s';
    elseif contains(filename, 'aparc')
      parcelfield = 'aparc';
    elseif contains(filename, 'ba')
      parcelfield = 'BA';
    else
      ft_error('unknown freesurfer parcellation type requested');
    end

    % read the labels
    [v, p, c] = read_annotation(filename);

    label = c.struct_names;
    rgba  = c.table(:,1:4);
    rgb   = c.table(:,5); % compound value that is used for the indexing in vector p
    index = ((1:c.numEntries)-1)';

    switch ft_filetype(filenamemesh)
      case 'freesurfer_triangle_binary'
        [pos, tri] = read_surf(filenamemesh);

        % ensure the triangles to be 1-indexed
        if min(tri(:))==0 && max(tri(:))==size(pos,1)-1
          tri = tri+1;
        end

        bnd.pos    = pos;
        bnd.tri    = tri;
        reindex    = true;
      otherwise
        ft_error('unsupported fileformat for surface mesh');
    end

    % check the number of vertices
    if size(bnd.pos,1) ~= numel(p)
      ft_error('the number of vertices in the mesh does not match the number of elements in the parcellation');
    end

    % reindex the parcels, if needed: I am not fully sure about this, but the caret
    % label files seem to have the stuff numbered with normal numbers, with unknown
    % being -1. assuming them to be in order;
    if reindex
      % this is then freesurfer convention, coding in rgb
      newp = zeros(size(p));
      for k = 1:numel(label)
        newp(p==rgb(k)) = index(k)+1;
      end
    else
      uniquep = unique(p);
      if uniquep(1)<0
        p(p<0) = 0;
      end
      newp   = p;
    end
    atlas       = [];
    atlas.pos   = bnd.pos;
    atlas.tri   = bnd.tri;
    atlas.(parcelfield)            = newp;
    atlas.([parcelfield, 'label']) = label;
    atlas.rgba  = rgba;
    atlas       = ft_determine_units(atlas);

  case 'caret_label'

    g = gifti(filename);

    rgba = [];
    if isfield(g, 'labels')
      label = g.labels.name(:);
      key   = g.labels.key(:);
      if isfield(g.labels, 'rgba')
        rgba = g.labels.rgba; % I'm not sure whether this always exists
      end
    else
      label = g.private.label.name(:);
      key   = g.private.label.key(:);
      if isfield(g.private.label, 'rgba')
        rgba = g.private.label.rgba; % I'm not sure whether this always exists
      end
    end

    %label = g.private.label.name; % provides the name of the parcel
    %key   = g.private.label.key;  % maps value to name

    % Store each column in cdata as an independent parcellation, because
    % each vertex can have multiple values in principle

    atlas = [];
    for k = 1:size(g.cdata,2)
      tmporig  = g.cdata(:,k);
      tmpnew   = nan(size(tmporig));
      tmplabel = cell(0,1);
      tmprgba  = zeros(0,4);
      cnt = 0;
      for m = 1:numel(label)
        sel = find(tmporig==key(m));
        if ~isempty(sel)
          cnt = cnt+1;
          if any(strcmp(tmplabel,deblank(label{m})))
            % one feature of a gifti can be that the same labels can exist (and
            % are treated as a different parcel) while they should be the same
            % parcel, i.e. when there's an empty space at the end of the label
            val = find(strcmp(tmplabel, deblank(label{m})));
          else
            % add as a new label
            tmplabel{end+1,1} = label{m};
            if ~isempty(rgba), tmprgba(end+1,:)  = rgba(m,:); end
            val = cnt;
          end
          tmpnew(tmporig==key(m)) = val;
        end
      end

      % there is some additional meta data that may be useful, but for now
      % stick to the rather uninformative parcellation1/2/3 etc.
      %
      % if strcmp(g.private.data{k}.metadata(1).name, 'Name')
      %   parcelfield = fixname(g.private.data{k}.metadata(1).value);
      % else
      %   ft_error('could not determine parcellation name');
      % end

      if size(g.cdata,2)>1
        parcelfield = ['parcellation' num2str(k)];
      else
        parcelfield = 'parcellation';
      end

      atlas.(parcelfield)           = tmpnew;
      atlas.([parcelfield 'label']) = tmplabel;
      if ~isempty(tmprgba), atlas.rgba = tmprgba; end
    end

    if exist('filenamemesh', 'var')
      tmp       = ft_read_headshape(filenamemesh);
      atlas.pos = tmp.pos;
      atlas.tri = tmp.tri;
      atlas     = ft_determine_units(atlas);
    elseif ~isfield(atlas, 'coordsys')
      atlas.coordsys = 'unknown';
    end

  case 'spm_anatomy'

    % load the map, this is assumed to be the struct-array MAP
    load(filename);
    [p,f,e]      = fileparts(filename);
    mrifilename  = fullfile(p,[strrep(f, '_MPM',''),'.img']);
    atlas        = ft_read_mri(mrifilename, 'dataformat', 'analyze_img', 'outputfield', 'tissue');
    tissue       = round(atlas.tissue); % I don't know why the values are non-integer
    label        = {MAP.name}';
    idx          = [MAP.GV]';

    % check whether all labels are present
    if numel(intersect(idx,unique(tissue(:))))<numel(idx)
      fprintf('there are fewer labels in the volume than in the list\n');
    end

    % remap the values of the labels to run from 1-numel(idx)
    newtissue = zeros(size(tissue));
    for k = 1:numel(idx)
      newtissue(tissue==idx(k)) = k;
    end
    atlas.tissue      = newtissue;
    atlas.tissuelabel = label;
    atlas.coordsys    = 'spm'; % I think this is safe to assume

    clear tissue newtissue;

  case 'fsl'
    map = ft_getopt(varargin, 'map', 'maxprob');
    switch map
      case 'prob'
        imagefile = 'imagefile';
      case 'maxprob'
        imagefile = 'summaryimagefile';
      otherwise
        error('unknown map requested');
    end

    ft_hastoolbox('gifti', 1);
    hdr = xmltree(filename);
    hdr = convert(hdr);

    % get the full path
    [p, f , x]  = fileparts(filename);

    mrifilename = sprintf('%s.nii.gz', hdr.header.images{1}.(imagefile));
    if isequal(mrifilename(1), '/')
      mrifilename = mrifilename(2:end); % remove first backslash to avoid error if no full path was given
    end

    % this uses the thresholded image
    switch map
      case 'maxprob'
        atlas        = ft_read_mri(fullfile(p, mrifilename), 'outputfield', 'tissue');
        atlas.tissuelabel = hdr.data.label(:);
        atlas.coordsys    = 'mni';
      case 'prob'
        tmp   = ft_read_mri(fullfile(p, mrifilename));
        atlas = removefields(tmp, 'anatomy');
        for m = 1:numel(hdr.data.label)
          fn = strrep(hdr.data.label{m}, ' ' , '_');
          fn = strrep(fn, '-', '_');
          fn = strrep(fn, '(', '');
          fn = strrep(fn, ')', '');

          atlas.(fn) = tmp.anatomy(:,:,:,m);
          if ~isa(atlas.(fn), 'double') && ~isa(atlas.(fn), 'single')
            % ensure that the probabilistic values are either double or
            % single precision, do single precision to save memory
            atlas.(fn) = single(atlas.(fn));
          end
          if any(atlas.(fn)(:)>1) && all(atlas.(fn)(:)<=100)
            % convert to probability values, assuming 100 to be max
            atlas.(fn) = atlas.(fn)./100;
          end
        end
        atlas.coordsys = 'mni';
        atlas.dim      = atlas.dim(1:3);
    end

  case 'mat'
    tmp = load(filename);
    if isfield(tmp, 'Vertices') && isfield(tmp, 'Atlas')
      % this applies to BrainStorm *.mat files containing cortical meshes
      atlas.pos = tmp.Vertices;
      % copy some optional fields over with a new name
      atlas = copyfields(tmp, atlas, {'Faces', 'Curvature', 'SulciMap'});
      atlas = renamefields(atlas, {'Faces', 'Curvature', 'SulciMap'}, {'tri', 'curv', 'sulc'});
      for i=1:numel(tmp.Atlas)
        name   = fixname(tmp.Atlas(i).Name);
        nlabel = numel(tmp.Atlas(i).Scouts);
        label  = cell(1, nlabel);
        index  = zeros(size(atlas.pos,1), 1);
        for j=1:nlabel
          index(tmp.Atlas(i).Scouts(j).Vertices) = j;
          label{j} = tmp.Atlas(i).Scouts(j).Label;
        end
        atlas.( name         ) = index;
        atlas.([name 'label']) = label;
      end
    elseif isfield(tmp, 'atlas')
      % this applies to most FieldTrip *.mat files
      atlas = tmp.atlas;
    elseif numel(fieldnames(tmp))==1
      % just take whatever variable is contained in the file
      fn = fieldnames(tmp);
      atlas = tmp.(fn{1});
      if isstruct(atlas)
        ft_warning('assuming that the variable "%s" in "%s" represents the atlas', fn{1}, filename);
      else
        ft_error('cannot read atlas structure from "%s"', filename);
      end
    else
      ft_error('the mat-file %s does not contain a variable called ''atlas''',filename);
    end

  case 'yeo7'
    % this uses Yeo2011_7Networks_MNI152_FreeSurferConformed1mm_LiberalMask_colin27.nii, which is
    % the 7 network parcellation from https://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation_Yeo2011
    % aligned to the colin27 template (skull-stripped version of single_subj_T1_1mm.nii)
    % using AFNI's 3dQwarp and 3dNwarpApply
    atlas = ft_read_mri(filename, 'outputfield', 'tissue');

    atlas.coordsys    = 'mni';
    atlas.tissuelabel = {
      '7Networks_1'
      '7Networks_2'
      '7Networks_3'
      '7Networks_4'
      '7Networks_5'
      '7Networks_6'
      '7Networks_7'
      };

    colors = [
      120 18 134;
      70 130 180;
      0 118 14;
      196 58 250;
      220 248 164;
      230 148 34;
      205 62 78
      ]; % not used

  case 'yeo17'
    % this uses Yeo2011_17Networks_MNI152_FreeSurferConformed1mm_LiberalMask_colin27.nii, which is
    % the 17 network parcellation from https://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation_Yeo2011
    % aligned to the colin27 template (skull-stripped version of single_subj_T1_1mm.nii) using AFNI's 3dQwarp and 3dNwarpApply
    atlas = ft_read_mri(filename, 'outputfield', 'tissue');

    atlas.coordsys    = 'mni';
    atlas.tissuelabel = {
      '17Networks_1'
      '17Networks_2'
      '17Networks_3'
      '17Networks_4'
      '17Networks_5'
      '17Networks_6'
      '17Networks_7'
      '17Networks_8'
      '17Networks_9'
      '17Networks_10'
      '17Networks_11'
      '17Networks_12'
      '17Networks_13'
      '17Networks_14'
      '17Networks_15'
      '17Networks_16'
      '17Networks_17'
      };
    colors = [
      120 18 134;
      255 0 0;
      70 130 180;
      42 204 164;
      74 155 60;
      0 118 14;
      196 58 250;
      255 152 213;
      220 248 164;
      122 135 50;
      119 140 176;
      230 148 34;
      135 50 74;
      12 48 255;
      0 0 130;
      255 255 0;
      205 62 78
      ]; % not used

  otherwise
    ft_error('unsupported format "%s"', fileformat);

end % switch fileformat

if ~isempty(unit)
  % ensure the atlas is in the desired units
  atlas = ft_convert_units(atlas, unit);
else
  % ensure the units of the atlas are specified
  try
    atlas = ft_determine_units(atlas);
  catch
    % ft_determine_units will fail for triangle-only gifties.
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TTatlas labels moved to a subfunction for readability of the above code
function [labels, values] = TTatlas_labels

% the following information is from https://sscc.nimh.nih.gov/afni/doc/misc/afni_ttatlas/index_html
values = [
  68
  71
  20
  21
  22
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  70
  72
  73
  74
  75
  76
  77
  124
  125
  126
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  144
  145
  151
  146
  147
  148
  149
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  93
  94
  95
  96
  97
  98
  99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  66
  65
  127
  64
  67
  ];

labels = {
  'Hippocampus'
  'Amygdala'
  'Posterior Cingulate'
  'Anterior Cingulate'
  'Subcallosal Gyrus'
  'Transverse Temporal Gyrus'
  'Uncus'
  'Rectal Gyrus'
  'Fusiform Gyrus'
  'Inferior Occipital Gyrus'
  'Inferior Temporal Gyrus'
  'Insula'
  'Parahippocampal Gyrus'
  'Lingual Gyrus'
  'Middle Occipital Gyrus'
  'Orbital Gyrus'
  'Middle Temporal Gyrus'
  'Superior Temporal Gyrus'
  'Superior Occipital Gyrus'
  'Inferior Frontal Gyrus'
  'Cuneus'
  'Angular Gyrus'
  'Supramarginal Gyrus'
  'Cingulate Gyrus'
  'Inferior Parietal Lobule'
  'Precuneus'
  'Superior Parietal Lobule'
  'Middle Frontal Gyrus'
  'Paracentral Lobule'
  'Postcentral Gyrus'
  'Precentral Gyrus'
  'Superior Frontal Gyrus'
  'Medial Frontal Gyrus'
  'Lentiform Nucleus'
  'Hypothalamus'
  'Red Nucleus'
  'Substantia Nigra'
  'Claustrum'
  'Thalamus'
  'Caudate'
  'Caudate Tail'
  'Caudate Body'
  'Caudate Head'
  'Ventral Anterior Nucleus'
  'Ventral Posterior Medial Nucleus'
  'Ventral Posterior Lateral Nucleus'
  'Medial Dorsal Nucleus'
  'Lateral Dorsal Nucleus'
  'Pulvinar'
  'Lateral Posterior Nucleus'
  'Ventral Lateral Nucleus'
  'Midline Nucleus'
  'Anterior Nucleus'
  'Mammillary Body'
  'Medial Globus Pallidus'
  'Lateral Globus Pallidus'
  'Putamen'
  'Nucleus Accumbens'
  'Medial Geniculum Body'
  'Lateral Geniculum Body'
  'Subthalamic Nucleus'
  'Brodmann area 1'
  'Brodmann area 2'
  'Brodmann area 3'
  'Brodmann area 4'
  'Brodmann area 5'
  'Brodmann area 6'
  'Brodmann area 7'
  'Brodmann area 8'
  'Brodmann area 9'
  'Brodmann area 10'
  'Brodmann area 11'
  'Brodmann area 13'
  'Brodmann area 17'
  'Brodmann area 18'
  'Brodmann area 19'
  'Brodmann area 20'
  'Brodmann area 21'
  'Brodmann area 22'
  'Brodmann area 23'
  'Brodmann area 24'
  'Brodmann area 25'
  'Brodmann area 27'
  'Brodmann area 28'
  'Brodmann area 29'
  'Brodmann area 30'
  'Brodmann area 31'
  'Brodmann area 32'
  'Brodmann area 33'
  'Brodmann area 34'
  'Brodmann area 35'
  'Brodmann area 36'
  'Brodmann area 37'
  'Brodmann area 38'
  'Brodmann area 39'
  'Brodmann area 40'
  'Brodmann area 41'
  'Brodmann area 42'
  'Brodmann area 43'
  'Brodmann area 44'
  'Brodmann area 45'
  'Brodmann area 46'
  'Brodmann area 47'
  'Uvula of Vermis'
  'Pyramis of Vermis'
  'Tuber of Vermis'
  'Declive of Vermis'
  'Culmen of Vermis'
  'Cerebellar Tonsil'
  'Inferior Semi-Lunar Lobule'
  'Fastigium'
  'Nodule'
  'Uvula'
  'Pyramis'
  'Culmen'
  'Declive'
  'Dentate'
  'Tuber'
  'Cerebellar Lingual'
  };


%GEOM_REVERT_OBJECT Revert/undo geometry object operations.
%
%   [ GEOM ] = GEOM_REVERT_OBJECT( GEOM, TAG ) Reverts/undos geometry
%   object operations by replacing the geometry object TAG with the
%   objects in its children field (with uniqified tags).

% Copyright 2013-2022 Precise Simulation, Ltd.


function display(obj)
disp([num2str(obj.value) ' +/- ' num2str(obj.error)])


function varargout = wave_clus_aux4(varargin)
% WAVE_CLUS_AUX1 M-file for wave_clus_aux.fig
%      WAVE_CLUS_AUX, by itself, creates a new WAVE_CLUS_AUX or raises the existing
%      singleton*.
%
%      H = WAVE_CLUS_AUX returns the handle to a new WAVE_CLUS_AUX or the handle to
%      the existing singleton*.
%
%      WAVE_CLUS_AUX('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in WAVE_CLUS_AUX.M with the given input arguments.
%
%      WAVE_CLUS_AUX('Property','Value',...) creates a new WAVE_CLUS_AUX or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before wave_clus_aux_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to wave_clus_aux_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help wave_clus_aux

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @wave_clus_aux4_OpeningFcn, ...
                   'gui_OutputFcn',  @wave_clus_aux4_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before wave_clus_aux is made visible.
function wave_clus_aux4_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to wave_clus_aux (see VARARGIN)

% Choose default command line output for wave_clus_aux
handles.output = hObject;

set(handles.isi24_accept_button,'value',1);
set(handles.isi25_accept_button,'value',1);
set(handles.isi26_accept_button,'value',1);
set(handles.isi27_accept_button,'value',1);
set(handles.isi28_accept_button,'value',1);
set(handles.fix24_button,'value',0);
set(handles.fix25_button,'value',0);
set(handles.fix26_button,'value',0);
set(handles.fix27_button,'value',0);
set(handles.fix28_button,'value',0);

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = wave_clus_aux4_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

h_figs=get(0,'children');
h_fig = findobj(h_figs,'tag','wave_clus_figure');
USER_DATA = get(h_fig,'UserData');
par = USER_DATA{1};

for i = 24:28
	si = num2str(i);
	set(eval(['handles.isi' si '_accept_button']),'value',1);
	set(eval(['handles.isi' si '_reject_button']),'value',0);
	set(eval(['handles.fix' si '_button']),'value',0);

	eval(['set(handles.isi' si '_nbins,''string'',par.nbins' si ');']);
	eval(['set(handles.isi' si '_bin_step,''string'',par.bin_step' si ');']);

end

plot_spikes_aux(handles,USER_DATA,4);