function fgplvmPrintPlot(model, lbls, capName, experimentNo)

% FGPLVMPRINTPLOT Print latent space for learnt model.
% FORMAT
% DESC prints a latent space repsresentation for an FGPLVM model.
% ARG model : the model to use for plotting the latent space.
% ARG lbls : any lables that are available for plotting.
% ARG capName : the name of the saved plots.
% ARG experimentNo : the experiment number to assign to the files.
%
% SEEALSO : lvmScatterPlot
%
% COPYRIGHT : Neil D. Lawrence, 2006

% FGPLVM

lvmScatterPlot(model, lbls);
fileName = ['dem' capName num2str(experimentNo)];
print('-depsc', ['../tex/diagrams/' fileName])
print('-deps', ['../tex/diagrams/' fileName 'NoColour'])

% make smaller for PNG plot.
pos = get(gcf, 'paperposition')
origpos = pos;
pos(3) = pos(3)/2;
pos(4) = pos(4)/2;
set(gcf, 'paperposition', pos);
fontsize = get(gca, 'fontsize');
set(gca, 'fontsize', fontsize/2);
lineWidth = get(gca, 'lineWidth');
set(gca, 'lineWidth', lineWidth*2);
print('-dpng', ['../html/' fileName])
set(gcf, 'paperposition', origpos);

figure
clf
ax = axes('position', [0.05 0.05 0.9 0.9]);
hold on
if ~isempty(lbls)
  lvmTwoDPlot(model.X, lbls, getSymbols(size(lbls, 2)));
else
  lvmTwoDPlot(model.X, lbls);
end
xLim = [min(model.X(:, 1)) max(model.X(:, 1))]*1.1;
yLim = [min(model.X(:, 2)) max(model.X(:, 2))]*1.1;
set(ax, 'xLim', xLim);
set(ax, 'yLim', yLim);

set(ax, 'fontname', 'arial');
set(ax, 'fontsize', 20);
print('-depsc', ['../tex/diagrams/' fileName 'NoGray'])
print('-deps', ['../tex/diagrams/' fileName 'NoGrayNoColour'])


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

%function [dat] = read_ricoh_data(filename, hdr, begsample, endsample, chanindx)
%
%% READ_RICOH_DATA reads continuous or averaged MEG data
%% generated by the RICOH MEG system and software,
%% and allows the data to be used in FieldTrip.
%%
%% Use as
%%   [dat] = read_ricoh_data(filename, hdr, begsample, endsample, chanindx)
%%
%% This is a wrapper function around the function getRData
%%
%% See also READ_RICOH_HEADER, READ_RICOH_EVENT

if ~ft_hastoolbox('ricoh_meg_reader')
    ft_error('cannot determine whether Ricoh toolbox is present');
end

hdr = hdr.orig; % use the original Ricoh header, not the FieldTrip header

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

handles = definehandles;

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

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

  % Unlike Yokogawa system, "AcqTypeEvokedRaw" is not supported for Ricoh system.

  otherwise
    ft_error('unknown data type');
end

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

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

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


% POP_LOADBCI - import a BCI2000 ascii file into EEGLAB
%
% Usage:
%   >> OUTEEG = pop_loadbci( filename, srate );
%
% Inputs:
%   filename       - file name
%   srate          - sampling rate
%
% Outputs:
%   OUTEEG         - EEGLAB data structure
%
% Author: Arnaud Delorme, CNL / Salk Institute, 9 July 2002
%
% See also: EEGLAB

% Copyright (C) 2002 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [EEG, command] = pop_loadbci(filename, srate);

    EEG = [];
    command = '';

    if nargin < 1
        % ask user
        [filename, filepath] = uigetfile('*.*', 'Choose a BCI file -- pop_loadbci');
        drawnow;
        if filename == 0 return; end
        filename = [filepath filename];
        promptstr    = { 'Sampling rate' };
        inistr       = { '256' };
        result       = inputdlg2( promptstr, 'Import BCI2000 data -- pop_loadbci()', 1,  inistr, 'pop_loadbci');
        if length(result) == 0 return; end
        srate   = eval( result{1} );
    end

    % import data
    % -----------
    EEG = eeg_emptyset;
    fprintf('Pop_loadbci: importing BCI file...\n');
    try
        % try to read as matlab
        % ---------------------
        bci = load( filename, '-mat');
        allfields = fieldnames(bci);
        allfields = setdiff_bc(allfields, 'signal');
        for index = 1:size(bci.signal,2)
            chanlabels{index} = [ 'C' int2str(index) ];
        end
        for index = 1:length(allfields)
            bci.signal(:,end+1) = getfield(bci, allfields{index});
        end
        EEG.chanlocs = struct('labels', { chanlabels{:} allfields{:} });
        EEG.data     = bci.signal';
        EEG.nbchan   = size(EEG.data, 1);
        EEG.pnts     = size(EEG.data, 2);
        EEG.trials   = 1;
        EEG.srate    = srate;
        EEG.comments = [ 'Original file: ' filename ];
        EEG = eeg_checkset(EEG);
        return;
    catch
        % get file names
        % --------------
        fields = loadtxt(filename, 'nlines', 1, 'verbose', 'off');
        if length(fields) > 300
            error('Not a BCI ASCII file');
        end

        % read data
        % ---------
        fid = fopen(filename, 'r');
        allcollumns = fgetl(fid);
        tmpdata = fscanf(fid, '%d', Inf);
        tmpdata = reshape(tmpdata, length(fields), length(tmpdata)/length(fields));

        EEG.data = tmpdata;
        EEG.chanlocs = struct('labels', fields);
        EEG.nbchan = size(EEG.data, 1);
        EEG.pnts   = size(EEG.data, 2);
        EEG.trials = 1;
        EEG.srate  = srate;
        EEG = eeg_checkset(EEG);
        return;

        % data channel range
        % ------------------
        indices = strmatch('ch', fields);

        bci = [];
        for index = setdiff_bc(1:length(fields), indices)
            bci = setfield(bci, fields{index}, tmpdata(index,:));
        end
        bci.signal = tmpdata(indices,:);
    end

    % ask for which event to import
    % -----------------------------
    geom = {[0.7 0.7 0.7]};
    uilist = { { 'style' 'text' 'string' 'State name' 'fontweight' 'bold' } ...
               { 'style' 'text' 'string' '    Import' 'fontweight' 'bold'  } ...
               { 'style' 'text' 'string' 'Type of'  'fontweight' 'bold' } };
    allfields = setdiff_bc(fieldnames(bci), 'signal');
    latencyfields = { '-----' };
    for index = 1:length(allfields)
        if ~isempty(findstr( lower(allfields{index}), 'time'))
            latencyfields{end+1} = allfields{index};
        end
    end
    for index = 1:length(allfields)
        geom   = { geom{:} [1.3 0.3 0.3 0.3 1] };
        uilist{end+1} = { 'style' 'text' 'string' allfields{index} };
        if ~isempty(findstr( lower(allfields{index}), 'time'))
            uilist{end+1} = { 'style' 'checkbox' 'value' 0 };
            uilist{end+1} = { };
            uilist{end+1} = { };
            uilist{end+1} = { };
        else
            uilist{end+1} = { 'style' 'checkbox' };
            uilist{end+1} = { };
            uilist{end+1} = { };
            uilist{end+1} = { 'style' 'listbox' 'string' strvcat(latencyfields) };
        end
    end
    geom   = { geom{:} [1] [0.08 1] };
    uilist{end+1} = { };
    uilist{end+1} = { 'style' 'checkbox' 'value' 0 };
    uilist{end+1} = { 'style' 'text' 'string' 'Attempt to adjust event latencies using sourcetime?' };

    result = inputgui( geom, uilist, 'pophelp(''pop_loadbci'')', 'Import BCI2000 data files - pop_loadbci()');
    if isempty(result), return; end

    % convert results to command line input
    % -------------------------------------
    listimport = {};
    count = 1;
    for index = 1:length(allfields)
        if ~isempty(findstr( lower(allfields{index}), 'time'))
            if result{count}, listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} }; end
            count = count+1;
        else
            if result{count}
                if result{count+1} ~= 1
                    listimport{end+1} = 'event'; listimport{end+1} = { allfields{index}  allfields{result{count+1}-1} };
                else
                    listimport{end+1} = 'event'; listimport{end+1} = { allfields{index} };
                end
            end
            count = count+2;
        end
    end
    if result{end}, adjust = 1; else adjust = 0; end

    % decode command line input
    % -------------------------
    count = 1;
    for index = 2:2:length(listimport)
        tmpindmatch = strmatch(listimport{index}{1}, allfields, 'exact');
        if ~isempty(tmpindmatch), indeximport(count) = tmpindmatch;
        else error(['State ''' listimport{index}{1} ''' not found']);
        end
        if length( listimport{index} ) > 1
            tmpindmatch = strmatch(listimport{index}{2}, allfields, 'exact');
            if ~isempty(tmpindmatch), corresp(count) = tmpindmatch;
            else error(['State ''' listimport{index}{2} ''' not found']);
            end
        else
            corresp(count) = 0;
        end
        count = count+1;
    end

    % find block size
    % ---------------
    tmpevent = find( diff(getfield(bci, 'SourceTime')) ~= 0);
    diffevent = tmpevent(2:end)-tmpevent(1:end-1);
    blocksize = unique_bc(diffevent);
    if length(blocksize) > 1, error('Error in determining block size');
    else                      fprintf('Blocksize: %d\n', blocksize);
    end

    % find types
    % ----------
    tmpcorresp      = find(corresp);
    indexcorresp    = corresp(tmpcorresp);
    indexcorrespval = indeximport(tmpcorresp);
    if length(tmpcorresp) ~= length(intersect(corresp, indeximport))
        disp('Warning: correspondence problem, some information will be lost');
    end

    % remove type from latency array
    % ------------------------------
    indeximport(tmpcorresp) = [];
    if adjust
        fprintf('Latency of event will be adjusted\n');
    else fprintf('WARNING: Latency of event will not be adjusted (latency uncertainty %2.1f ms)\n', ...
                 blocksize/srate*1000);
    end

	% process events
	% --------------
	fprintf('Pop_loadbci: importing events...\n');
	counte = 1; % event counter
	events(10000).latency = 0;
    indexsource =  strmatch('sourcetime', lower( allfields ), 'exact' );
    sourcetime  = getfield(bci, allfields{ indexsource });
	for index = 1:length(indeximport)
        tmpdata  = getfield(bci, allfields{indeximport(index)});
		tmpevent = find( diff(tmpdata) > 0);
		tmpevent = tmpevent+1;
        tmpcorresp = find(indexcorresp == indeximport(index));

		for tmpi = tmpevent'
            if ~isempty(tmpcorresp)
                events(counte).type = allfields{ indexcorrespval(tmpcorresp) };
            else
                events(counte).type = allfields{ indeximport(index) };
            end
            if adjust
                baselatency = sourcetime(tmpi); % note that this is the first bin a block
                realtmpi    = tmpi+blocksize;   % jump to the end of the block+1
                if curlatency < baselatency, curlatency = curlatency+65536; end; % in ms
                events(counte).latency = realtmpi+(curlatency-baselatency)/1000*srate;
                % (curlatency-baselatency)/1000*srate
                % there is still a potentially large error between baselatency <-> realtmpi
            else
                events(counte).latency = tmpi+(blocksize-1)/2;
            end
            counte = counte+1;
		end
	end;

	EEG.data = bci.signal';
	EEG.nbchan = size(EEG.data, 1);
	EEG.pnts   = size(EEG.data, 2);
	EEG.trials = 1;
	EEG.srate  = srate;
	EEG = eeg_checkset(EEG);
	EEG.event = events(1:counte-1);
	EEG = eeg_checkset( EEG, 'eventconsistency' );
	EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } );

% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$ dsffd
% $$$
% $$$ 	% find electrode indices
% $$$ 	% ----------------------
% $$$ 	indices = [];
% $$$ 	for index = 1:length(colnames)
% $$$ 		if strcmp( colnames{index}(1:2), 'ch')
% $$$ 			indices = [indices index ];
% $$$ 		end
% $$$ 	end
% $$$
% $$$     EEG.data = tmpdata(indices,:);
% $$$     EEG.nbchan = size(EEG.data, 1);
% $$$     EEG.srate  = srate;
% $$$     try
% $$$         eventindices = setdiff_bc(1:length(colnames), indices);
% $$$         ISIind = eventindices(3 + 9);
% $$$         eventindices(3 + [ 1 2 3 4 7 8 9 10 11 12]) = [];
% $$$         eventindices(1:3) = []; % suppress these event
% $$$
% $$$         % add the trial number
% $$$         % --------------------
% $$$         tmptrial = find( diff(tmpdata(ISIind, :)) ~= 0);
% $$$         tmptrial = tmptrial+1;
% $$$
% $$$         % process events
% $$$         % --------------
% $$$         fprintf('Pop_loadbci: importing events...\n');
% $$$         counte = 1; % event counter
% $$$         events(10000).latency = 0;
% $$$         for index = eventindices
% $$$             counttrial = 1;
% $$$             tmpevent = find( diff(tmpdata(index, :)) ~= 0);
% $$$             tmpevent = tmpevent+1;
% $$$             for tmpi = tmpevent
% $$$                 if tmpdata(index, tmpi)
% $$$                     events(counte).type    = [ colnames{index} int2str(tmpdata(index, tmpi)) ];
% $$$                     events(counte).latency = tmpi;
% $$$                     %events(counte).value   = tmpdata(index, tmpi);
% $$$                     %while tmpi > tmptrial(counttrial) & counttrial < length(tmptrial)
% $$$                     %	counttrial = counttrial+1;
% $$$                     %end
% $$$                     %events(counte).trial = counttrial;
% $$$                     counte = counte+1;
% $$$                     %if mod(counte, 100) == 0, fprintf('%d ', counte); end
% $$$                 end
% $$$             end
% $$$         end
% $$$
% $$$         % add up or down events
% $$$         % ---------------------
% $$$         EEG = eeg_checkset(EEG);
% $$$         EEG.event = events(1:counte-1);
% $$$         EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } );
% $$$         for index=1:length(EEG.event)
% $$$             if strcmp(EEG.event(index).type(1:6), 'Target')
% $$$                 targetcode = str2num(EEG.event(index).type(end));
% $$$                 if targetcode == 1
% $$$                     EEG.event(index).type = 'toptarget';
% $$$                 else
% $$$                     EEG.event(index).type = 'bottomtarget';
% $$$                 end
% $$$             else
% $$$                 if strcmp(EEG.event(index).type(1:6), 'Result')
% $$$                     resultcode = str2num(EEG.event(index).type(end));
% $$$                     if resultcode == 1
% $$$                         EEG.event(index).type = 'topresp';
% $$$                     else
% $$$                         EEG.event(index).type = 'bottomresp';
% $$$                     end
% $$$                     EEG.event(end+1).latency = EEG.event(index).latency;
% $$$                     if (resultcode == targetcode)
% $$$                         EEG.event(end).type = 'correct';
% $$$                     else
% $$$                         EEG.event(end).type = 'miss';
% $$$                     end
% $$$                 end
% $$$             end
% $$$         end
% $$$         EEG = pop_editeventvals( EEG, 'sort', { 'latency', [0] } );
% $$$         %EEG.data = tmpdata([72 73 75],:);
% $$$     catch, disp('Failed to import data events');
% $$$     end
% $$$
% $$$ command = sprintf('EEG = pop_loadbci(''%s'', %f);',filename, srate);
% $$$ return;


%kvnthick 'N-1 Compositions of Thickenings'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros vnthick.pane file
%
% Parameters:
% InputFile: i 'Input Image ', required: 'input image'
% InputFile: str1 'Struct Element 1', required: 'Structuring Element'
% InputFile: str2 'Struct Element 2', required: 'Structuring Element'
% Integer: n 'Number of Thickenings', default: 5: 'number of thickenings'
% MultiChoice: r 'Struct El. Rotation Step', default: 1: 'Rotation step'
%    Choices are:
%   1: '1 '
%   2: '2 '
%   3: '4 '
% OutputFile: o 'Output Image ', required: 'resulting output image'
%
% Example: o = kvnthick({i, str1, str2}, {'i','';'str1','';'str2','';'n',5;'r',1;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% vnthick - N-1 compositions of Thickenings
%
%  DESCRIPTION
% .I vnthick
% will do N successive thickenings of an image.
%
% The output image data type will be the same as that of the highest data type
% of the input image.
%
% Some useful pairs of structuring elements:
%
%                               0 0 0    1 1 1
%   Conditional Segmentation    0 1 0    0 0 0
%                               1 1 1    0 0 0
%
%                               0 0 0    1 0 0
%   Pseudo Convex Hull          0 1 1    1 0 0
%                               0 0 0    1 0 0
%
%                               1 0 0    0 0 0
%   Convex Hull                 1 0 0    0 1 0
%                               1 0 0    0 0 0
%
%                               0 0 0    1 1 1
%   Homotopic Pruning           0 1 0    1 0 1
%                               0 0 0    1 1 1
%
%
%
%  EXAMPLES
% vnthick -i feath.xv -str1 b1.str -str2 b2.str -n 5 -r 1 -o outimage.xv
%
% Will do 5 successive thickenings (vnthick) of the input image "feath.xv" by the structuring element b1.str and b2.str, rotating the struct. els. 1 step after each thinning. The resulting image will be written to  "outimage.xv".
%
%  "SEE ALSO"
% vcast1(1)
%
%  RESTRICTIONS
% .I vnthick
% can be defined for all data types supported by Khoros, but at the moment it has been implemented just for the bit and unsigned char types.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993-1997 Junior Barrera, Roberto Lotufo.  All rights reserved.
%

function varargout = kvnthick(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kvnthick(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'str1', '__input';'str2', '__input';'n', 5;'r', 1;'o', '__output'};
maxval={0,0,0,2,0,0};
minval={0,0,0,2,0,0};
istoggle=[0,0,0,0,0,0];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','InputFile','Integer','MultiChoice','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'vnthick"  '],Inputs,narglist);


% finputcheck() - check Matlab function {'key','value'} input argument pairs
%
% Usage: >> result = finputcheck( varargin, fieldlist );
%        >> [result varargin] = finputcheck( varargin, fieldlist, ...
%                                              callingfunc, mode, verbose );
% Input:
%   varargin  - Cell array 'varargin' argument from a function call using 'key',
%               'value' argument pairs. See Matlab function 'varargin'.
%               May also be a structure such as struct(varargin{:})
%   fieldlist - A 4-column cell array, one row per 'key'. The first
%               column contains the key string, the second its type(s),
%               the third the accepted value range, and the fourth the
%               default value.  Allowed types are 'boolean', 'integer',
%               'real', 'string', 'cell' or 'struct'.  For example,
%                       {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'}
%                       {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'}
%  callingfunc - Calling function name for error messages. {default: none}.
%  mode        - ['ignore'|'error'] ignore keywords that are either not specified
%                in the fieldlist cell array or generate an error.
%                {default: 'error'}.
%  verbose     - ['verbose', 'quiet'] print information. Default: 'verbose'.
%
% Outputs:
%   result     - If no error, structure with 'key' as fields and 'value' as
%                content. If error this output contain the string error.
%   varargin   - residual varagin containing unrecognized input arguments.
%                Requires mode 'ignore' above.
%
% Note: In case of error, a string is returned containing the error message
%       instead of a structure.
%
% Example (insert the following at the beginning of your function):
%	result = finputcheck(varargin, ...
%               { 'title'         'string'   []       ''; ...
%                 'percent'       'real'     [0 1]    1 ; ...
%                 'elecamp'       'integer'  [1:10]   [] });
%   if isstr(result)
%       error(result);
%   end
%
% Note:
%   The 'title' argument should be a string. {no default value}
%   The 'percent' argument should be a real number between 0 and 1. {default: 1}
%   The 'elecamp' argument should be an integer between 1 and 10 (inclusive).
%
%   Now 'g.title' will contain the title arg (if any, else the default ''), etc.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002

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

function [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose )

	if nargin < 2
		help finputcheck;
		return;
	end;
	if nargin < 3
		callfunc = '';
	else
		callfunc = [callfunc ' ' ];
	end;
    if nargin < 4
        mode = 'do not ignore';
    end;
    if nargin < 5
        verbose = 'verbose';
    end;
	NAME = 1;
	TYPE = 2;
	VALS = 3;
	DEF  = 4;
	SIZE = 5;

	varargnew = {};
	% create structure
	% ----------------
	if ~isempty(vararg)
        if isstruct(vararg)
            g = vararg;
        else
            for index=1:length(vararg)
                if iscell(vararg{index})
                    vararg{index} = {vararg{index}};
                end;
            end;
            try
                g = struct(vararg{:});
            catch
                vararg = removedup(vararg, verbose);
                try
                    g = struct(vararg{:});
                catch
                    g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return;
                end;
            end;
        end;
	else
		g = [];
	end;

	for index = 1:size(fieldlist,NAME)
		% check if present
		% ----------------
		if ~isfield(g, fieldlist{index, NAME})
			g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF});
		end;
		tmpval = getfield( g, {1}, fieldlist{index, NAME});

		% check type
		% ----------
        if ~iscell( fieldlist{index, TYPE} )
            res = fieldtest( fieldlist{index, NAME},  fieldlist{index, TYPE}, ...
                           fieldlist{index, VALS}, tmpval, callfunc );
            if isstr(res), g = res; return; end;
        else
            testres = 0;
            tmplist = fieldlist;
            for it = 1:length( fieldlist{index, TYPE} )
                if ~iscell(fieldlist{index, VALS})
                     res{it} = fieldtest(  fieldlist{index, NAME},  fieldlist{index, TYPE}{it}, ...
                                           fieldlist{index, VALS}, tmpval, callfunc );
                else res{it} = fieldtest(  fieldlist{index, NAME},  fieldlist{index, TYPE}{it}, ...
                                           fieldlist{index, VALS}{it}, tmpval, callfunc );
                end;
                if ~isstr(res{it}), testres = 1; end;
            end;
            if testres == 0,
                g = res{1};
                for tmpi = 2:length(res)
                    g = [ g 10 'or ' res{tmpi} ];
                end;
                return;
            end;
        end;
	end;

    % check if fields are defined
	% ---------------------------
	allfields = fieldnames(g);
	for index=1:length(allfields)
		if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact'))
			if ~strcmpi(mode, 'ignore')
				g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return;
			end;
			varargnew{end+1} = allfields{index};
			varargnew{end+1} = getfield(g, {1}, allfields{index});
		end;
	end;

function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc );
	NAME = 1;
	TYPE = 2;
	VALS = 3;
	DEF  = 4;
	SIZE = 5;
    g = [];

    switch fieldtype
     case { 'integer' 'real' 'boolean' 'float' },
      if ~isnumeric(tmpval) && ~islogical(tmpval)
          g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return;
      end;
      if strcmpi(fieldtype, 'boolean')
          if tmpval ~=0 && tmpval ~= 1
              g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return;
          end;
      else
          if strcmpi(fieldtype, 'integer')
              if ~isempty(fieldval)
                  if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ...
                          && (~ismember(tmpval, fieldval))
                      g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
                  end;
              end;
          else % real or float
              if ~isempty(fieldval) && ~isempty(tmpval)
                  if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2))
                      g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return;
                  end;
              end;
          end;
      end;

     case 'string'
      if ~isstr(tmpval)
          g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return;
      end;
      if ~isempty(fieldval)
          if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact'))
              g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
          end;
      end;

     case 'cell'
      if ~iscell(tmpval)
          g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return;
      end;

     case 'struct'
      if ~isstruct(tmpval)
          g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return;
      end;

     case 'function_handle'
      if ~isa(tmpval, 'function_handle')
          g = [ callfunc 'error: argument ''' fieldname ''' must be a function handle' ]; return;
      end;

     case '';
     otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]);
    end;

% remove duplicates in the list of parameters
% -------------------------------------------
function cella = removedup(cella, verbose)
% make sure if all the values passed to unique() are strings, if not, exist
%try
    [tmp indices] = unique_bc(cella(1:2:end));
    if length(tmp) ~= length(cella)/2
        myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n');
    end;
    cella = cella(sort(union(indices*2-1, indices*2)));
%catch
    % some elements of cella were not string
%    error('some ''key'' values are not string.');
%end;

function myfprintf(verbose, varargin)

if strcmpi(verbose, 'verbose')
    fprintf(varargin{:});
end;


function [X,Y,Width,Height,Lbl] = read_lay(layoutname);

% READ_LAY reads an electrode or gradiometer layout file
% Layout files are used for topoplotting and multiplotting.
%
% Use as
%   [X, Y, Width, Height, Lbl] = read_lay(layoutname)

% Copyright (C) 2003, Ole Jensen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% 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: read_lay.m 945 2010-04-21 17:41:20Z roboos $

if ~exist(layoutname, 'file')
  error(sprintf('could not open layout file: %s', layoutname));
end

% discard the channel number
[chNum,X,Y,Width,Height,Lbl] = textread(layoutname,'%f %f %f %f %f %q');


function [samples, E_hist, g_mean] = gpnddisimSampleHMC(model, display, iters, options);

% GPNDDISIMSAMPLEHMC Do HMC sampling for the GPNDDISIM model.
% FORMAT
% DESC performs HMC sampling for the Gaussian process single input
% motif model for a given number of iterations.
% ARG model : the model to be optimised.
% ARG display : whether or not to display while optimisation
% proceeds, set to 2 for the most verbose and 0 for the least
% verbose.
% ARG iters : number of samples to return.
% RETURN samples : the samples.
%
% SEEALSO : hmc, gpsimCreate, gpsimGradient, gpsimObjective
%
% COPYRIGHT : Neil D. Lawrence, 2006
%
% COPYRIGHT : Antti Honkela, 2007-2013
%
% COPYRIGHT : Jaakko Peltonen, 2011

% GPNDDISIM

if nargin < 3
  iters = 2000;
  if nargin < 2
    display = 1;
  end
end

[params,paramnames] = modelExtractParam(model);

if nargin < 4,
  options = hmcDefaultOptions;
end

if isfield(model, 'uniformPriors') && model.uniformPriors,
  options.iters = iters;
  bounds = gpnddisimExtractParamTransformSettings(model);
  bounds = cat(1, bounds{:})';
  [samples, E_hist, g_mean] = ...
      myhmc_bounded('modelObjective', params,  options, ...
		    'modelGradient', bounds, model);
else
  hmcopt = optOptions;
  if display
    hmcopt(1) = display;
    if length(params) <= 100
      hmcopt(9) = 1;
    end
  end

  % Momentum persistence
  hmcopt(5) = 1;

  % Leapfrog steps
  hmcopt(7) = options.tau;

  % hmcopt(18) = epsilon, step length
  hmcopt(18) = options.epsilon;

  % Number of samples to return
  hmcopt(14) = iters;

  samples = hmc('modelObjective', params,  hmcopt, ...
		'modelGradient', model);

  E_hist = [];
  g_mean = [];
end


% Copyright 2011 Zdenek Kalal
%
% This file is part of TLD.
%
% TLD is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% TLD is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with TLD.  If not, see <http://www.gnu.org/licenses/>.

function flag = bb_isin(bb,imsize)

flag = bb(1,:) >= 1 & ...
bb(2,:) >= 1 & ...
bb(3,:) <= imsize(2) & ...
bb(4,:) <= imsize(1);


function region_bb = get_region_bbox(regions, sp_bb)

for obj = 1:numel(regions)
   sub_bb = sp_bb(regions{obj},:);
   if(numel(sub_bb) > 0)
      region_bb(obj, :) = [min(sub_bb(:, 1)), min(sub_bb(:, 2)), max(sub_bb(:,3)), max(sub_bb(:, 4))];
   else
      region_bb(obj, :) = [-1 -1 -1 -1];
   end
end


function [res] = mne_add_coil_defs(chs,accuracy,templates)
%
% [res] = mne_add_coil_defs(chs,accuracy,coil_def_templates)
%
% Add transformed coil definitions to the channel info
%
% chs        - original channel definitions
% accuracy   - desired accuracy (0, 1, or 2, defaults to 1)
% templates  - coil definition templates
%              (defaults to $MNE_ROOT/setup/mne/coil_def.dat or $MNE_ROOT/share/mne/coil_def.dat)
%

%
%   Author : Matti Hamalainen, MGH Martinos Center
%   License : BSD 3-clause
%
%
%   Revision 1.8  2006/05/03 18:53:05  msh
%   Approaching Matlab 6.5 backward compatibility
%
%   Revision 1.7  2006/04/26 00:14:24  msh
%   Return empty structure from fiff_pick_channels evoked and fiff_pick_types_evoked if there is no match.
%   Accuracy checking was incorrect in mne_add_coil_defs
%
%   Revision 1.6  2006/04/24 00:07:24  msh
%   Fixed error in the computation of the surface-based coordinate system.
%
%   Revision 1.5  2006/04/23 15:29:40  msh
%   Added MGH to the copyright
%
%   Revision 1.4  2006/04/21 17:31:07  msh
%   Added the examples.
%   Modified the formatting of some informative output.
%
%   Revision 1.3  2006/04/18 20:44:46  msh
%   Added reading of forward solution.
%   Use length instead of size when appropriate
%
%   Revision 1.2  2006/04/17 15:01:34  msh
%   More small improvements.
%
%   Revision 1.1  2006/04/17 11:52:15  msh
%   Added coil definition stuff
%
%
me='MNE:mne_add_coil_defs';

global FIFF;
if isempty(FIFF)
    FIFF = fiff_define_constants();
end

if nargin == 2 || nargin == 1 || isempty(templates)
    %
    %   We need the templates
    %
    try
        templates = mne_load_coil_def;
    catch
        error(me,'%s',mne_omit_first_line(lasterr));
    end
    if nargin == 1
        accuracy = 1;
    end
elseif nargin ~= 3
    error(me,'Incorrect number of arguments');
end

fprintf(1,'\t%d coil definition templates available\n',length(templates));

if accuracy ~= 0 && accuracy ~= 1 && accuracy ~= 2
    error(me,'Accuracy should attain one of the values 0, 1, 2');
end

res    = chs;
nchan  = length(chs);
ntemp  = length(templates);
nmeg   = 0;
neeg   = 0;
eeg_cm = zeros(1,3);

first = true;
for k = 2:nchan
    if chs(k).kind == FIFF.FIFFV_EEG_CH || chs(k).kind == FIFF.FIFFV_MEG_CH || ...
            chs(k).kind == FIFF.FIFFV_REF_MEG_CH
        if first
            coord_frame = chs(k).coord_frame;
            first = false;
        elseif chs(k).coord_frame ~= coord_frame
            error(me,'All coils and electrodes are not in the same coordinate system (%s)',chs(k).ch_name);
        end
    end
end

lower_half = hex2dec('FFFF');
for k = 1:nchan
    res(k).coil_def = [];
    if chs(k).kind == FIFF.FIFFV_EEG_CH && ~isempty(chs(k).eeg_loc)
        %
        %   Set up a "coil definition" for an EEG electrode
        %
        temp             = templates(1);             %   Just pick one
        temp.class       = 1000;                     %   EEG electrode class
        temp.id          = chs(k).coil_type;         %   Copy from the channel info
        temp.accuracy    = 1;                        %   Normal accuracy no matter what
        temp.num_points  = size(chs(k).eeg_loc,2);   %   Number of points is normally two
        temp.size        = 10e-3;                    %   Rather arbitrary
        temp.baseline    = 0;                        %   Baseline does not apply
        temp.description = 'EEG electrode';          %   Useful description
        temp.coildefs    = zeros(temp.num_points,7); %   Location data
        temp.coildefs(1,1)   = 1;                    %   The electrode location
        temp.coildefs(1,2:4) = chs(k).eeg_loc(:,1)';
        nn  = chs(k).eeg_loc(:,1);                   %   The normal definition is probably immaterial
        len = nn'*nn;
        if len > 0
            temp.coildefs(1,5:7) = nn';
        end
        if temp.num_points > 1                       %   Add the reference electrode
            temp.coildefs(2,1)   = -1;
            temp.coildefs(2,2:4) = chs(k).eeg_loc(:,2);
            nn  = chs(k).eeg_loc(:,2);
            len = nn'*nn;
            if len > 0
                temp.coildefs(2,5:7) = nn';
            end
        end
        temp.FV          = [];                            %   Empty for now
        eeg_cm           = eeg_cm + temp.coildefs(1,2:4); %   Accumulate center of mass
        res(k).coil_def  = temp;                          %   There it is
        neeg = neeg + 1;
    elseif chs(k).kind == FIFF.FIFFV_MEG_CH || chs(k).kind == FIFF.FIFFV_REF_MEG_CH
        %
        %   Set up an MEG coil definition
        %
        coil_type = bitand(double(chs(k).coil_type),lower_half);
        temp = [];
        for t = 1:ntemp
            if templates(t).id == coil_type && templates(t).accuracy == accuracy
                temp = templates(t);
                break;
            end
        end
        %
        %  Did we find the template?
        %
        if isempty(temp)
            error(me,'Could not find an MEG coil template (coil type = %d accuracy = %d) for channel %s', ...
                coil_type,accuracy,chs(k).ch_name);
        end
        %
        %  Transform the template using the coil transformation
        %
        np = size(temp.coildefs,1);
        %
        %  Transform the integration points and the normals
        %
        trans = chs(k).coil_trans(1:3,:);
        temp.coildefs(:,2:4) = (trans*[ temp.coildefs(:,2:4)' ; ones(1,np) ])';
        temp.coildefs(:,5:7) = (trans*[ temp.coildefs(:,5:7)' ; zeros(1,np) ])';
        %
        %  Transform the vertices
        %
        if ~isempty(temp.FV)
            nvert = size(temp.FV.vertices,1);
            temp.FV.vertices = (trans*[temp.FV.vertices' ; ones(1,nvert)])';
        end
        %
        %   Attach the coil definition to the result
        %
        res(k).coil_def = temp;
        nmeg = nmeg + 1;
    end
end
%
%     Create the EEG coils drawings now that we have the center of mass
%
if neeg > 0
    eeg_cm = eeg_cm/neeg;
    for k = 1:nchan
        if res(k).kind == FIFF.FIFFV_EEG_CH && ~isempty(res(k).eeg_loc)
            res(k).coil_def.FV = draw_electrode(res(k).coil_def,eeg_cm);
        end
    end
end

fprintf(1,'\t%d MEG coil definitions and %d EEG electrodes set up\n',nmeg,neeg);

return;

    function FV = draw_electrode(def,cm)

        % create a patch for an EEG electrode

        if def.class == 1000
            % round disk
            Radius  = def.size/2;           % radius
            Len_cir = 15;                   % number of points for circle
            r0      = def.coildefs(1,2:4);
            %
            %   Make a template circle
            %
            rr(1,:) = cos(2*pi*[0:Len_cir]/Len_cir);
            rr(2,:) = sin(2*pi*[0:Len_cir]/Len_cir);
            rr(3,:) = 0.0;
            rr(4,:) = ones(1,Len_cir+1);
            %
            %    Scaling
            %
            T1 = [ [ Radius 0 0 0 ] ; [ 0 Radius 0 0 ] ; [ 0 0 1 0 ...
                ] ; [  0 0 0 1 ] ];
            %
            %   Rotation (this is only approximately correct...)
            %
            %   The normal is parallel to the vector from CM to the electrode location
            %
            nn     = (def.coildefs(1,2:4) - cm)';
            sizenn = norm(nn);
            if sizenn > 0
                nn = nn/sizenn;
                [ u, s, v ]  = svd(eye(3,3) - nn*nn');
                if nn'*u(:,3) < 0
                    u = - u;
                end
                T2 = [ u [ 0 0 0 ]' ; [ 0 0 0 1 ]];
            else
                T2 = eye(4,4);
            end
            %
            %   Translation
            %
            T3 = [ [ 1 0 0 r0(1) ] ; [ 0 1 0 r0(2) ] ; [ 0 0 1 r0(3) ...
                ] ; [  0 0 0 1 ] ];
            %
            %    Transfrom the data and create the structure
            %
            rr = T3*T2*T1*rr;
            FV.vertices = [[rr(1,:)' rr(2,:)' rr(3,:)']];
            FV.faces    = [1:length(FV.vertices)];
        end
        return;
    end

end


% biosig2eeglabevent() - convert biosig events to EEGLAB event structure
%
% Usage:
%   >> eeglabevent = biosig2eeglabevent( biosigevent, interval )
%
% Inputs:
%   biosigevent    - BioSig event structure
%   interval       - Period to extract events for, in frames.
%                    Default [] is all.
%
% Outputs:
%   eeglabevent    - EEGLAB event structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2006-

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

function event = biosig2eeglabevent(EVENT, interval)

if nargin < 2
    interval = [];
end;

event = [];
disp('Importing data events...');

% If the interval variable is empty, import all events.
if isempty(interval)
    if isfield(EVENT, 'Teeg')
        event = EVENT.Teeg;
    end
    if isfield(EVENT, 'TYP')
        for index = 1:length( EVENT.TYP )
            event(index).type = EVENT.TYP(index);
        end
    end
    if isfield(EVENT, 'POS')
        for index = 1:length( EVENT.POS )
            event(index).latency = EVENT.POS(index);
        end
    end
    if isfield(EVENT, 'DUR')
        if any( [ EVENT.DUR ] )
            for index = 1:length( EVENT.DUR )
                event(index).duration = EVENT.DUR(index);
            end
        end
    end
    if isfield(EVENT, 'CHN')
        if any( [ EVENT.CHN ] )
            for index = 1:length( EVENT.CHN )
                event(index).chanindex = EVENT.CHN(index);
            end
        end
    end
% If a subinterval was specified, select only events that fall in that range, and
% edit duration field if it exceeds that range.
elseif isfield(EVENT,'POS')
    count = 1;
    for index = 1:length(EVENT.POS)
        pos_tmp = EVENT.POS(index) - interval(1) + 1;
        if pos_tmp > 0 & EVENT.POS(index) <= interval(2)
            event(count).latency = pos_tmp;
            if isfield(EVENT, 'TYP'), event(count).type = EVENT.TYP(index); end
            if isfield(EVENT, 'CHN'), event(count).chanindex = EVENT.CHN(index); end
            if isfield(EVENT, 'DUR')
                event(count).duration = min(EVENT.DUR(index), interval(2) - EVENT.POS(index));
            end
            count = count + 1;
        end
    end
end


% pop_specparams() - Set plotting and statistics parameters for computing
%                    STUDY component spectra.
% Usage:
%       >> STUDY = pop_specparams(STUDY, 'key', 'val');
%
% Inputs:
%   STUDY        - EEGLAB STUDY set
%
% Plot options:
%   'topofreq'   - [real] Plot Spectrum scalp maps at one specific freq. (Hz).
%                  A frequency range [min max] may also be defined (the
%                  spectrum is then averaged over the interval) {default: []}
%   'freqrange'  - [min max] spectral frequency range (in Hz) to plot.
%                  {default: whole frequency range} .
%   'ylim'       - [mindB maxdB] spectral plotting limits in dB
%                  {default: from data}
%   'plotgroups' - ['together'|'apart'] 'together' -> plot subject groups
%                  on the same figure in different colors, else ('apart') on
%                  different figures {default: 'apart'}
%   'plotconditions' - ['together'|'apart'] 'together' -> plot conditions
%                  on the same figure in different colors, else ('apart')
%                  on different figures. Note: keywords 'plotgroups' and
%                  'plotconditions' cannot both be set to 'together'.
%                  {default: 'apart'}
%   'subtractsubjectmean' - ['on'|'off'] subtract individual subject mean
%                  from each spectrum before plotting and computing
%                  statistics. Default is 'off'.
%   'averagechan' - ['on'|'off'] average data channels when several are
%                  selected.
%
% See also: std_specplot()
%
% Authors: Arnaud Delorme, CERCO, CNRS, 2006-

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

function [ STUDY, com ] = pop_specparams(STUDY, varargin);

STUDY = default_params(STUDY);
TMPSTUDY = STUDY;
com = '';
if isempty(varargin)

    enablecond         = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off');
    enablegroup        = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off');
    detachplots        = fastif(strcmpi(STUDY.etc.specparams.detachplots,'on'), 1, 0);
    plotconditions     = fastif(strcmpi(STUDY.etc.specparams.plotconditions, 'together'), 1, 0);
    plotgroups         = fastif(strcmpi(STUDY.etc.specparams.plotgroups,'together'), 1, 0);
    submean            = fastif(strcmpi(STUDY.etc.specparams.subtractsubjectmean,'on'), 1, 0);
    radio_averagechan  = fastif(strcmpi(STUDY.etc.specparams.averagechan,'on'), 1, 0);
    radio_scalptopo    = fastif(isempty(STUDY.etc.specparams.topofreq), 0, 1);
    if radio_scalptopo, radio_averagechan = 0; end;
    if radio_scalptopo+radio_averagechan == 0, radio_scalparray = 1; else radio_scalparray = 0; end;

    cb_radio = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ...
                 'set(gcbo, ''value'', 1);' ...
                 'set(findobj(gcbf, ''tag'', ''topofreq''), ''string'', '''');' ];
    cb_edit  = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ...
                 'set(findobj(gcbf, ''tag'', ''scalptopotext''), ''value'', 1);' ];

    uilist = { ...
           {'style' 'text'       'string' 'Spectrum plotting options' 'fontweight' 'bold' 'fontsize', 12} ...
        {} {'style' 'text'       'string' 'Frequency [low_Hz high_Hz]' } ...
           {'style' 'edit'       'string' num2str(STUDY.etc.specparams.freqrange) 'tag' 'freqrange' } ...
        {} {'style' 'text'       'string' 'Plot limits [low high]'} ...
           {'style' 'edit'       'string' num2str(STUDY.etc.specparams.ylim) 'tag' 'ylim' } ...
        {} {'style' 'checkbox'   'string' 'Subtract individual subject mean spectrum' 'value' submean 'tag' 'submean' } ...
        {} ...
           {'style' 'text'       'string' 'Spectrum plotting format' 'fontweight' 'bold' 'fontsize', 12} ...
        {} {'style' 'checkbox'   'string' 'Plot first variable on the same panel' 'value' plotconditions 'enable' enablecond  'tag' 'plotconditions' } ...
        {} {'style' 'checkbox'   'string' 'Plot second variable on the same panel' 'value' plotgroups 'enable' enablegroup 'tag' 'plotgroups' } ...
        {} {'style' 'checkbox'   'string' 'Detach plots' 'value' detachplots 'enable' 'on' 'tag' 'detachtag' } ...
        {} ...
           {'style' 'text'       'string' 'Multiple channels selection' 'fontweight' 'bold' 'fontsize', 12} ...
        {} {'style' 'radio'      'string' 'Plot channels in scalp array'    'value' radio_scalparray 'tag' 'scalparray'       'userdata' 'radio' 'callback' cb_radio} { } ...
        {} {'style' 'radio'      'string'  'Plot topography at freq. (Hz)' 'value' radio_scalptopo  'tag' 'scalptopotext' 'userdata' 'radio' 'callback' cb_radio} ...
           {'style' 'edit'       'string' num2str(STUDY.etc.specparams.topofreq) 'tag' 'topofreq' 'callback' cb_edit } ...
        {} {'style' 'radio'      'string' 'Average selected channels' 'value' radio_averagechan 'tag' 'averagechan' 'userdata' 'radio' 'callback' cb_radio} { } };
    cbline = [0.07 1.1];
    otherline = [ 0.07 0.6 .3];
    chanline  = [ 0.07 0.8 0.3];
    geometry = { 1 otherline otherline cbline 1 1 cbline cbline cbline 1 1 chanline chanline chanline };
    geomvert = [1.2 1 1 1 0.5 1.2 1 1 1 0.5 1.2 1 1 1 ];

    % component plotting
    % ------------------
    if isnan(STUDY.etc.specparams.topofreq)
        geometry(end-4:end) = [];
        geomvert(end-4:end) = [];
        uilist(end-10:end) = [];
    end;

    [out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, 'geomvert', geomvert, ...
                                            'title', 'Spectrum plotting options -- pop_specparams()');
    if isempty(res), return; end;

    % decode inputs
    % -------------
    %if res.plotgroups & res.plotconditions, warndlg2('Both conditions and group cannot be plotted on the same panel'); return; end;
    if res.submean   , res.submean    = 'on'; else res.submean    = 'off'; end;
    if res.plotgroups, res.plotgroups = 'together'; else res.plotgroups = 'apart'; end;
    if res.plotconditions , res.plotconditions  = 'together'; else res.plotconditions  = 'apart'; end;
    if res.detachtag, res.detachtag = 'on'; else res.detachtag = 'off'; end;
    if ~isfield(res, 'topofreq'), res.topofreq = STUDY.etc.specparams.topofreq;
    else res.topofreq  = str2num( res.topofreq );
    end;
    if ~isfield(res, 'averagechan'), res.averagechan = STUDY.etc.specparams.averagechan;
    elseif res.averagechan, res.averagechan = 'on'; else res.averagechan = 'off';
    end;
    res.freqrange = str2num( res.freqrange );
    res.ylim      = str2num( res.ylim );

    % build command call
    % ------------------
    options = {};
    if ~strcmpi( res.plotgroups, STUDY.etc.specparams.plotgroups), options = { options{:} 'plotgroups' res.plotgroups }; end;
    if ~strcmpi( res.plotconditions , STUDY.etc.specparams.plotconditions ), options = { options{:} 'plotconditions'  res.plotconditions  }; end;
    if ~strcmpi( res.detachtag, STUDY.etc.specparams.detachplots), options = { options{:} 'detachplots' res.detachtag}; end;
    if ~strcmpi( res.submean   , STUDY.etc.specparams.subtractsubjectmean ), options = { options{:} 'subtractsubjectmean'  res.submean  }; end;
    if ~isequal(res.topofreq, STUDY.etc.specparams.topofreq),       options = { options{:} 'topofreq' res.topofreq }; end;
    if ~isequal(res.ylim, STUDY.etc.specparams.ylim),               options = { options{:} 'ylim' res.ylim      }; end;
    if ~isequal(res.freqrange, STUDY.etc.specparams.freqrange),     options = { options{:} 'freqrange' res.freqrange }; end;
    if ~isequal(res.averagechan, STUDY.etc.specparams.averagechan), options = { options{:} 'averagechan' res.averagechan }; end;
    if ~isempty(options)
        STUDY = pop_specparams(STUDY, options{:});
        com = sprintf('STUDY = pop_specparams(STUDY, %s);', vararg2str( options ));
    end;
else

    if strcmpi(varargin{1}, 'default')
        STUDY = default_params(STUDY);
    else
        for index = 1:2:length(varargin)
            if ~isempty(strmatch(varargin{index}, fieldnames(STUDY.etc.specparams), 'exact'))
                STUDY.etc.specparams = setfield(STUDY.etc.specparams, varargin{index}, varargin{index+1});
            end;
        end;
    end;
end;

% scan clusters and channels to remove specdata info if freqrange has changed
% ----------------------------------------------------------
if ~isequal(STUDY.etc.specparams.freqrange, TMPSTUDY.etc.specparams.freqrange) | ...
    ~isequal(STUDY.etc.specparams.subtractsubjectmean, TMPSTUDY.etc.specparams.subtractsubjectmean)
    rmfields = { 'specdata' 'specfreqs' };
    for iField = 1:length(rmfields)
        if isfield(STUDY.cluster, rmfields{iField})
            STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField});
        end;
        if isfield(STUDY.changrp, rmfields{iField})
            STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField});
        end;
    end;
end;

function STUDY = default_params(STUDY)
    if ~isfield(STUDY.etc, 'specparams'), STUDY.etc.specparams = []; end;
    if ~isfield(STUDY.etc.specparams, 'topofreq'),             STUDY.etc.specparams.topofreq = []; end;
    if ~isfield(STUDY.etc.specparams, 'freqrange'),            STUDY.etc.specparams.freqrange = []; end;
    if ~isfield(STUDY.etc.specparams, 'ylim'     ),            STUDY.etc.specparams.ylim      = []; end;
    if ~isfield(STUDY.etc.specparams, 'subtractsubjectmean' ), STUDY.etc.specparams.subtractsubjectmean  = 'off'; end;
    if ~isfield(STUDY.etc.specparams, 'plotgroups'),           STUDY.etc.specparams.plotgroups = 'apart'; end;
    if ~isfield(STUDY.etc.specparams, 'plotconditions'),       STUDY.etc.specparams.plotconditions  = 'apart'; end;
    if ~isfield(STUDY.etc.specparams, 'averagechan') ,         STUDY.etc.specparams.averagechan  = 'off'; end;
    if ~isfield(STUDY.etc.specparams, 'detachplots') ,         STUDY.etc.specparams.detachplots  = 'on'; end;


function x = RecoverNonlinearSolversolution(model,xout);

if isempty(model.nonlinearindicies)
    x = xout(:);
else
    x = zeros(length(model.c),1);
    for i = 1:length(model.linearindicies)
        x(model.linearindicies(i)) = xout(i);
    end
    x = x(1:length(model.c));
end


function matVer = getMLVersion
%"MLVersion"
%   Returns the numeric version of Matlab currently running.  Uses the first
%   3 digits of the Version field returned from ver('matlab').
%
%JRA 11/15/04
%
%Usage:
%   version = MLVersion
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

verOutput = ver('MATLAB');
if isempty(verOutput)
    verOutput(1).Version = '';
end
verString = verOutput.Version;
matVer = str2num(verString);

% dotInd = strfind(verString, '.');
% startInd = [1 dotInd+1];
% endInd = [dotInd - 1 length(verString)];
% for i = 1:length(startInd)
%     versionCell{i} = str2num(verString(startInd(i):endInd(i)));
% end
%
% if length(versionCell) == 2
%     matVer = str2num([num2str(versionCell{1}),num2str(versionCell{2})]);
% elseif length(versionCell) == 3
%     matVer = str2num([num2str(versionCell{1}),num2str(versionCell{2}),'.',num2str(versionCell{3})]);
% end

% verOutput = ver('MATLAB');
% verString = verOutput.Version;
%
% matVer = str2num(verString);

% dotInd = strfind(verString, '.');
% startInd = [1 dotInd+1];
% endInd = [dotInd - 1 length(verString)];
%
% for i = 1:length(startInd)
%     versionCell{i} = str2num(verString(startInd(i):endInd(i)));
% end
%
% if length(versionCell) > 1
%     version = versionCell{1} + versionCell{2}*1/(10^length(versionCell{2}));
% else
%     version = versionCell{1};
% end


function M=json2mat(J)

%JSON2MAT converts a javscript data object (JSON) into a Matlab structure
%         using s recursive approach. J can also be a file name.
%
%Example: lala=json2mat('{lele:2,lili:4,lolo:[1,2,{lulu:5,bubu:[[1,2],[3,4],[5,6]]}]}')
%         notice lala.lolo{3}.bubu is read as a 2D matrix.
%
% Jonas Almeida, March 2010

if exist(J)==2 % if J is a filename
    fid=fopen(J,'r');
    J='';
    while ~feof(fid)
        J=[J,fgetl(fid)];
    end
    fclose(fid);
    M=json2mat(J);
else
    J1=regexprep(J(1:min([5,length(J)])),'\s',''); %despaced start of J string
    if J1(1)=='{' %extract structures
        JJ=regexp(J,'\{(.*)\}','tokens');
        M=extract_struct(JJ{1}{1});
    elseif J1(1)=='[' %extract cells
        JJ=regexp(J,'\[(.*)\]','tokens');
        M=extract_cell(JJ{1}{1});
    elseif J1(1)=='"' %literal string
        JJ=regexp(J,'\"(.*)\"','tokens');
        M=JJ{1}{1};
    else %numeric value
        M=str2num(J); % is number
    end
end

function y=extract_struct(x)
%detag arrays first
indOC=extract_embed(x,'[',']');
n=size(indOC,1);
for i=n:-1:1
    tag{i}=json2mat(x(indOC(i,1):indOC(i,2)));
    x=[x(1:indOC(i,1)-1),'tag{',num2str(i),'}',x(indOC(i,2)+1:end)];
end

a=regexp(x,'[^:,]+:[^,]+');
n=length(a);
a=[a,length(x)+2];
for i=1:n
    s=x(a(i):a(i+1)-2);
    t=regexp(s,'([^:]+):(.+)','tokens');
    %t{1}{1}(t{1}{1}==32)=[]; % remove blanks, maybe later do something fancier like replace with underscores
    t{1}{1}=strrep(t{1}{1},' ','_');
    t{1}{1}=strrep(t{1}{1},'"','');
    if t{1}{1}(1)=='_' %JSON allows for fieldnames starting with "_"
        t{1}{1}(1)=''; % this line will cause hard to track problems if the same object has 2 attributes with the same name but one of them starting with "_"
    end
    if regexp(t{1}{2},'tag{\d+}')
        y.(t{1}{1})=eval(t{1}{2});
    else
        y.(t{1}{1})=json2mat(t{1}{2});
    end
    %y.(t{1}{1})=json2mat(t{1}{2});
end

function y=extract_cell(x)

indOC=extract_embed(x,'{','}');
n=size(indOC,1);
for i=n:-1:1
    tag{i}=json2mat(x(indOC(i,1):indOC(i,2)));
    x=[x(1:indOC(i,1)-1),'tag~<',num2str(i),'>~',x(indOC(i,2)+1:end)];
end
indOC=extract_embed(x,'[',']');
m=size(indOC,1);
for j=m:-1:1
    i=n+j;
    tag{i}=json2mat(x(indOC(i,1):indOC(i,2)));
    try;tag{i}=cell2mat(tag{i});end
    x=[x(1:indOC(i,1)-1),'tag{',num2str(i),'}',x(indOC(i,2)+1:end)];
end
x=strrep(x,'~<','{');
x=strrep(x,'>~','}');
if exist('tag') %catching numeric content
    if isnumeric([tag{:}])
        try
            y=eval(['[',strrep(x,'},','};'),']']);
        end
    end
end

if exist('y')~=1
    y=eval(['{',strrep(x,'"',''''),'}']);
end

%look for embeded objects and arrays

function y=extract_embed(x,tagOpen,tagClose)

%EXTRACT_EMBED identifies embeded tagged segments
%Example y=extract_embed(str,'[',']')

indOpen=strfind(x,tagOpen)';
indOpen=[indOpen,ones(length(indOpen),1)];
indClose=strfind(x,tagClose)';
indClose=[indClose,-ones(length(indClose),1)];
indOpenClose=[indOpen;indClose];
[~,Ind]=sort(indOpenClose(:,1));
indOpenClose=indOpenClose(Ind,:);
n=size(indOpenClose,1);
for i=2:n % add one for open, take one for close
    indOpenClose(i,2)=indOpenClose(i-1,2)+indOpenClose(i,2);
end
i=0;
op=0; %open
while i<n
    i=i+1;
    if (indOpenClose(i,2)==1)*(op==0)
        op=1;
    elseif indOpenClose(i,2)==0
        op=0;
    else
        indOpenClose(i,2)=-1;
    end
end
if isempty(indOpenClose)
    y=[];
else
    indOpenClose(indOpenClose(:,2)<0,:)=[];
    y=[indOpenClose(1:2:end,1),indOpenClose(2:2:end,1)];% Open/Close Indexes
end


% Script for testing the string array feature of SOFA

%% Test Strings as application-specific variable
% Load some arbritrary HRTFs
hrtf = SOFAload(fullfile(SOFAdbPath, 'database','ari','dtf_nh2.sofa'));
% Add a string array
str={};
for ii=1:hrtf.API.M
  str{ii,1}=['String' num2str(round(rand(1,1)*10000))];
end
% SOFAaddVariable(Obj,Name,Dim,Value)
hrtf2 = SOFAaddVariable(hrtf,'Test','MS',str);
% Save as SOFA
SOFAsave('stringtest_applicationvar.sofa',hrtf2);
% Reload the file
hrtf = SOFAload('stringtest_applicationvar.sofa');
% compare the strings
if prod(strcmp(hrtf.Test,hrtf2.Test))
    disp('SimpleFreeFieldHRIR: String Load-Reload: OK');
    delete('stringtest_applicationvar.sofa');
else
    error('String comparison showed differences');
end
clear all

%% Test with conventions GeneralString
% Create an empty object
Obj = SOFAgetConventions('GeneralString');
% Create numeric data with M=15, R=2, N=10
Obj.Data.Double=rand(15,2,10);
% Create string arrays
str2={}; str={};
for ii=1:15
  id = num2str(round(rand(1,1)*1000000));
  str{ii,1}=['X' id];
  str2{ii,1}=['Left' id];
  str2{ii,2}=['Right' id];
end
Obj.String2 = str2;      % String1=[MRS]
Obj.Data.String1 = str;  % Data.String1=[MS]
Obj.Data.String2 = str2; % Data.String2=[MRS]
% Add a new string with dimensions [RS]
strn={'left ear'; 'right ear'};
Obj = SOFAaddVariable(Obj, 'Ears', 'RS', strn);
% Update dimensions
Obj = SOFAupdateDimensions(Obj);
% Save as SOFA
SOFAsave('stringtest_generalstring.sofa',Obj);
% Reload the file
Obj2 = SOFAload('stringtest_generalstring.sofa');
% Compare the strings
if ~prod(strcmp(Obj2.Data.String2,Obj.Data.String2))
    error('Data.String2: Comparison showed differences');
end
if ~prod(strcmp(Obj2.String2,Obj.String2))
    error('String2: Comparison showed differences');
end
if ~prod(strcmp(Obj2.Data.String1,Obj.Data.String1))
    error('Data.String1: Comparison showed differences');
end
if ~prod(strcmp(Obj2.Ears,Obj.Ears))
    error('Ears: Comparison showed differences');
end
disp('GeneralString: String1, String2, Data, Ears: Load-Reload: OK');
clear all
delete('stringtest_generalstring.sofa');


function assertNotEqual(a, b, message)
% assert that two inputs are not equal
%
% assertNotEqual(a,b,[msg])
%
% Inputs:
%   a           first input  } of any
%   b           second input } type
%   msg             optional custom message
%
% Raises:
%   'assertNotEqual:equal'                a and b are equal, and are either
%                                         both sparse or both not sparse
%
% Examples:
%   assertNotEqual('foo','bar');
%   %|| % passes without output
%
%   assertNotEqual(1,sparse(1));
%   %|| % passes without output
%
%   assertNotEqual('foo','foo');
%   %|| error('elements are equal');
%
% Notes:
%   - If a custom message is provided, then any error message is prefixed
%     by this custom message
%   - In this function, NaN values are considered equal.
%   - This function attempts to show similar behaviour as in
%     Steve Eddins' MATLAB xUnit Test Framework (2009-2012)
%     URL: http://www.mathworks.com/matlabcentral/fileexchange/
%                           22846-matlab-xunit-test-framework
%

    % Note: although it may seem more logical to compare class before size,
    % for compatibility reasons the order of tests matches that of the
    % MATLAB xUnit framework

    if isequaln_wrapper(a,b) && issparse(a)==issparse(b)
        whatswrong='inputs are equal';
        error_id='assertNotEqual:equal';

    else
        % elements are equal
        return;
    end

    if nargin<3
        message='';
    end

    full_message=moxunit_util_input2str(message,whatswrong,a,b);

    if moxunit_util_platform_is_octave()
        error(error_id,'%s',full_message);
    else
        throwAsCaller(MException(error_id, '%s', full_message));
    end

function tf=isequaln_wrapper(a,b)
% wrapper to support old versions of Matlab
    persistent has_equaln;

    if isempty(has_equaln)
        has_equaln=~isempty(which('isequaln'));
    end

    if has_equaln
        tf=isequaln(a,b);
    else
        tf=isequalwithequalnans(a,b);
    end


function [y]=attachToolToFlange(t_kuka,ts)
%% About
% Attach the tool specified by the transform (ts) into the flange

%% Areguments
% t_kuka: TCP/IP comunication object
% ts: transform vector [x,y,z,a,b,c] of TCP to the flange of the robot
% x,y,z are in mm
% a,b,c are XYZ fixed rotation angles in radians

% Copyright: Mohammad SAFEEA, 2018

    if max(max(size(ts==6)))
    else
        y=false;
        return;
    end
%%
    theCommand=['TFtrans']; % instruction part
    for i=1:6
        st=num2str(ts(i));
        theCommand=[theCommand,'_',st];
    end
    fprintf(t_kuka, theCommand);
    message=fgets(t_kuka);
    [ret]=checkAcknowledgment(message);
    y=ret;
    if(y==false)
        % turn off the server
        disp('Could not attach the tool to the Robot');
        net_turnOffServer(t_kuka);
    end
end


function S = read_mclust_t(tfilelist)

% adapted from M-clust function LoadSpikes

%-------------------
% Check input type
%-------------------
if ~isa(tfilelist, 'cell')
   ft_error('LoadSpikes: tfilelist should be a cell-array.');
end

nFiles = length(tfilelist);

S = cell(nFiles, 1);
for iF = 1:nFiles
	tfn = tfilelist{iF};
	if ~isempty(tfn)
    try
 		  tfp = fopen_or_error(tfn, 'rb','b');
    catch err
			warning([ 'Could not open tfile ' tfn]);
      continue
		end

		ReadHeader(tfp);
		S{iF} = fread(tfp,inf,'uint64');
	  S{iF} = double(S{iF}*100);

		fclose(tfp);
	end 		% if tfn valid
end		% for all files
fprintf(2,'\n');


function dtiVisualizeClusterOfFibers(clusterID, clusterlabels, fg)
%Display a group of fibers from fg.
%dtiVisualizeClusterOfFibers(clusterID, clusterlabels, fg)
%e.g., dtiVisualizeClusterOfFibers(1, fg.subgroup, fg)
%clusterlabels is a vector denoting, for each fiber, which cluster the
%fiber belongs to.
%clusterID is which cluster we want to visualize.
%ER 11/2007
if length(clusterlabels)~=1
    clusterlabels=clusterlabels';
end

figure;
for fbindex = find(clusterlabels==clusterID)'
curve=fg.fibers{fbindex};

tubeplot(curve(1, :), curve(2, :), curve(3, :), 1);
hold on;
end
axis([ -80    80  -120    90   -60    90]); xlabel('L<->R'); ylabel('P<->A'); zlabel('I<->S'); grid on;


function removeNSxData(timestamps, filename)
%
%   removeNSxData(timestamps, filename)
%
%   This function removes chunks of data given in a 2-column timestamps
%   variable from a NSx file and then saves it as another NSx. This is
%   useful when removing useless data from the file to decrease the size of
%   the NSx file without modifying the file timestamps. The file size only
%   changes when the NSx file is compressed.
%
%   timestamps: This variable contains beginning and ending timestamps of
%               the data that need to be removed from the NSx file. The
%               format is:
%                          [BegTimeStamp1 EndTimeStamp1
%                           BegTimeStamp2 EndTimeStamp2
%                           BegTimeStamp3 EndTimeStamp3
%                                ...          ...
%                           BegTimeStampN EndTimeStampN]
%
%               The data in the NSx between the pairs of timestamps will be
%               removed and set to 0.
%               (REQUIRED)
%
%   filename:   The name of the NSx file to be used. This input is also
%               optional. In its absense, a dialog will open and will
%               prompt the user to select an NSx file.
%               (OPTIONAL)
%
%   Example:    removeNSxData([100,600; 1000,2000], 'c:\datafile\sampleNSx.ns5')
%
%               In the example above, the timestamps between 100:600 and
%               1000:2000 will be removed from the file sampleNSx.ns5 and
%               the resulting NSx will be saved in sampleNSx_chunked.ns5
%               file.
%
%   Kian Torab
%   ktorab@blackrockmicro.com
%   Blackrock Microsystems
%
%   Version 1.0.1.0

% Validating the timestamps variable
if ~exist('timestamps', 'var')
    disp('The variable timestamps is required.');
    return;
end

if size(timestamps, 2) ~= 2
    disp('The timestamps variable should be a Nx2 variable containing beginning timestamps in the first column and ending timestamps in the second column.');
    return;
end

if ~all(timestamps(:,1) < timestamps(:,2))
    disp('The timestamps in the first column (beginning) have to be smaller than the ones in the second column (ending).')
    return;
end

% Figuring out the filename, if not passed on to the function
if ~exist('filename', 'var')
	[fname, path] = getFile('*.*', 'Choose an NSx file...');
    filename = [path fname];
end

if exist(filename, 'file') ~= 2
    disp('The file does not exist.');
    return;
end

% Openning and reading the file
FID = fopen(filename, 'r', 'ieee-le');
readData = fread(FID, '*uint8');
FID = fclose(FID);

% Extracting some information from the NSx file
fileTypeID   = char(readData(1:8))';
headerBytes  = typecast(readData(11:14), 'uint32')+9;
samplingFreq = double(typecast(readData(291:294), 'uint32'))/...
               double(typecast(readData(287:290), 'uint32'));
channelCount = typecast(readData(311:314), 'uint32');

% Converting timestamps into uint16 (2 bytes per data point)
timestamps = timestamps*2;

% Removing given timestamps
for idx = 1:size(timestamps, 1)
    readData((timestamps(idx,1)-2)*channelCount+1+headerBytes:timestamps(idx,2)*channelCount+headerBytes) = NaN;
end

% Saving the chunked file
writeFilename = [filename(1:end-4) '_chunked', filename(end-3:end)];
FID = fopen(writeFilename, 'w+', 'ieee-le');
fwrite(FID, readData);
fclose(FID);


function str = parSimp(str)
%PARSIMP   Remove unnecessary parentheses from string inputs.
%   STROUT = PARSIMP(STRIN) returns the string STROUT, obtained by doing some
%   basic simplifications of the string STRIN, attempting to remove unnecessary
%   parenthesis, zeros, and consecutive +/- pairs.

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

% We can't really expect to simplify a one character string...
if ( length(str) < 2 )
    return
end

% Simplify until we can't simplify more!
oldlength = 0;
while ( length(str) ~= oldlength )
    oldlength = length(str);
    str = parSimpMain(str);
end

end

function str = parSimpMain(str)
%PARSIMMAIN   Do the actual simplification

% Find all locations of ( and ):
leftParLoc = strfind(str, '(');
rightParLoc = strfind(str, ')');

% Find weighted vector of operators:
opVec = (str == '-') + (str == '+') + 2*((str == '*') + (str == '/')) + ...
    3*(str == '^');

% Operator locations
opLoc = find(opVec);

% Location of characters and numbers
charLoc = regexp(str, '[A-Za-z0-9@]');
ltgtLoc = regexp(str, '[\<\>]');

% Error if the number of ( and ) are not equal
if ( length(leftParLoc) ~= length(rightParLoc) )
    error('CHEBFUN:STRINGPARSER:parSimp:parenthSimplify', ...
        'Incorrect number of parenthesis.');
end

% Store number of parenthesis
numOfPars = length(leftParLoc);
% Pair them together
pairsLoc = zeros(numOfPars, 2);
pairsVec = zeros(1, length(str));
parCounter = 1;
leftStack = [];
for strIndex = 1:length(str)
    if ( str(strIndex) == '(' ) % Push to the stack
        leftStack = [leftStack, strIndex]; %#ok<AGROW>
    elseif ( str(strIndex) == ')' ) % Pop from the stack
        % Write information to pairs
        pairsLoc(parCounter, 1) = leftStack(end);
        pairsLoc(parCounter, 2) = strIndex;
        pairsVec([leftStack(end) strIndex]) = parCounter;
        % Update stack and counter
        leftStack(end) = [];
        parCounter = parCounter + 1;
    end
end

for k = 1:numel(ltgtLoc)
    idx = find((pairsLoc(:, 1) < ltgtLoc(k)) & (pairsLoc(:, 2) > ltgtLoc(k)));
    [ignored, idx2] = max(pairsLoc(idx, 1));
    charLoc = sort([charLoc pairsLoc(idx(idx2), :)]);
    pairsLoc(idx(idx2),:) = [];
    numOfPars = numOfPars - 1;
end

leftParsLoc = pairsLoc(:, 1);
rightParsLoc = pairsLoc(:, 2);

    function removeExtras(varargin)
        % Remove things other than parentheses, like consecutive +/- pairs
        % and hanging zeros. If there's an input argument, then we don't
        % attempt to remove zeros.

        % Remove leading + signs
        if ( strcmp(str(1), '+') )
            str(1) = [];
            opVec(1) = [];
            leftParsLoc = leftParsLoc - 1;
            rightParsLoc = rightParsLoc - 1;
            opLoc = opLoc - 1;
            charLoc = charLoc - 1;
        end

        % Remove consecutive +/- pairs
        opVec1 = ( opVec == 1 );
        dOV = ~[abs(diff(opVec1)) 1] & opVec1; % Find adjacent opVec == 1's
        pm = find(dOV, 1); % Get the first
        if ( ~isempty(pm) ) % If +/- pair exists, remove the first occurence
            if ( str(pm) == str(pm+1) )
                str(pm) = '+';
            else
                str(pm) = '-';
            end
            str(pm + 1) = [];
            % Need to update indices and operators
            opVec(pm+1) = [];
            leftParsLoc(leftParsLoc > pm) = leftParsLoc(leftParsLoc > pm) - 1;
            rightParsLoc(rightParsLoc > pm) = ...
                rightParsLoc(rightParsLoc > pm) - 1;
            opLoc(opLoc > pm) = opLoc(opLoc > pm) - 1;
            charLoc(charLoc > pm) = charLoc(charLoc > pm) - 1;
            removeExtras(1) % recurse
        end

        % +/- pairs recurse locally
        if ( nargin > 0 )
            return
        end

    end

removeExtras()

% Loop over the pairs
for pIndex = 1:numOfPars

    removeExtras()

    pLeft = leftParsLoc(pIndex);
    pRight = rightParsLoc(pIndex);
    nextOpLeft = max(opLoc(opLoc < pLeft));
    nextOpRight = min(opLoc(opLoc > pRight));

    if ( nextOpLeft == 0 )
        nextOpLeft = [];
    end

    if ( nextOpRight == 0 )
        nextOpRight = [];
    end

    if ( any(charLoc == pLeft - 1) )
        % If the character in str next to the left of the left parenthesis is a
        % letter or a number (e.g. from sin or log2), we have a function from
        % which we cannot remove the () pair.
        continue
    end

    % Just mask the interior of these parentheses
    mask = zeros(1, length(str));
    mask(pLeft+1:pRight-1) = true;
    idx = find((leftParsLoc > pLeft) & (rightParsLoc < pRight));
    for k = 1:numel(idx)
        mask(leftParsLoc(idx(k)):rightParsLoc(idx(k))) = false;
    end
    interiorOpVec = opVec.*mask;
    interiorOpVec(interiorOpVec==0) = inf;
    minOpInside = min(interiorOpVec(pLeft:pRight));

    % If not, we perform a check to see whether we can remove them.
    if ( (isempty(nextOpLeft) || (minOpInside >= opVec(nextOpLeft))) && ...
            (isempty(nextOpRight) || minOpInside >= opVec(nextOpRight)) )

        if ( (minOpInside == 1) && ~isempty(nextOpLeft) && ...
                strcmp(str(pLeft - 1), '-') )
            % Deal with the case of minus (switch interior pluses and minuses
%            continue % uncomment if we don't want to simplify -(a+b) = -a-b
            interiorPM = interiorOpVec == 1;
            interiorPM(pLeft+1) = 0;
            m = (str == '-') & interiorPM;
            p = (str == '+') & interiorPM;
            % But we have to be careful that we don't change 1e-2 to 1e+2!
            mPos = find(m);
            pPos = find(p);
            mThrow = str(mPos-1) == 'e';
            pThrow = str(pPos-1) == 'e';
            m(mPos(mThrow)) = 0;
            p(pPos(pThrow)) = 0;
            str(m) = '+';
            str(p) = '-';
        end

        if ( (minOpInside == 2) && ~isempty(nextOpLeft) && ...
                strcmp(str(pLeft - 1), '/') )
            % Deal with division.  Unlike subtraction, we don't intend to
            % generally change a/(b/c) into a*c/b, so just move on.
            % (See GitHub issue #2357.)
            continue;
        end

        % Remove parenthesis pairs
        str(pLeft) = [];
        str(pRight-1) = [];

        % Update indices and operators
        opVec(pLeft) = [];
        opVec(pRight-1) = [];
        leftParsLoc(pIndex) = NaN;
        rightParsLoc(pIndex) = NaN;
        leftParsLoc = updateLoc(leftParsLoc, pLeft, pRight);
        rightParsLoc = updateLoc(rightParsLoc, pLeft, pRight);
        opLoc = updateLoc(opLoc, pLeft, pRight);
        charLoc = updateLoc(charLoc, pLeft, pRight);
    end

end

% Remove leading + signs
if ( strcmp(str(1), '+') )
    str(1) = [];
end

end

function out = updateLoc(in, pLeft, pRight)
out = in - (in > pLeft) - (in > pRight);
end


function test_issue1067

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY ft_prepare_layout ft_prepare_mesh ft_prepare_sourcemodel ft_prepare_headmodel ft_prepare_neighbours

% For some fields there are multiple ways to obtain them. The desired use in the
% high-level functions is to call the function that is the highest in the hierarchy.
%
% ft_prepare_xxx -> ft_fetch_xxx -> ft_read_xxx/loadvar

%%

cd(dccnpath('/home/common/matlab/fieldtrip/data/test/issue1067'));

%% layout

cfg = [];
cfg.layout = 'CTF151.lay';
cfg.layout = ft_prepare_layout(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.layout));
cfg.layout = ft_prepare_layout(cfg); % using FT_PREPARE_XXX again

cfg = [];
cfg.layout = 'CTF151.mat';
cfg.layout = ft_prepare_layout(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.layout));
cfg.layout = ft_prepare_layout(cfg); % using FT_PREPARE_XXX again

%% headshape

cfg = [];
cfg.headshape = 'Subject01.shape';
cfg.headshape = ft_prepare_mesh(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.headshape));
cfg.headshape = ft_prepare_mesh(cfg); % using FT_PREPARE_XXX again

cfg = [];
cfg.headshape = 'Subject01_headshape.mat';
cfg.headshape = ft_prepare_mesh(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.headshape));
cfg.headshape = ft_prepare_mesh(cfg); % using FT_PREPARE_XXX again

%% sourcemodel

cfg = [];
cfg.sourcemodel = 'Subject01_sourcemodel.mat';
cfg.sourcemodel = ft_prepare_sourcemodel(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.sourcemodel));
cfg.sourcemodel = ft_prepare_sourcemodel(cfg); % using FT_PREPARE_XXX again

%% headmodel

cfg = [];
cfg.headmodel = 'Subject01.hdm';
cfg.headmodel = ft_prepare_headmodel(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.headmodel));
cfg.headmodel = ft_prepare_headmodel(cfg); % using FT_PREPARE_XXX again

cfg = [];
cfg.headmodel = 'Subject01_headmodel.mat';
cfg.headmodel = ft_prepare_headmodel(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.headmodel));
cfg.headmodel = ft_prepare_headmodel(cfg); % using FT_PREPARE_XXX again

%% neighbours

cfg = [];
cfg.neighbours = 'ctf151_neighb.mat';
cfg.neighbours = ft_prepare_neighbours(cfg); % using FT_PREPARE_XXX
assert(isstruct(cfg.neighbours));
cfg.neighbours = ft_prepare_neighbours(cfg); % using FT_PREPARE_XXX again

%% grad

cfg = [];
cfg.grad = 'Subject01_grad.mat';
cfg.grad = ft_fetch_sens(cfg); % using FT_FETCH_XXX
assert(isstruct(cfg.grad));
cfg.grad = ft_fetch_sens(cfg); % using FT_FETCH_XXX again

%% elec

cfg = [];
cfg.elec = 'Subject01_elec.mat';
cfg.elec = ft_fetch_sens(cfg); % using FT_FETCH_XXX
assert(isstruct(cfg.elec));
cfg.elec = ft_fetch_sens(cfg); % using FT_FETCH_XXX again

%% opto

cfg = [];
cfg.opto = 'opto.mat';
cfg.opto = ft_fetch_sens(cfg); % using FT_FETCH_XXX
assert(isstruct(cfg.opto));
cfg.opto = ft_fetch_sens(cfg); % using FT_FETCH_XXX again

%% event

cfg = [];
cfg.event = 'Subject01_event.mat';
cfg.event = ft_read_event(cfg.event); % using FT_READ_XXX
assert(isstruct(cfg.event));

%% mri

cfg = [];
cfg.mri = 'Subject01.mri';
cfg.mri = ft_read_mri(cfg.mri);  % using FT_READ_XXX
assert(isstruct(cfg.mri));

cfg = [];
cfg.mri = 'Subject01_mri.mat';
cfg.mri = ft_read_mri(cfg.mri);  % using FT_READ_XXX
assert(isstruct(cfg.mri));


function mtrClusterResampleSISPathways(fgFilenames,samplerOptsFilename,numSamplesPerCluster,clusterROIFilename,dt6Filename,fgResampledFilename, hintNumTotalFibers, bCalcStats)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% mtrClusterResampleSISPathways(fgFilenames,samplerOptsFilename,
%%                                numSamplesPerCluster,clusterROI,
%%                                fgResampledFilename)
%%
%% fgFilenames - filenames for metrotrac pathways
%% samplerOptsFilename - parameters file for collecting paths and stats
%% numSamplesPerCluster - total weight of all resamples
%% clusterROIFilename - ROI where we will resample pathways around each coordinate
%%              of the ROI.
%% fgResampledFilename - filename for resampled pathways
%% dt6Filename - Filename for dt6.
%% hintNumTotalFibers - Number hopefully greater than the total number of
%% fibers that we will load.  This will speed up processing significantly
%% as it will allow us to preallocate space for validity matrix.
%% bCalcStats - True then calculate the statistics False then they already
%% exist.
%%
%%
%% Author: Anthony Sherbondy
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Constants
DISTANCE_THRESH = 2;

%% MUST MAKE SURE THIS PROGRAM IS COMPILED AND IN RIGHT LOCATION
if(ispc)
    executable = which('updatestats.exe');
else
    error('Not compiled for Linux.');
end

% Get all the needed files
if(ieNotDefined('dt6Filename'))
    [f, p] = uigetfile({'*.mat';'*.*'}, 'Load DT6 file...');
    if(isnumeric(f)), disp('Resampling canceled.'); return; end
    dt6Filename = fullfile(p,f);
end

dt6 = load(dt6Filename);

% Load ROI
roi = load(clusterROIFilename);
roi = roi.roi;

% Get importance weight file that we need to resample with also load the
% pathfile into matlab
totalFiberCount = 1;
fg_input = dtiNewFiberGroup;
fg_temp = dtiNewFiberGroup;

% Allocate validity map with hint of number of total fibers
if(ieNotDefined('hintNumTotalFibers'))
    hinNumTotalFibers = 50000;
end
validFiberToROIMap = logical(zeros(size(roi.coords,1),hintNumTotalFibers));

for ii = 1:length(fgFilenames)
     tic;
    statvec_names{ii} = sprintf('temp%d_statvec_iw.dat',ii);
    if(bCalcStats)
        disp('Calculating Statistics.');
        args = sprintf(' -v %s -i %s -o temp.dat -s 4 -sf %s', samplerOptsFilename, fgFilenames{ii}, statvec_names{ii});
        cmd = [executable args];
        disp(cmd); disp('...')
        [s, ret_info] = system(cmd,'-echo');
        disp('Done.')
    end

    disp('Loading pathway file into matlab...')
    fg_temp = mtrImportFibers(fgFilenames{ii}, dt6.xformToAcPc);
    disp('Done')

    % For all of the ROI points see which pathways are close enough
    disp('Finding closest ROI points for each path...')

    for ff = 1:length(fg_temp.fibers)
        [indices, bestSqDist] = nearpoints(roi.coords', fg_temp.fibers{ff});
        % Coordinates are in mm
        validFiberToROIMap(:,totalFiberCount) = bestSqDist < DISTANCE_THRESH;
        totalFiberCount = totalFiberCount+1;
    end
    disp('Done')

    % Keep aggregating all of the fibers together into one group
    if(isempty(fg_input.fibers))
        fg_input.fibers = fg_temp.fibers;
    else
        fg_input.fibers = {fg_input.fibers{:}, fg_temp.fibers{:}};
    end
     toc;
end
clear fg_temp;

% Send the valid matrix in with the resample computations
[fg_output, sample_w] = resampleClusterSISPathways(numSamplesPerCluster, statvec_names, fg_input, roi, validFiberToROIMap);

% Output the pathways in dtifiberUI space
dtiWriteFiberGroup(fg_output,fgResampledFilename);

% Output the pathways in metrotrac space
%mtrExportFiberGroupToMetrotrac(fgResampledFilename,fg_output,dt6.t1NormParams,dt6.mmPerVox,dt6.xformToAcPc,size(dt6.b0));

% Cleanup temp files
delete('temp.dat');

% Why should I delete these stats?? they are yummy!!
% for ii = 1:length(statvec_names)
%     delete(statvec_names{ii});
% end

return;

function [fg_output, sample_w_out] = resampleClusterSISPathways(numSamplesPerCluster, weightFilenames, fg_input, roi, validFiberToROIMap)

numFiles = length(weightFilenames);
sizeFiles = [];

% Setup the output file
fg_output = dtiNewFiberGroup;

% Load multiple importance weight files
iw = [];
for f = 1:numFiles
    iwtemp = mtrLoadStatvec(weightFilenames{f});
    iw = [iw; iwtemp];
    sizeFiles(f) = length(iwtemp);
end
% Give everything a small chance of sampling
iw = exp(iw)+realmin;

% For each ROI point lets resample from the database
for rr = 1:size(roi.coords,1)
    iwROI = validFiberToROIMap(rr,:) .* iw(:)';
    % If no fibers are near enough to this position forget about it
    if(sum(iwROI)>0)
        % Resample pathways according to normalized weight and whether they are
        % near this ROI point
        sample_ind = randsample([1:length(iwROI)],numSamplesPerCluster,true,iwROI);
        unique_sample_ind = unique(sample_ind);
        unique_sample_w = 0;
        for i = 1:length(unique_sample_ind)
            unique_sample_w(i) =  sum(sample_ind == unique_sample_ind(i));
        end
        % Add fibers sampled from this ROI to the output fiber group
        if(isempty(fg_output.fibers))
            fg_output.fibers = {fg_input.fibers{unique_sample_ind}};
            sample_w_out = unique_sample_w;
        else
            fg_output.fibers = {fg_output.fibers{:}, fg_input.fibers{unique_sample_ind}};
            sample_w_out = [sample_w_out, unique_sample_w];
        end
    else
    end
end

return;


% GPS Signal Capture Script
% This requires LeCroy's ActiveDSO Interface, available at http://www.lecroy.com
% No additional MathWorks products are required.
% The scope state has been setup via front panel controls:
% 50 MSPS rate, 48 M words record length, 0.1V/div, BWL 20 MHz
% and a single shot capture has been made.
% Copywrite 2002-2011 The Mathworks, Inc.
% Dick Benson
%% Create ActiveX Control to establish communication with scope
hDSO = actxcontrol('lecroy.activedsoctrl.1',[130 80 800 600]);
MakeConnection(hDSO,'TCPIP: 192.168.0.13'); % static IP set for this scope

%  inspect(hDSO)      %What do we know about it?
%  methodsview(hDSO)  %What can we do with it, and how?

% returns unsigned int8, need to remove offset, and recast to int8
y = int8(int16((GetByteWaveform(hDSO,'C1',48e6,0)))-128); % 48 million samples from channel 1
figure; plot(y(1:1e5)); % sanity check
Disconnect(hDSO);
clear hDSO
s=[6 10 30 21 2 29 5]; % satellites that should be in the data set
% save the capture
save GPS_long_3_X y s


function [out] = grayero(im,se)

if (~isa(se,'strel'))
    se=strel(se);
end
seq=getsequence(se);
lunghezza=size(seq,1);

out=gerod(im,getnhood(seq(1)),2);
for ii=2:lunghezza
    out=gerod(out,getnhood(seq(ii)),2);
end


% A helper function to check that all HOWTOs are working

HOWTO_spectra;
HOWTO_features;
HOWTO_sinusoidal;
HOWTO_egg;
HOWTO_glottalsource;
HOWTO_VAD;
HOWTO_envelope;
HOWTO_formant;
HOWTO_hmpd;
HOWTO_filterbanks;


classdef OptimizerToDesignVariableTranslator <  handle

    methods (Access = public, Static)

        function n = translate(optimizer)
            switch optimizer
                case {'SLERP', 'PROJECTED SLERP', 'HAMILTON-JACOBI'}
                    n = 'LevelSet';
                case {'PROJECTED GRADIENT', 'MMA', 'IPOPT'}
                    n = 'Density';
            end

        end

    end

end


function bool = checkFormulae(formulaA, formulaB, exceptions)
% Compares two formulae for the number of elements for all optionally except the
% elements listed in exceptions
%
% USAGE:
%
%    bool = checkFormulae(formulaA, formulaB, exceptions)
%
% INPUT:
%    formulaA:
%    formulaB:
%
% OPTIONAL INPUT:
%    exceptions:    String array of metabolite abbreviation exceptions e.g. {'H'}
%
% OUTPUT:
%    bool:          Boolean where 1 means the formulae match and 0 otherwise
%
% .. Author: - Ronan M. T. Fleming 20 July 2009

if ~exist('exceptions','var')
    exceptions={};
end

if ischar(exceptions)
    ex=exceptions;
    clear exceptions
    exceptions{1}=ex;
end

elements = {'C','H','O','P','S','K','Na','N'};

bool=1;
for n=1:length(elements)
    if ~any(strcmp(elements{n},exceptions))
        numA=numAtomsOfElementInFormula(formulaA,elements{n});
        numB=numAtomsOfElementInFormula(formulaB,elements{n});
        %check to see if number of elements is not the same for each
        %metabolite
        if numA~=numB
            bool=0;
            break;
        end
    end
end


function noiseWriteParamsToFID(noise, FID)

% NOISEWRITEPARAMSTOFID Write the noise parameters to a stream.
% FORMAT
% DESC writes noise parameters to  a file stream.
% ARG noise : the noise structure that is being written.
% ARG FID : the file ID of the stream that is being written.
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2008
%
% SEEALSO : noiseWriteToFID

% NOISE

writeIntToFID(FID, 'outputDim', noise.numProcess);
writeIntToFID(FID, 'numParams', noise.nParams);
if strcmp(noise.type, 'ncnm')
  writeIntToFID(FID, 'gammaSplit', noise.gammaSplit);
end
fhandle = str2func([noise.type 'NoiseExtractParam']);
params = fhandle(noise);
doubleMatrixWriteToFID(params, FID);


function region = p07_region ( )

%*****************************************************************************80
%
%% P07_REGION returns the name of the integration region for problem 07.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string REGION, the name of the integration region.
%
  region = 'box';

  return
end


function outmap = read_map(filename)
% Reads a map from a file.  The file must contain two columns with
% keys in the first column and values in the second column.
% Inputs:
%   filename: The name of the text file containing the map.
% Outputs:
%   outmap: A struct with a cell array of keys and a cell array of
%   values.  The cell arrays will be the same length and will
%   contain strings.

assert(isa(filename,'char'))

fid = fopen(filename,'r');
cc = textscan(fid,'%s%s');
fclose(fid);

outmap.keySet = cc{1};
outmap.values = cc{2};


function rgb = cortex_dark

% This returns a predefined color as [red green blue] values
%   red               = [255   0   0]/255;
%   green             = [  0 192   0]/255;
%   blue              = [  0   0 255]/255;
%   magenta           = [255 255   0]/255;
%   cyan              = [  0 255 255]/255;
%   yellow            = [255 255   0]/255;
%   white             = [255 255 255]/255;
%   black             = [  0   0   0]/255;
%
%   skull             = [140  85  85]/255
%   cortex            = [255 213 119]/255;
%   cortex_light      = [199 194 169]/255;
%   cortex_dark       = [100  97  85]/255;
%   skin              = [249 223 192]/255;
%   skin_light        = [249 223 192]/255;
%   skin_medium_light = [225 194 158]/255;
%   skin_medium       = [188 142 106]/255;
%   skin_medium_dark  = [155 102	65]/255;
%   skin_dark         = [ 91  71  61]/255;

rgb = [100 97 85]/255;