function o = niftistruc(fmt)
% Create a data structure describing NIFTI headers
%__________________________________________________________________________
% Copyright (C) 2005-2017 Wellcome Trust Centre for Neuroimaging

%
% $Id: niftistruc.m 7147 2017-08-03 14:07:01Z spm $

if ~nargin, fmt = 'nifti1'; end
switch lower(fmt)
    case {'nifti1','ni1','n+1'}
        o = nifti1struc;
    case {'nifti2','ni2','n+2'}
        o = nifti2struc;
    otherwise
        error('Unknown format.');
end


function r = uminus(c)

%tstoolbox/@core/uminus
%   Syntax:
%     * r = uminus(c)
%
%   Input Arguments:
%     * c - core object
%
%   negate time series
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

r = core(-data(c));


function convertNetworkToFastRcnn(obj, varargin)
% convertNetworkToFastRcnn(obj, varargin)
%
% Modify network for Fast R-CNN's ROI pooling.
%
% Copyright by Holger Caesar, 2015
% Updated by Jasper Uijlings:
%  - Extra flexibility and possible bounding box regression
%  - Added instanceWeights to loss layer

% Initial settings
p = inputParser;
addParameter(p, 'lastConvPoolName', 'pool5');
addParameter(p, 'finalFCName', 'fc8');
parse(p, varargin{:});

lastConvPoolName = p.Results.lastConvPoolName;
finalFCName = p.Results.finalFCName;

fprintf('Converting object classification network to Fast R-CNN network (ROI pooling, box regression, etc.)...\n');

%%% Add weights to loss layer. Note that this field remains empty when not
% given as input. So the loss layers should ignore empty weights.
softmaxInputs = obj.net.layers(obj.net.getLayerIndex('softmaxloss')).inputs;
if ~ismember('instanceWeights', softmaxInputs)
    softmaxInputs{end+1} = 'instanceWeights';
    obj.net.setLayerInputs('softmaxloss', softmaxInputs);
end

%%% Replace pooling layer of last convolution layer with roiPooling
lastConvPoolIdx = obj.net.getLayerIndex(lastConvPoolName);
assert(~isnan(lastConvPoolIdx));
roiPoolName = ['roi', lastConvPoolName];
firstFCIdx = obj.net.layers(lastConvPoolIdx).outputIndexes;
assert(length(firstFCIdx) == 1);
roiPoolSize = obj.net.layers(firstFCIdx).block.size(1:2);
roiPoolBlock = dagnn.RoiPooling('poolSize', roiPoolSize);
replaceLayer(obj.net, lastConvPoolName, roiPoolName, roiPoolBlock, {'oriImSize', 'boxes'}, {'roiPoolMask'});

%%% Add bounding box regression layer
if obj.nnOpts.bboxRegress
    finalFCLayerIdx = obj.net.getLayerIndex(finalFCName);
    inputVars = obj.net.layers(finalFCLayerIdx).inputs;
    finalFCLayerSize = size(obj.net.params(obj.net.layers(finalFCLayerIdx).paramIndexes(1)).value);
    regressLayerSize = finalFCLayerSize .* [1 1 1 4]; % Four times bigger than classification layer
    regressName = [finalFCName 'regress'];
    obj.net.addLayer(regressName, dagnn.Conv('size', regressLayerSize), inputVars, {'regressionScore'}, {'regressf', 'regressb'});
    regressIdx = obj.net.getLayerIndex(regressName);
    newParams = obj.net.layers(regressIdx).block.initParams();
    obj.net.params(obj.net.layers(regressIdx).paramIndexes(1)).value = newParams{1} / std(newParams{1}(:)) * 0.001; % Girshick initialization with std of 0.001
    obj.net.params(obj.net.layers(regressIdx).paramIndexes(2)).value = newParams{2};

    obj.net.addLayer('regressLoss', dagnn.LossRegress('loss', 'Smooth', 'smoothMaxDiff', 1), ...
        {'regressionScore', 'regressionTargets', 'instanceWeights'}, 'regressObjective');
end

%%% Set correct learning rates and biases (Girshick style)
if obj.nnOpts.fastRcnnParams
    % Biases have learning rate of 2 and no weight decay
    for lI = 1 : length(obj.net.layers)
        if isa(obj.net.layers(lI).block, 'dagnn.Conv')
            biasI = obj.net.layers(lI).paramIndexes(2);
            obj.net.params(biasI).learningRate = 2;
            obj.net.params(biasI).weightDecay = 0;
        end
    end

    % First convolutional layer should not learn
    % Note that this is different from Fast R-CNN, but gives good results
    % Also note that there is no speedup as Matconvnet still computes the
    % gradients, but does not update the parameters.
    conv1I = obj.net.getLayerIndex('conv1'); % AlexNet-style networks
    if isnan(conv1I)
        conv1I = obj.net.getLayerIndex('conv1_1'); % VGG-16 style networks
    end
    obj.net.params(obj.net.layers(conv1I).paramIndexes(1)).learningRate = 0;
    obj.net.params(obj.net.layers(conv1I).paramIndexes(2)).learningRate = 0;
end


function v = cvxcnst( rhs )
v = class( struct( 'rhs_', rhs ), 'cvxcnst' );

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function e = horzcat(varargin)
% overloads [e1,e2,e3..]

e = cat(2,varargin{:});


function plotFourier(SO3F,varargin)
% visualize the harmonic coefficients
%
% Syntax
%   plotFourier(SO3F)
%   plotFourier(SO3F,'bandwidth',32)
%
% Input
%  SO3F - @SO3Fun
%

warning('The command plotFourier is depreciated! Please use plotSpektra instead.')

plotSpektra(SO3F,varargin)


function t_pf_radial(quiet)
%T_PF_RADIAL  Tests for distribution power flow solvers.

if nargin < 1
    quiet = 0;
end

t_begin(329, quiet);

if quiet
    verbose = 0;
else
    verbose = 1;
end
if have_feature('octave')
    if have_feature('octave', 'vnum') >= 4
        file_in_path_warn_id = 'Octave:data-file-in-path';
    else
        file_in_path_warn_id = 'Octave:load-file-in-path';
    end
    s1 = warning('query', file_in_path_warn_id);
    warning('off', file_in_path_warn_id);
end
mpopt = mpoption('out.all', 0, 'verbose', verbose);

%% define named indices into bus, gen, branch matrices
[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;

%% Test Distribution Power Flow
mpopt = mpoption(mpopt, 'pf.alg', 'NR', 'pf.radial.max_it', 100);
casefile = {
    'case4_dist'
    'case18'
    'case22'
    'case33bw'
    'case69'
    'case85'
    'case141'
    };
method = {
    'PQSUM' 'Power Summation'
    'ISUM'  'Current Summation'
    'YSUM'  'Admittance Summation'
    };

% Original test cases (no PV buses)
iter_expected = {
           'none'    'NR' 'PQSUM' 'ISUM' 'YSUM'
     'case4_dist'      3      12     12     11
         'case18'      4       9     12     10
         'case22'      3       3      6      6
       'case33bw'      3       5      8      8
         'case69'      4       5      8      8
         'case85'      4       5      9      9
        'case141'      3       4      7      7
        };
iter_nopv = zeros(size(casefile,1),size(method,1)+1);
for i = 1:length(casefile)
    % which row in iter_expected is for current casefile
    row = find(strcmp(casefile{i}, iter_expected(:,1)) == 1);
    mpc = loadcase(casefile{i});
    % solve it with NR
    r = runpf(mpc, mpopt);
    iter_nopv(i,1) = r.iterations;
    % which columng in iter_expected is for current method
    col = find(strcmp('NR', iter_expected(1,:)) == 1);
    t = ['Newton''s method, ' casefile{i} ' : '];
    t_is(r.iterations, iter_expected{row,col}, 6, [t 'iterations']);
    for j = 1:size(method,1)
        mpopt1 = mpoption(mpopt,'pf.alg',method{j,1});
        r1 = runpf(mpc,mpopt1);
        iter_nopv(i,j+1) = r1.iterations;
        % which columng in iter_expected is for current method
        col = find(strcmp(method{j,1}, iter_expected(1,:)) == 1);
        t = [method{j,2} ', ' casefile{i} ' : '];
        t_ok(r1.success, [t 'success']);
        t_is(r1.iterations, iter_expected{row,col}, 6, [t 'iterations']);
        t_is(r1.bus, r.bus, 6, [t 'bus']);
        t_is(r1.gen, r.gen, 6, [t 'gen']);
        t_is(r1.branch, r.branch, 6, [t 'branch']);
    end
end

% Test cases with added PV buses
clear iter_expected
iter_expected{1} = {
% pf.radial.vcorr = 0
           'none'    'NR' 'PQSUM' 'ISUM' 'YSUM'
     'case4_dist'      3      12     12     11
         'case18'      4      20     16     13
         'case22'      4      11     25     25
       'case33bw'      4       8     16     16
         'case69'      4      12     27     27
         'case85'      5       9     17     17
        'case141'      5       9     18     18
};
iter_expected{2} = {
% pf.radial.vcorr = 1
           'none'    'NR' 'PQSUM' 'ISUM' 'YSUM'
     'case4_dist'      3       7      6      7
         'case18'      4      10     12     12
         'case22'      4      12     14     14
       'case33bw'      4       8     11     11
         'case69'      4      13     17     17
         'case85'      5       9     13     13
        'case141'      5       9     12     12
};
iter_pv = zeros(size(casefile,1),size(method,1)+1,2);
for i = 1:length(casefile)
    % which row in iter_expected is for current casefile
    row = find(strcmp(casefile{i}, iter_expected{1}(:,1)) == 1);
    mpc = loadcase(casefile{i});
    pv = mpc.bus(:,BUS_TYPE) == PV;
    if all(~pv)
        %%% ADD PV BUSES %%%
        N = 5; % How many PV buses should I add?
        % Solve the case without PV buses with Newton method
        r = runpf(mpc, mpopt);
        % Find the last N buses with lowest voltage
        [Vm, B] = sort(r.bus(:,VM));
        B = B(1:N);
        Vm = Vm(1:N);
        % add PV generators at buses in B
        % set VG 0.05 pu bigger then voltage at buses in B
        mpc.gen = repmat(mpc.gen,N+1,1);
        mpc.gen(2:end,GEN_BUS) = mpc.bus(B, BUS_I);
        mpc.gen(2:end,VG) = Vm + 0.05;
        mpc.bus(B,BUS_TYPE) = 2;
        if isfield(mpc,'gencost')
            mpc.gencost = repmat(mpc.gencost,N+1,1);
        end
        %%% END OF ADD PV BUSES %%%
    end
    r = runpf(mpc, mpopt);
    iter_pv(i,1,1) = r.iterations;
    iter_pv(i,1,2) = r.iterations;
    % which columng in iter_expected is for current method
    col = find(strcmp('NR', iter_expected{1}(1,:)) == 1);
    t = ['Newton''s method, ' casefile{i} ' : '];
    t_is(r.iterations, iter_expected{1}{row,col}, 6, [t 'iterations']);
    for j = 1:size(method,1)
        for vcorr = 0:1
            mpopt1 = mpoption(mpopt,'pf.alg',method{j,1},'pf.radial.vcorr',vcorr);
            r1 = runpf(mpc,mpopt1);
            iter_pv(i,j+1,vcorr+1) = r1.iterations;
            % which columng in iter_expected is for current method
            col = find(strcmp(method{j,1}, iter_expected{vcorr+1}(1,:)) == 1);
            t = [method{j,2} ', vcorr = ' num2str(vcorr) ', ' casefile{i} ' : '];
            t_ok(r1.success, [t 'success']);
            t_is(r1.iterations, iter_expected{vcorr+1}{row,col}, 6, [t 'iterations']);
            t_is(r1.bus, r.bus, 6, [t 'bus']);
            t_is(r1.gen, r.gen, 6, [t 'gen']);
            t_is(r1.branch, r.branch, 6, [t 'branch']);
        end
    end
end

t_end;

if verbose > 0
    fprintf('\nITERATIONS: Original test cases (no PV buses), pf.radial.vcorr = 0\n');
    print_iterations(casefile,method,iter_nopv)
    fprintf('\nITERATIONS: Test cases with added PV buses, pf.radial.vcorr = 0\n');
    print_iterations(casefile,method,iter_pv(:,:,1))
    fprintf('\nITERATIONS: Test cases with added PV buses, pf.radial.vcorr = 1\n');
    print_iterations(casefile,method,iter_pv(:,:,2))
end

if have_feature('octave')
    warning(s1.state, file_in_path_warn_id);
end

function print_iterations(casefile,method,iterations)
fprintf('%22s','NR');
for j = 1:size(method,1)
    fprintf('%7s',method{j,1});
end
fprintf('\n');
for i = 1:length(casefile)
    fprintf('%15s',casefile{i});
    for j = 1:size(method,1)+1
        fprintf('%7i',iterations(i,j));
    end
    fprintf('\n');
end


%%% Replay the set of solution vectors:

if ~exist('param_list'),
   if ~exist('solution');
      fprintf(1,'Error: Need to calibrate first\n');
      return;
   else
      param_list = solution;
   end;
end;

N_iter = size(param_list,2);

if N_iter == 1,
   fprintf(1,'Warning: There is a unique state in the list of parameters.\n');
end;

%M = moviein(N_iter);

for nn = 1:N_iter,

   solution = param_list(:,nn);

   extract_parameters;
   comp_error_calib;

   ext_calib;

   drawnow;

%   Mnn = getframe(gcf);

%   M(:,nn) = Mnn;

end;

%fig = gcf;

%figure(fig+1);
%close;
%figure(fig+1);

%clf;
%movie(M,20);


function c = diff(c)

% DIFF differentiate each trace.
%
% C = DIFF(C) differentiate each trace through a call to WAVEFORM/DIFF.
% See WAVEFORM/DIFF for details

% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
% $Date$
% $Revision$

c.W = diff(c.W);


% pop_writeeeg - write EEGLAB dataset to disk in EDF/GDF or BDF format
%
% pop_writeeeg( EEG ) % pops up a window
% pop_writeeeg( EEG, filename, 'key', 'val' )
%
% Inputs:
%  EEG        - EEGLAB dataset
%  filename   - [string] filename
%
% Optional keys (same as writeeeg):
%  'TYPE'         - ['GDF'|'EDF'|'BDF'|'CFWB'|'CNT'] file format for writing
%                   default is 'EDF'.
%  See writeeeg for more information
%
% Author: Arnaud Delorme, SCCN, UCSD/CERCO, 2009
%         Based on BIOSIG, sopen and swrite

% Copyright (C) 22 March 2002 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 [command] = pop_writeeeg(EEG, filename, varargin);
command = '';

if nargin < 2
    if EEG.trials > 1
        res = questdlg2( [ 'This dataset contains data epochs.' 10 'Do you want to export the concatenated' 10 'data epochs?' ], '', 'No', 'Yes', 'Yes');
        if strcmpi(res, 'No')
            return;
        end;
    end;

	% ask user
	[filename, filepath] = uiputfile('*.*', 'Enter a file name -- pop_writeeeg()');
	if filename == 0 return; end;
	filename = fullfile(filepath,filename);

    % file format
    % -----------
    fileformats = { 'EDF' 'GDF' 'BDF' };
    uilist = { { 'style' 'text' 'String' 'File format' } ...
               { 'style' 'listbox' 'string' strvcat(fileformats) 'value' 1 } };
    geom = [1 1];
    result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''pop_writeeeg'')', ...
                     'title', 'Write data using BIOSIG -- pop_writeeeg()', 'geomvert', [1 2.5]);
    if length(result) == 0 return; end;

    options = { 'TYPE' fileformats{result{1}} };
else
    options = varargin;
end;

warning('off', 'MATLAB:intConvertNonIntVal');
if ~isempty(EEG.chanlocs)
    tmpchanlocs = EEG.chanlocs;
    writeeeg(filename, EEG.data(:,:), EEG.srate, 'label', { tmpchanlocs.labels }, 'EVENT', EEG.event, options{:});
else
    writeeeg(filename, EEG.data(:,:), EEG.srate, 'EVENT', EEG.event, options{:});
end;
warning('on', 'MATLAB:intConvertNonIntVal');

command = sprintf('pop_writeeeg(EEG, ''%s'', %s);', filename, vararg2str(options));

return;


function res = pickconditions(this, label, rejectbad)
% Method for returning indices of trials of a certain trial type.
% If input argument rejectbad == 0, the function will also return trial
% indices which are set to bad (i.e. rejected). If bad is omitted,
% the default is not to include rejected trials.
% FORMAT res = pickconditions(this)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Stefan Kiebel
% $Id: pickconditions.m 3146 2009-05-26 09:54:23Z vladimir $

if nargin<3
    rejectbad = 1;
end

c = conditions(this);

if isa(label, 'char')
    label = {label};
end

res = find(ismember(c, label));

if rejectbad && ~isempty(res)
    res = res(~reject(this, res));
end


function F = imag( F )
%IMAG   Imaginary part of a DISKFUNV.
%   IMAG(F) returns the imaginary part of a DISKFUNV.
%
%   Since all DISKFUNV objects are real-valued, the result of this
%   function is always the original DISKFUNV F.
%
% See also DISKFUNV/CONJ, DISKFUNV/REAL.

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

% Empty check:
if ( isempty( F ) )
    return
end

% Take imaginary part of each component:
F.components = cellfun( @imag, F.components, 'UniformOutput', false );

end


label='';
for k = 1:5
if k==1
    label='_gau_001';
end
if k==2
    label='_gau_0005';
end
if k==3
    label='_sp_01';
end
if k==4
    label='_sp_02';
end
if k==5
    label='_poi';
end
disp(label);

for i=1:10
index = i;

fused_path = ['./fused_mf_noise/fused',num2str(i),label,'_cbf.png'];
fused_path_new = ['./fused_mf_noise/fused',num2str(i),label,'_convsr.png'];

im=imread(fused_path);
imwrite(im,fused_path_new);
delete(fused_path);
end
end


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

%%
clear; close all; clc;

%% Syntax
% |[Et,Vt,Ft]=hexahedral_hexagon_beam(r,ne,hz,nz,XYZ_centre);|

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


% This script performs our evaluation on simulated datasets obtained from
% our ground truth data.

%% Update MATLAB path.
addpath(genpath('../utility'));
addpath(genpath('../algorithms/OpticalFlow'));
addpath(genpath('../algorithms/SRAlgorithms'));

%% Evaluation settings.

% Path to input data and result directory.
inputDir = '../../data';
datasetConfig = 'baselineDatasets';
resultDir = '../../results/simulatedDatasets';

% Parameters for this evaluation.
initEvaluationParametersForSimulatedDatasets;

%% Start evaluation.
processDatasets(inputDir, datasetConfig, resultDir, binningFactors, numberOfFrames, startReferenceFrame, numberOfFrames_val, sliding_val, sr_method, binning_val, scenes_val, compressions(compress_val), 1, true);


function definput = arg_fwt(definput)

%definput.flags.ext=  {'per','zpd','sym','symw','asym','asymw','ppd','sp0'};
definput.flags.ext = {'per','zero','even','odd'};


classdef PTKAirwayGrowingLabelledBySegment < PTKPlugin
    % PTKAirwayGrowingLabelledBySegment. Plugin to find the segmental bronchi in each lobe
    %
    %     This is a plugin for the Pulmonary Toolkit. Plugins can be run using
    %     the gui, or through the interfaces provided by the Pulmonary Toolkit.
    %     See PTKPlugin.m for more information on how to run plugins.
    %
    %     Plugins should not be run directly from your code.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    properties
        ButtonText = 'Growing bronchi<br>labelled by segment'
        ToolTip = 'Finds the segmental bronchi in each lobe'
        Category = 'Airways'

        AllowResultsToBeCached = true
        AlwaysRunPlugin = false
        PluginType = 'DoNothing'
        HidePluginInDisplay = false
        FlattenPreviewImage = true
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 2
        GeneratePreview = false
        Visibility = 'Developer'
    end

    methods (Static)
        function results = RunPlugin(dataset, reporting)
            growing_centreline_tree = dataset.GetResult('PTKAirwayGrowing');
            growing_centreline_tree = growing_centreline_tree.Airways;

            segments_by_bronchus = dataset.GetResult('PTKSegmentsByNearestBronchus');

            labelled_segmental_tree = segments_by_bronchus.AirwaysBySegment.Trachea;

            growing_tree_with_segmental_labels = PTKMapSegmentalParameters(labelled_segmental_tree, growing_centreline_tree, reporting);

            results = [];
            results.StartBranches = growing_tree_with_segmental_labels;
        end
    end
end


function c = cellRemoveEmpty(inCell)
%Remove empty entries from a cell array
%
%   c = cellRemoveEmpty(inCell)
%
% GB/BW
% See removeListElement for another way to do this.
%

if isempty(inCell), c = {}; return; end
n = length(inCell);
emptyList = [];
for ii=1:n
    if isempty(inCell{ii}), emptyList = [emptyList,ii]; end
end
if isempty(emptyList), c = inCell; return; end
c = {};
for ii=setdiff(1:n,emptyList)
    c{end+1} = inCell{ii};
end
return;


function [image_roidb, bbox_means, bbox_stds] = mask_prepare_image_roidb_voc(conf, imdbs, roidbs, bbox_means, bbox_stds)
% [image_roidb, bbox_means, bbox_stds] = fast_rcnn_prepare_image_roidb(conf, imdbs, roidbs, cache_img, bbox_means, bbox_stds)
%   Gather useful information from imdb and roidb
%   pre-calculate mean (bbox_means) and std (bbox_stds) of the regression
%   term for normalization
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------

    if ~exist('bbox_means', 'var')
        bbox_means = [];
        bbox_stds = [];
    end

    if ~iscell(imdbs)
        imdbs = {imdbs};
        roidbs = {roidbs};
    end

    imdbs = imdbs(:);
    roidbs = roidbs(:);

    image_roidb = ...
        cellfun(@(x, y) ... // @(imdbs, roidbs)
               arrayfun(@(z) ... //@([1:length(x.image_ids)])
                        struct('image_path', x.image_at(z), 'image_seg_path', x.image_seg_at(z), 'image_id', x.image_ids{z}, ...
                        'im_size', x.sizes(z, :), 'imdb_name', x.name, 'overlap', y.rois(z).overlap, 'boxes', y.rois(z).boxes, ...
                        'class', y.rois(z).class, 'image', [], 'bbox_targets', [], 'mask_targets', []), ...
                        [1:length(x.image_ids)]', 'UniformOutput', true),...
        imdbs, roidbs, 'UniformOutput', false);

    image_roidb = cat(1, image_roidb{:});

    % enhance roidb to contain bounding-box regression targets
    [image_roidb, bbox_means, bbox_stds] = append_bbox_regression_targets(conf, image_roidb, bbox_means, bbox_stds);
end

function [image_roidb, means, stds] = append_bbox_regression_targets(conf, image_roidb, means, stds)
    % means and stds -- (k+1) * 4, include background class

    num_images = length(image_roidb);
    % Infer number of classes from the number of columns in gt_overlaps
    num_classes = size(image_roidb(1).overlap, 2);
    valid_imgs = true(num_images, 1);
    for i = 1:num_images
       rois = image_roidb(i).boxes;
       [image_roidb(i).bbox_targets, image_roidb(i).mask_targets, valid_imgs(i)] = ...
           compute_targets(conf, rois, image_roidb(i).overlap, image_roidb(i).image_seg_path);
    end
    if ~all(valid_imgs)
        image_roidb = image_roidb(valid_imgs);
        num_images = length(image_roidb);
        fprintf('Warning: fast_rcnn_prepare_image_roidb: filter out %d images, which contains zero valid samples\n', sum(~valid_imgs));
    end
    if ~(exist('means', 'var') && ~isempty(means) && exist('stds', 'var') && ~isempty(stds))
        % Compute values needed for means and stds
        % var(x) = E(x^2) - E(x)^2
        class_counts = zeros(num_classes, 1) + eps;
        sums = zeros(num_classes, 4);
        squared_sums = zeros(num_classes, 4);
        for i = 1:num_images
           targets = image_roidb(i).bbox_targets;
           for cls = 1:num_classes
              cls_inds = find(targets(:, 1) == cls);
              if ~isempty(cls_inds)
                 class_counts(cls) = class_counts(cls) + length(cls_inds);
                 sums(cls, :) = sums(cls, :) + sum(targets(cls_inds, 2:end), 1);
                 squared_sums(cls, :) = squared_sums(cls, :) + sum(targets(cls_inds, 2:end).^2, 1);
              end
           end
        end

        means = bsxfun(@rdivide, sums, class_counts);
        stds = (bsxfun(@minus, bsxfun(@rdivide, squared_sums, class_counts), means.^2)).^0.5;
        % add background class
        means = [0, 0, 0, 0; means];
        stds = [0, 0, 0, 0; stds];

    end
    % Normalize targets
    for i = 1:num_images
        targets = image_roidb(i).bbox_targets;
        for cls = 1:num_classes
            cls_inds = find(targets(:, 1) == cls);
            if ~isempty(cls_inds)
                image_roidb(i).bbox_targets(cls_inds, 2:end) = ...
                    bsxfun(@minus, image_roidb(i).bbox_targets(cls_inds, 2:end), means(cls+1, :));
                image_roidb(i).bbox_targets(cls_inds, 2:end) = ...
                    bsxfun(@rdivide, image_roidb(i).bbox_targets(cls_inds, 2:end), stds(cls+1, :));
            end
        end
    end
end

function [bbox_targets, mask_targets, is_valid] = compute_targets(conf, rois, overlap, img_seg_path)
%function [bbox_targets, is_valid] = compute_targets(conf, rois, overlap)
    overlap = full(overlap);

    [max_overlaps, max_labels] = max(overlap, [], 2);

    % ensure ROIs are floats
    rois = single(rois);

    bbox_targets = zeros(size(rois, 1), 5, 'single');
    mask_targets = zeros(size(rois,1), 28, 28, 'single');
    % Indices of ground-truth ROIs
    gt_inds = find(max_overlaps == 1);

    if ~isempty(gt_inds)
        % Indices of examples for which we try to make predictions
        ex_inds = find(max_overlaps >= conf.bbox_thresh);

        % Get IoU overlap between each ex ROI and gt ROI
        ex_gt_overlaps = boxoverlap(rois(ex_inds, :), rois(gt_inds, :));

        %Small error between gt overlap and calculated overlap
        assert(all(abs(max(ex_gt_overlaps, [], 2) - max_overlaps(ex_inds)) < 10^-4));

        % Find which gt ROI each ex ROI has max overlap with:
        % this will be the ex ROI's gt target
        [~, gt_assignment] = max(ex_gt_overlaps, [], 2);
        gt_rois = rois(gt_inds(gt_assignment), :);
        ex_rois = rois(ex_inds, :);

        [regression_label] = fast_rcnn_bbox_transform(ex_rois, gt_rois);

        bbox_targets(ex_inds, :) = [max_labels(ex_inds), regression_label];
        seg_image = imread(img_seg_path);
        [max_h, max_w] = size(seg_image);

        %Get mask targets
        for i=1:size(ex_rois,1)
          roi_orig = ex_rois(round(i),:); %convert to int before accessing indices
          mask = seg_image(max(1, roi_orig(2)): min(max_h, roi_orig(4)), max(1, roi_orig(1)):min(max_w, roi_orig(3)));
          mask = imresize(mask, [28, 28], 'nearest');
          mask(mask == 255) = 0; % We consider void boundaries as background
          mask_targets(i,:,:) = mask;
        end
    end
    % Select foreground ROIs as those with >= fg_thresh overlap
    is_fg = max_overlaps >= conf.fg_thresh;
    % Select background ROIs as those within [bg_thresh_lo, bg_thresh_hi)
    is_bg = max_overlaps < conf.bg_thresh_hi & max_overlaps >= conf.bg_thresh_lo;

    % check if there is any fg or bg sample. If no, filter out this image
    is_valid = true;
    if ~any(is_fg | is_bg)
        is_valid = false;
    end
end


function fg = dtiFiberCombineFiberGroups(fgList,outName,type)
%
% fg = dtiFiberCombineGroups([fgList=uiselectfile],...
%                            [outName='combinedFiberGroup'],[type='pdb'])
%
% Combine N fiber groups (pdb or mat) into a single fiber group and save.
% This routine is a wrapper for dtiMergeFiberGroups, making it simple to
% comine an arbitrary number of groups.
%
% INPUTS:
%   fgList  - CELL ARRAY of fiber names.
%   outName - Name of fiber group to save.
%   type    - 'mat' or 'pdb'
%
%
% (C) Stanford University, VISTA Lab
%

%% Check INPUTS

if notDefined('fgList')
    [names p] = uigetfile({'*.pdb';'*.mat'}, 'Select fiber groups','MultiSelect','on');
    for ff=1:numel(names)
        fgList{ff} = fullfile(p, names{ff});
    end
end

if ~iscell(fgList)
    error('fgList must be a cell array of fiber names');
end

if notDefined('type')
    type = 'pdb';
end

if notDefined('outName')
        outName = fullfile(pwd,['combinedFiberGroup.' type]);
        name = 'combinedFiberGroup';
else
    [~, name ~] = fileparts(outName);
end

%% Combine the fiber groups

disp('Combining fiber groups...');

for ii=1:numel(fgList)
    if ii==1
        fg = fgRead(fgList{ii});
    else
        fgM = fgRead(fgList{ii});
        fg = dtiMergeFiberGroups(fg,fgM);
    end

end

fg.name = name;

%% Save

fprintf('\n Saved: %s\n', outName);
fgWrite(fg,outName,type);

return


function [HDR] = save2bkr(arg1,arg2,arg3);
% SAVE2BKR loads EEG data and saves it in BKR format
% The following data formats are supported:
%	CNT, EDF, BKR, MAT, etc. format
%
%       HDR = save2bkr(sourcefile [, destfile [, option]]);
%
%       HDR = eegchkhdr();
%	HDR = save2bkr(HDR,data);
%
%   sourcefile	sourcefile wildcards are allowed
%   destfile	destination file in BKR format
%	if destfile is empty or a directory, sourcefile but with extension .bkr is used.
%   options
%       gain            Gain factor for unscaled EEG data (e.g. old Matlab files)
%       'removeDC'      removes mean
%       'regressEOG k:l,m:n'     removes EOG (channels m:n) from EEG (channels k:l)
%       'autoscale k:l'	uses only channels from k to l for scaling
%       'detrend k:l'	channels from k to l are detrended with an FIR-highpass filter.
%       'PhysMax=XXX'	uses a fixed scaling factor; might be important for concanating BKR files
%			+XXX and -XXX correspond to the maximum and minimum physical value, resp.
% 		You can concanate several options by separating with space, komma or semicolon
%
%   HDR		Header, HDR.FileName must contain target filename
%   data	data samples
%
% Examples:
%   save2bkr('/tmp/*.cnt',[],'autoscale 5:30');
%	converts all CNT-files from subdir /tmp/ into BKR files
%       and saves them in the current directory
%   save2bkr('/tmp/*.cnt','/tmp2/','autoscale 5:30, PhysMax=200');
%	converts all CNT-files from subdir /tmp/ into BKR files
%       and saves them in the directory /tmp2/
%
%
%
% see also: EEGCHKHDR, REGRESS_EOG, SLOAD

%	$Revision: 1.23 $
% 	$Id: save2bkr.m 2205 2009-10-27 12:18:15Z schloegl $
%	Copyright (C) 2002-2003 by Alois Schloegl <a.schloegl@ieee.org>
%    	This is part of the BIOSIG-toolbox http://biosig.sf.net/

% This library is free software; you can redistribute it and/or
% modify it under the terms of the GNU Library General Public
% License as published by the Free Software Foundation; either
% Version 2 of the License, or (at your option) any later version.
%
% This library 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
% Library General Public License for more details.
%
% You should have received a copy of the GNU Library General Public
% License along with this library; if not, write to the
% Free Software Foundation, Inc., 59 Temple Place - Suite 330,
% Boston, MA  02111-1307, USA.

FLAG_REGRESS_EOG = 0;
FLAG_REMOVE_DC = 0;
FLAG_AUTOSCALE = 0;
FLAG_DETREND = 0;
FLAG_PHYSMAX = 0;
FLAG_removeDrift = 0;

chansel = 0;

if nargin<2, arg2=[]; end;

if nargin<3,
        cali = NaN;
elseif isnumeric(arg3)
        cali = arg3;
else
        FLAG_REMOVE_DC = findstr(lower(arg3),'removedc');

        tmp = findstr(arg3,'autoscale');
        if ~isempty(tmp);
                [chansel,tmp] = strtok(arg3(tmp+9:length(arg3)),' ;+');
                tmp = str2num(chansel);
                if isempty(tmp),
                        fprintf(2,'invalid autoscale argument %s',chansel);
                        return;
                else
                        FLAG_AUTOSCALE = 1;
                        chansel = tmp;
                end;
        end;

        tmp = findstr(lower(arg3),'detrend');
        if ~isempty(tmp);
                [chansel_dt,tmp] = strtok(arg3(tmp+7:length(arg3)),' ;,+');
                tmp = str2num(chansel_dt);
                if isempty(tmp),
                        fprintf(2,'invalid detrend argument %s',chansel_dt);
                        return;
                else
                        FLAG_DETREND = 1;
                        chansel_dt = tmp;
                end;
        end;

        tmp = findstr(lower(arg3),'removedrift');
        if ~isempty(tmp);
                [chansel_dt2,tmp] = strtok(arg3(tmp+11:length(arg3)),' ;+');
                tmp = str2num(chansel_dt2);
                if isempty(tmp),
                        fprintf(2,'invalid RemoveDrift argument %s',chansel_dt2);
                        return;
                else
                        FLAG_removeDrift = 1;
                        chansel_dt2 = tmp;
                end;
        end;

        tmp = findstr(lower(arg3),'regresseog');
        if ~isempty(tmp);
                [chansel_dt3,tmp] = strtok(arg3(tmp+11:length(arg3)),' ;,+');
                [chansel_dt4,tmp] = strtok(tmp,' ;,+');
                tmp = str2num(chansel_dt3);
                FLAG_REGRESS_EOG = ~isempty(tmp);
                if isempty(tmp),
                        fprintf(2,'invalid REGRESSEOG argument %s',chansel_dt3);
                        return;
                else
                        FLAG_REGRESS_EOG = 1;
                        chansel_dt3 = tmp;
                end;
                tmp = str2num(chansel_dt4);
                FLAG_REGRESS_EOG = FLAG_REGRESS_EOG * ~isempty(tmp);
                if isempty(tmp),
                        fprintf(2,'invalid REGRESSEOG argument %s',chansel_dt4);
                        return;
                else
                        chansel_dt4 = tmp;
                end;
        end;
        tmp = findstr(lower(arg3),'physmax=');
        if ~isempty(tmp);
                [tmp,tmp1] = strtok(arg3(tmp+8:length(arg3)),' ;,');
                PHYSMAX = str2num(tmp);
                if isempty(PHYSMAX ),
                        fprintf(2,'invalid PhysMax argument %s',tmp);
                        return;
                else
                        FLAG_PHYSMAX = 1;
                end;
        end;
end;

if 0,
elseif exist(arg1,'file')
	inpath='';
	infile.name=arg1;
        outfile = arg2;
elseif exist(arg1,'dir')
        inpath = fileparts(arg1);
        infile = dir(arg1);	% input  file
        if isempty(infile)
                fprintf(2,'ERROR SAVE2BKR: file %s not found.\n',arg1);
                return;
        end;
        outfile = arg2;
elseif isstruct(arg1) & isnumeric(arg2),
        HDR  = arg1;
        data = arg2;
else  %if isstruct(arg1) & isnumeric(arg2),
        fprintf(2,'Error SAVE2BKR: invalid input arguments\n');
        return;
end;

if isstruct(arg1),
        %HDR.FileName 	= destfile;	% Assign Filename
        if isfield(HDR,'NS')
                if HDR.NS==size(data,2),
                        % It's ok.
                elseif HDR.NS==size(data,1),
                        warning('data is transposed\n');
                        data = data';
                else
                        fprintf(2,'HDR.NS=%i is not equal number of data columns %i\n',HDR.NS,size(data,2));
                        return;
                end;
        else
                HDR.NS = size(data,2);	% number of channels
        end;
        if ~isfield(HDR,'NRec'),
                HDR.NRec = 1;		% number of trials (1 for continous data)
        end;
        HDR.SPR 	= size(data,1)/HDR.NRec;	% number of samples per trial
        %HDR.SampleRate	= 100;		% Sampling rate
        %HDR.Label  	= hdr.Label; % Labels,

        %HDR.PhysMax 	= max(abs(data(:)));	% Physical maximum
        %HDR.DigMax 	= max(2^15-1);		% Digital maximum
        % --- !!! Previous scaling gave an error up to 6% and more !!! ---

        %HDR.Filter.LowPass  = 30;	% upper cutoff frequency
        %HDR.Filter.HighPass = .5;	% lower cutoff frequency
        HDR.FLAG.REFERENCE   = ' ';	% reference '', 'LOC', 'COM', 'LAP', 'WGT'
        %HDR.FLAG.REFERENCE  = HDR.Recording;
        HDR.FLAG.TRIGGERED   = HDR.NRec>1;	% Trigger Flag

        if FLAG_REMOVE_DC,
                %y = center(y,1);
                data = data - repmat(mean(data,1),size(data,1),1);
        end;
        if chansel == 0;
                chansel=1:HDR.NS;
        end;
        tmp = data(:,chansel);
        HDR.PhysMax = max(abs(tmp(:))); %gives max of the whole matrix
        HDR.DigMax = 2^15-1;            % maximum resulution
        for k = 1:HDR.NS,
                if any(k==chansel),
                        data(:,k) = data(:,k)*HDR.DigMax/HDR.PhysMax;
                else
                        mm = max(abs(data(:,k)));
                        data(:,k) = data(:,k)*HDR.DigMax/mm;
                end;
        end;
        HDR.FLAG.UCAL = 1;              % data is de-calibrated, no rescaling within SWRITE
        %HDR = eegchkhdr(HDR);
        HDR.TYPE = 'BKR';

        HDR = sopen (HDR,'w',0);     	% OPEN BKR FILE
        HDR = swrite(HDR,data);  	% WRITE BKR FILE
        %fwrite(HDR.FILE.FID,data','int16');  	% WRITE BKR FILE
        HDR = sclose(HDR);            % CLOSE BKR FILE

        % save Classlabels
        if isfield(HDR,'Classlabel'),
                fid = fopen([HDR.FileName(1:length(HDR.FileName)-4) '.par'],'wt');
                fprintf(fid, '%i\n', HDR.Classlabel);
                fclose(fid);
        end;
        if isfield(HDR,'ArtifactSelection'),
                fid = fopen([HDR.FileName(1:length(HDR.FileName)-4) '.sel'],'w');
                fprintf(fid, '%i\r\n', HDR.ArtifactSelection);
                fclose(fid);
        end;

        % final test
        try
                HDR = sopen(HDR.FileName,'r');
                HDR = sclose(HDR);
        catch
                fprintf(2,'Error SAVE2BKR: saving file %s failed\n',HDR.FileName);
        end;
        return;
end;

for k=1:length(infile);
        filename = fullfile(inpath,infile(k).name);
        [pf,fn,ext] = fileparts(filename);

        % load eeg data
        [y,HDR] = sload(filename);

        % load classlabels if the exist
        tmp = fullfile(HDR.FILE.Path,[HDR.FILE.Name,'.mat']);
        if exist(tmp),
                tmp=load(tmp);
                if isfield(tmp,'classlabel');
                        HDR.Classlabel = tmp.classlabel;
                end;
        end;

        if isempty(y),
                fprintf(2,'Error SAVE2BKR: file %s not found\n',filename);
                return;
        end;

        if ~isfield(HDR,'NS'),
                warning(['number of channels undefined in ',filename]);
                HDR.NS = size(y,2);
        end;
        if ~HDR.FLAG.TRIGGERED,
                HDR.NRec = 1;
                HDR.SPR = size(y,1);
        end;
        if ~isfield(HDR,'NRec'),
                HDR.NRec = 1;
        end;
        if ~isfield(HDR,'SPR'),
                HDR.SPR = size(y,1)/HDR.NRec;
        elseif length(HDR.SPR)>1,       % use just one sampling rate
                HDR.SPR = HDR.AS.MAXSPR;
                HDR.SampleRate = HDR.AS.MAXSPR/HDR.Dur;
                FLAG_PHYSMAX = 1;
                PHYSMAX = max(abs(y(:)));
                HDR.DigMax  = 2^15-1;
        end;

        if FLAG_REGRESS_EOG,
                fprintf(1,'\tREGRESS_EOG \n');
                [R,y] = regress_eog(y,chansel_dt3,chansel_dt4);
        end;

        if FLAG_REMOVE_DC,
                fprintf(1,'\tREMOVE_DC \n');
                y = y - repmat(mean(y,1),size(y,1),1);
        end;
        if FLAG_DETREND,
                B = -ones(1,HDR.SampleRate)/HDR.SampleRate;
                B(HDR.SampleRate/2) = B(HDR.SampleRate/2)+1;
                HDR.Filter.B = B;
                HDR.Filter.A = 1;
                %HDR.Filter.B=B;%conv(-B, HDR.Filter.B);
                Delay = length(B)/2;
                HDR.FLAG.FILT = 1;
                HDR.Filter.HighPass = .5;

                for k = chansel_dt,
                        tmp = filter(B,1,[y(:,k);zeros(length(B),1)]);
                        y(:,k) = tmp(Delay+1:size(y,1)+Delay);
                end;
        end;

        if FLAG_removeDrift,
                B = .5*(1 - cos(2*pi*(1:4*HDR.SampleRate+1)'/(4*HDR.SampleRate+2)));
                B = -B/sum(B);
                B(2*HDR.SampleRate) = B(HDR.SampleRate)+1;

                B = -ones(1,HDR.SampleRate)/HDR.SampleRate;
                B(HDR.SampleRate/2) = B(HDR.SampleRate/2)+1;
                %B(1) = B(1)+1;

                HDR.Filter.B = B;
                HDR.Filter.A = 1;
                %HDR.Filter.B=B;%conv(-B, HDR.Filter.B);
                Delay = (length(B)-1)/2;
                HDR.FLAG.FILT = 1;
                HDR.Filter.HighPass = .5;

                for k = chansel_dt2,
                        y(:,k) = filtfilt(B,1,y(:,k));
                        %y(:,k) = tmp(Delay+1:size(y,1)+Delay);
                end;
        end;

        if chansel == 0;
                chansel=1:HDR.NS;
        end;

        % add event channel
        if isfield(HDR,'EVENT')
                if ~length(HDR.EVENT.TYP),
                elseif 0,
                        % TypeList = unique(HDR.EVENT.TYP); but ignores NaN's
                        [sY ,idx] = sort(HDR.EVENT.TYP(:));
                        TypeList  = sY([1;find(diff(sY,1)>0)+1]);

                        event = zeros(size(y,1),length(TypeList));
                        for k2 = 1:length(TypeList),
                                tmp = (HDR.EVENT.TYP==TypeList(k2));
                                event(HDR.EVENT.POS(tmp),k2) = HDR.EVENT.TYP(tmp);
                        end;
                        HDR.NS = HDR.NS + size(event,2);
                        y = [y, event];
                elseif all(HDR.EVENT.TYP < 256),  % only NeuroScan Events are converted into separate channels
                        K = 0; event = [];
                        for k1 = 0:7,
                                tmp = bitand(HDR.EVENT.TYP,2^k1);
                                if any(tmp),
                                        K = K+1;
                                        event(size(y,1),K) = 0;
                                        event(HDR.EVENT.POS(tmp>0),K) = 1;
                                end;
                        end;
                        if any(sum(event,2)>1),
                                fprintf(2,'Warning SAVE2BKR: simulateneous events occur. \n');
                        end;
                        HDR.NS = HDR.NS + size(event,2);
                        y = [y, event];
                end;
        end;

        % re-scale data to account for the scaling factor in the header
        HDR.DigMax = 2^15-1;
        if FLAG_PHYSMAX,
                HDR.PhysMax = PHYSMAX;
        else
                tmp = y(:,chansel);
                HDR.PhysMax = max(abs(tmp(:))); %gives max of the whole matrix
        end;
        for k = 1:HDR.NS,
                if any(k==chansel),
                        y(:,k) = y(:,k)*HDR.DigMax/HDR.PhysMax; % keep correct scaling factor
                else
                        mm = max(abs(y(:,k)));
                        y(:,k) = y(:,k)*HDR.DigMax/mm;          % scale to maximum resolution
                end;
        end;
        HDR.FLAG.UCAL = 1;              % data is de-calibrated, no rescaling within SWRITE

        tmp = round(HDR.PhysMax);
        fprintf(1,'Rounding of PhysMax yields %f%% error.\n',abs((HDR.PhysMax-tmp)/tmp)*100);
        HDR.PhysMax = tmp;
        HDR.TYPE = 'BKR';
        HDR.FLAG.REFERENCE = ' ';
        HDR.FLAG.TRIGGERED = (HDR.NRec>1);

        if isempty(outfile), 	% default destination directory
                ix = max(find(filename=='.'));
                %HDR.FileName = [filename(1:ix-1),'.bkr'];  % destination directory is same as source directory
                HDR.FileName  = [HDR.FILE.Name,'.bkr'];     % destination directory is current working directory
        elseif isdir(outfile),	% output file
                HDR.FILE.Path = outfile;
                HDR.FileName  = fullfile(outfile,[HDR.FILE.Name,'.bkr']);
        else
                [HDR.FILE.Path,HDR.FILE.Name,Ext] = fileparts(outfile);
                HDR.FileName = fullfile(HDR.FILE.Path,[HDR.FILE.Name,Ext]);
        end;
        %HDR = eegchkhdr(HDR);

        HDR = sopen(HDR,'w');
        if HDR.FILE.FID < 0,
                fprintf(1,'Error SAVE2BKR: couldnot open file %s.\n',HDR.FileName);
                return;
        end;
        % writes data
        HDR = swrite(HDR,y(:,1:HDR.NS));  	% WRITE BKR FILE
        %count = fwrite(HDR.FILE.FID,y','short');
        HDR = sclose(HDR);

        % save classlabels
        if isfield(HDR,'Classlabel'),
                if ~isempty(HDR.Classlabel),
                        fid = fopen([HDR.FileName(1:length(HDR.FileName)-4) '.par'],'w');
                        fprintf(fid, '%i\r\n', HDR.Classlabel);
                        fclose(fid);
                end;
        end;
        if isfield(HDR,'ArtifactSelection'),
                fid = fopen([HDR.FileName(1:length(HDR.FileName)-4) '.sel'],'w');
                fprintf(fid, '%i\r\n', HDR.ArtifactSelection);
                fclose(fid);
        end;

        % final test
        try
                HDR = sopen(HDR.FileName,'r');
                HDR = sclose(HDR);
        catch
                fprintf(2,'Error SAVE2BKR: saving file %s failed\n',HDR.FileName);
        end;
end;


function infoz(var1)
    % make an info window for various routines
    %
    %   A.Allmann

    global slapinfo p1

    report_this_filefun();

    if var1==1               %first call in P-Value window

        % This is the info window text
        %
        ttlStr='Help Window                                 ';

        hlpStr1=...
            ['                                                             '
            'No help available on this topic. Please                      '
            'consult the manual or contact stefan@giseis.alaska.edu       '
            '                                                             '];

    elseif var1 == 2                 % second help message

        ttlStr='Stress Tensor Inversion Resuls              ';

        hlpStr1=...
            ['                                                             '
            'This is a polar projection of the Stress Tensor Inversion    '
            'results, using Gepards and Forsyths (1984) technique.        '
            'Show in black are the best fitting stress directions,        '
            'The red. yellow and blue symbols indicate the 95% confidence '
            'region. The histogrom in the corner shows the distribution   '
            'of R values in this data-set.                                '
            '                                                             '];

    end

    % display the message
    zmaphelp(ttlStr,hlpStr1)
end


classdef dmce_reserve_zone_mpc2 < mp.dmc_element % & mp.dmce_reserves
%MP.DMCE_RESERVE_ZONE_MPC2  Data model converter for reserve zones for MATPOWER case v2.

%   MATPOWER
%   Copyright (c) 2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%     properties
%     end     %% properties

    methods
        function name = name(obj)
            name = 'reserve_zone';
        end

        function df = data_field(obj)
            df = 'reserves';
        end

        function s = data_subs(obj)
            s = struct('type', {'.', '.'}, 'subs', {obj.data_field(), 'zones'});
        end

        function vmap = table_var_map(obj, dme, mpc)
            vmap = table_var_map@mp.dmc_element(obj, dme, mpc);

            import_req_fcn   = @(a, b, c, d)import_req(a, b, c, d);
            import_zones_fcn = @(a, b, c, d)import_zones(a, b, c, d);

            %% mapping for each name, default is {'col', []}
            vmap.uid        = {'IDs'};      %% consecutive IDs, starting at 1
            vmap.name       = {'cell', ''}; %% empty char
            vmap.status     = {'num', 1};   %% ones
            vmap.source_uid = {'cell', ''}; %% empty char
            vmap.req        = {'fcn', import_req_fcn};
            vmap.zones      = {'fcn', import_zones_fcn};
            vmap.prc        = {'num', 0};   %% zeros
        end

        function val = import_req(obj, mpc, spec, vn)
            val = mpc.reserves.req;
        end

        function val = import_zones(obj, mpc, spec, vn)
            val = mpc.reserves.zones;
        end
    end     %% methods
end         %% classdef


% File: VisualizeDataset.m
%
% Copyright (C) Daphne Koller, Stanford Univerity, 2012

function VisualizeDataset(Dataset)

figure
for i=1:size(Dataset,1)
    img = ShowPose(reshape(Dataset(i,:,:), [10 3]));
    imshow(img);
    pause(0.3);
end


classdef prtActionWrapperMil < prtAction

    properties (SetAccess = private)
        % Descriptive name of prtAction object.
        name = 'MIL Wrapper';

        % Shortened name for the prtAction object.
        nameAbbreviation = 'MILWrap';
    end

    properties (SetAccess = protected)
        % Specifies if the prtAction requires a labeled dataSet
        isSupervised

        % Indicates whether or not cross-validation is a valid operation
        isCrossValidateValid
    end

    properties (Dependent)
        theAction; % a prtActionObject
    end
    properties (SetAccess = private,Hidden)
        theAction_ = prtPreProcPca;
    end

    methods
        function self = prtActionWrapperMil(varargin)
            self = prtUtilAssignStringValuePairs(self,varargin{:});
            self.isSupervised = self.theAction.isSupervised;
            self.isCrossValidateValid = self.theAction.isCrossValidateValid;
        end

        function val = get.theAction(self)
            val = self.theAction_;
        end

        function self = set.theAction(self,action)

            if isa(action,'prtAction');
                self.theAction_ = action;

                self.isSupervised = self.theAction.isSupervised;
                self.isCrossValidateValid = self.theAction.isCrossValidateValid;

            else
                error('prt:prtActionWrapperMil','theAction must be a subclass of prtAction, provided action was a %s',class(action));
            end
        end
    end

    methods (Access = protected, Hidden = true)
        % prtAction.trainAction() - Primary method for training a prtAction
        %   self = prtAction.trainAction(self,DataSet)
        function self = trainAction(self, dsMil)

            ds = prtDataSetClass(dsMil.expandedData,dsMil.expandedTargets);
            self.theAction = self.theAction.train(ds);

        end
        % prtAction.runAction() - Primary method for evaluating a prtAction
        %   DataSet = runAction(self, DataSet)
        function dsMil = runAction(self, dsMil)

            ds = prtDataSetClass(dsMil.expandedData,dsMil.expandedTargets);
            dsOut = self.theAction.run(ds);
            dsMil = dsMil.fromPrtDataSetClassData(dsOut);

        end
    end
end


function title = p00_title ( problem )

%*****************************************************************************80
%
%% P00_TITLE returns a title for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 October 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer PROBLEM, the number of the problem.
%
%    Output, string TITLE, a title for the problem.
%
  if ( problem == 1 )
    title = p01_title ( );
  elseif ( problem == 2 )
    title = p02_title ( );
  elseif ( problem == 3 )
    title = p03_title ( );
  elseif ( problem == 4 )
    title = p04_title ( );
  elseif ( problem == 5 )
    title = p05_title ( );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_TITLE - Fatal error!\n' );
    fprintf ( 1, '  Illegal value of PROBLEM = %d', problem );
    error ( 'P00_TITLE - Fatal error!' );
  end

  return
end


%% NOMAD Install for OPTI Toolbox

% This file will help you compile NOMAD for use with MATLAB.

% My build platform:
% - Windows 8 x64
% - Visual Studio 2012

% To recompile you will need to get / do the following:

% 1) Get NOMAD
% NOMAD is available from http://www.gerad.ca/NOMAD/PHP_Forms/Download.php.
% Complete the download form then download the latest version. Once you
% have installed NOMAD, locate the /src/ directory.

% 2) Compile NOMAD
% The easiest way to compile NOMAD is to use the Visual Studio Project
% Builder included with OPTI. Use the following commands, substituting the
% required path on your computer:

% %% Visual Studio Builder Commands
% path = 'full path to NOMAD here'; %e.g. 'C:\Solvers\NOMAD'
% sdir = [path '\src'];
% name = 'libnomad';
% opts.exPP = {'_CRT_SECURE_NO_WARNINGS'};
% opts.exclude = 'nomad.cpp';
% VS_WriteProj(sdir,name,[],opts)
% %%

% Once complete, you will have a directory called NOMAD\libnomad. Open the
% Visual Studio 2012 project file, then complete the following steps:
%   a) In defines.hpp change the following:
%       - line 194 change MAX_DIMENSION to 5000.
%   b) Build a Win32 or x64 Release to compile the code.
%   c) Copy the generated .lib file to the following folder:
%
%   OPTI/Solvers/nomad/Source/lib/win32 or win64
%
%   And rename it to libnomad.lib.
%
%   You will also need to copy all header files from NOMAD/src to
%   the following folder:
%
%   OPTI/Solvers/nomad/Source/Include

% 3) NOMAD MEX Interface
% % The NOMAD MEX Interface is a simple MEX interface I wrote to use NOMAD.
% Note the MEX interface contains two versions, a GERAD version (for the
% authors of NOMAD) and an OPTI version (for easier integration into this
% toolbox). By default the GERAD version is built, however to build the
% OPTI version simply add the preprocessor "OPTI_VERSION" to the compiler.

% 4) Compile the MEX File
% The code below will automatically include all required libraries and
% directories to build the NOMAD MEX file. Once you have completed all the
% above steps, simply run this file to compile NOMAD! You MUST BE in the
% base directory of OPTI!

clear nomad

% Get Arch Dependent Library Path
libdir = opti_GetLibPath();

fprintf('\n------------------------------------------------\n');
fprintf('NOMAD MEX FILE INSTALL\n\n');

%Get NOMAD Libraries
post = [' -IInclude -L' libdir ' -llibnomad -llibut -output nomad -DOPTI_VERSION'];

%CD to Source Directory
cdir = cd;
cd 'Solvers/nomad/Source';

%Compile & Move
pre = 'mex -v -largeArrayDims nomadmex.cpp';
try
    eval([pre post])
    movefile(['nomad.' mexext],'../','f')
    fprintf('Done!\n');
catch ME
    cd(cdir);
    error('opti:nomad','Error Compiling NOMAD!\n%s',ME.message);
end
cd(cdir);
fprintf('------------------------------------------------\n');


function ground_truth = load_groundtruth(base_path, video)

%see if there's a suffix, specifying one of multiple targets, for
%example the dot and number in 'Jogging.1' or 'Jogging.2'.
if numel(video) >= 2 && video(end-1) == '.' && ~isnan(str2double(video(end))),
    suffix = video(end-1:end);  %remember the suffix
    video = video(1:end-2);  %remove it from the video name
else
    suffix = '';
end

%full path to the video's files
if base_path(end) ~= '/' && base_path(end) ~= '\',
    base_path(end+1) = '/';
end
video_path = [base_path video '/'];

%try to load ground truth from text file (Benchmark's format)
filename = [video_path 'groundtruth_rect' suffix '.txt'];
f = fopen(filename);
assert(f ~= -1, ['No initial position or ground truth to load ("' filename '").'])

%the format is [x, y, width, height]
try
    ground_truth = textscan(f, '%f,%f,%f,%f', 'ReturnOnError',false);
catch  %#ok, try different format (no commas)
    frewind(f);
    ground_truth = textscan(f, '%f %f %f %f');
end
ground_truth = cat(2, ground_truth{:});
fclose(f);

end


function tracking_env()
addpath('../matconvnet/matlab');
run('vl_setupnn.m') ;
fftw('planner','patient');
end


function models = esvm_initialize_exemplars(e_set, params, ...
                                            models_name)

% Initialize script which writes out initial model files for all
% exemplars in an exemplar stream e_set (see get_pascal_stream)
% NOTE: this function is parallelizable (and dalalizable!)
%
% INPUTS:
% params.dataset_params: the parameters of the current dataset
% e_set: the exemplar stream set which contains
%   e_set{i}.I, e_set{i}.cls, e_set{i}.objectid, e_set{i}.bbox
% models_name: model name
% init_params: a structure of initialization parameters
% init_params.init_function: a function which takes as input (I,bbox,params)
%   and returns a model structure [if not specified, then just dump
%   out names of resulting files]
%
% OUTPUTS:
% allfiles: The names of all outputs (which are .mat model files
%   containing the initialized exemplars)
%
% Copyright (C) 2011-12 by Tomasz Malisiewicz
% All rights reserved.
%
% This file is part of the Exemplar-SVM library and is made
% available under the terms of the MIT license (see COPYING file).
% Project homepage: https://github.com/quantombone/exemplarsvm

% DTstring = '';
% if dalalmode == 1
%   %Find the best window size from taking statistics over all
%   %training instances of matching class
%   hg_size = get_hg_size(cls);
%   DTstring = '-dt';
% elseif dalalmode == 2
%   hg_size = [8 8];
%   DTstring = '-gt';
% end

%if (dalalmode == 1) || (dalalmode == 2)
%  %Do the dalal-triggs anisotropic warping initialization
%  model = initialize_model_dt(I,bbox,SBIN,hg_size);
%else

if isfield(params,'dataset_params') && ...
      isfield(params.dataset_params,'localdir') && ...
      length(params.dataset_params.localdir)>0
  CACHE_FILE = 1;
else
  CACHE_FILE = 0;
  params.dataset_params.localdir = '';
end

if ~exist('models_name','var')
  models_name = '';
end

cache_dir =  ...
    sprintf('%s/models/',params.dataset_params.localdir);

cache_file = ...
    sprintf('%s/%s.mat',cache_dir,models_name);

if CACHE_FILE ==1 && fileexists(cache_file)
  models = load(cache_file);
  models = models.models;
  return;
end

results_directory = ...
    sprintf('%s/models/%s/',params.dataset_params.localdir, ...
            models_name);

if CACHE_FILE==1 && ~exist(results_directory,'dir')
  fprintf(1,'Making directory %s\n',results_directory);
  mkdir(results_directory);
end

%fprintf(1,'Writing %d Exemplars to directory %s\n',length(e_set),...
%        results_directory);

%Randomize creation order
if CACHE_FILE == 1
  myRandomize;
  rrr = randperm(length(e_set));

  if (params.dataset_params.display == 1)
    rrr = 1:length(rrr);
  end
  e_set = e_set(rrr);
end

%Create an array of all final file names
allfiles = cell(length(e_set), 1);

for i = 1:length(e_set)
  cls = e_set{i}.cls;
  objectid = e_set{i}.objectid;
  bbox = e_set{i}.bbox;
  curid = e_set{i}.curid;

  %[tmp,curid,tmp] = fileparts(e_set{i}.I);
  %filer = sprintf('%s/%s.%d.%s.mat',...
  %                results_directory, curid, objectid, cls);

  filer = sprintf('%s/%s',results_directory, e_set{i}.filer);

  allfiles{i} = filer;
  if ~isfield(params,'init_params')
    error('Warning, cannot initialize without params.init_params\n');
  end
  filerlock = [filer '.lock'];

  if CACHE_FILE == 1
    if fileexists(filer) || (mymkdir_dist(filerlock)==0)
      continue
    end
  end
  gt_box = bbox;
  fprintf(1,'.');

  I = convert_to_I(e_set{i}.I);

  %Call the init function which is a mapping from (I,bbox) to (model)
  [model] = params.init_params.init_function(I, bbox, params.init_params);

  clear m
  m.model = model;

  %Save filename (or original image)
  m.I = e_set{i}.I;
  m.curid = curid;
  m.objectid = objectid;
  m.cls = cls;
  m.gt_box = gt_box;

  m.sizeI = size(I);
  m.models_name = models_name;
  m.name = sprintf('%s.%d.%s',m.curid,m.objectid,m.cls);

  if CACHE_FILE == 1
    save(filer,'m');
    if exist(filerlock,'dir')
      rmdir(filerlock);
    end
  else
    allfiles{i} = m;
  end

  % %Print the bounding box overlap between the initial window and
  % %the final window
  % finalos = getosmatrix_bb(m.gt_box, m.model.bb(1,:));
  % fprintf(1,'Final OS is %.3f\n', ...
  %         finalos);

  % fprintf(1,'Final hg_size is %d %d\n',...
  %         m.model.hg_size(1), m.model.hg_size(2));

  %Show the initialized exemplars
  if params.dataset_params.display == 1
    esvm_show_exemplar_frames({m}, 1, params.dataset_params);
    drawnow
    snapnow;
  end
end

if CACHE_FILE == 0
  models = allfiles;
  return;
end

%sort files so they are in alphabetical order
[allfiles, bb] = sort(allfiles);

%Load all of the initialized exemplars
CACHE_FILE = 1;

if length(models_name) == 0
  CACHE_FILE = 0;
end

STRIP_FILE = 0;
DELETE_INITIAL = 0;

models = esvm_load_models(params.dataset_params, models_name, allfiles, ...
                          CACHE_FILE, STRIP_FILE, DELETE_INITIAL);

fprintf(1,'\n   --- Done initializing %d exemplars\n',length(e_set));


% pop_writeeeg - write EEGLAB dataset to disk in EDF/GDF or BDF format
%
% pop_writeeeg( EEG ) % pops up a window
% pop_writeeeg( EEG, filename, 'key', 'val' )
%
% Inputs:
%  EEG        - EEGLAB dataset
%  filename   - [string] filename
%
% Optional keys (same as writeeeg):
%  'TYPE'         - ['GDF'|'EDF'|'BDF'|'CFWB'|'CNT'] file format for writing
%                   default is 'EDF'.
%  See writeeeg for more information
%
% Author: Arnaud Delorme, SCCN, UCSD/CERCO, 2009
%         Based on BIOSIG, sopen and swrite

% Copyright (C) 22 March 2002 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 [command] = pop_writeeeg(EEG, filename, varargin)
command = '';

% enforce use the str2double of Biosig
biosigpathfirst

% Check for BIOSIG Toolbox
global PLUGINLIST
 if ~isempty(PLUGINLIST) && ~any(strcmpi({PLUGINLIST.plugin}','biosig'))
     fprintf(2,'pop_writeeeg error: This function requires you to install BIOSIG Toolbox plug-in. \n');
     return;
 elseif isempty(PLUGINLIST)
     warning('pop_writeeeg check for BIOSIG Toolbox could not be performed.');
 end

if nargin < 2
    if EEG.trials > 1
        res = questdlg2( [ 'This dataset contains data epochs.' 10 'Do you want to export the concatenated' 10 'data epochs?' ], '', 'No', 'Yes', 'Yes');
        if strcmpi(res, 'No')
            return;
        end;
    end;

	% ask user
	[filename, filepath] = uiputfile('*.*', 'Enter a file name -- pop_writeeeg()');
	if filename == 0 return; end;
	filename = fullfile(filepath,filename);

    % file format
    % -----------
    fileformats = { 'EDF' 'GDF' 'BDF' };
    uilist = { { 'style' 'text' 'String' 'File format' } ...
               { 'style' 'listbox' 'string' strvcat(fileformats) 'value' 1 } };
    geom = [1 1];
    result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''pop_writeeeg'')', ...
                     'title', 'Write data using BIOSIG -- pop_writeeeg()', 'geomvert', [1 2.5]);
    if length(result) == 0 return; end;

    options = { 'TYPE' fileformats{result{1}} };
else
    options = varargin;
end;

warning('off', 'MATLAB:intConvertNonIntVal');
if ~isempty(EEG.chanlocs)
    tmpchanlocs = EEG.chanlocs;
    writeeeg(filename, EEG.data(:,:), EEG.srate, 'label', { tmpchanlocs.labels }, 'EVENT', EEG.event, options{:});
else
    writeeeg(filename, EEG.data(:,:), EEG.srate, 'EVENT', EEG.event, options{:});
end;
warning('on', 'MATLAB:intConvertNonIntVal');

command = sprintf('pop_writeeeg(EEG, ''%s'', %s);', filename, vararg2str(options));
biosigpathlast


function destPath = compute_visual_feats(destPath, varargin)

	opts.gpus = 2 ;
  opts.limit = inf ;
  opts.clobber = false ;
  opts.batchSize = 128 ;
  opts.numEmotions = 8 ;
  opts.targetDataset = 'rml' ;
  opts.modelName = 'senet50-ferplus' ;
  opts = vl_argparse(opts, varargin) ;
  opts.imdbPath = fullfile(vl_rootnn, ...
             sprintf('data/xEmo18/%s_imdb/imdb.mat', opts.targetDataset)) ;

  if exist(destPath, 'file') && ~opts.clobber
    fprintf('found features at %s... skipping\n', destPath) ;
    return
  end

  switch opts.targetDataset
    case 'afew'
      opts.dataDir = fullfile(vl_rootnn, 'data/datasets/emotiw2016') ;
      getImdb = @(x) getAfewImdb(x, 'dropTracksWithNoDets', 1) ;
    case 'afew-6' % extracted at a stride of 6
      opts.dataDir = fullfile(vl_rootnn, 'data/datasets/emotiw2016') ;
      getImdb = @(x) getAfewImdb(x, 'dropTracksWithNoDets', 1, ...
                                 'subsampleStride', 6) ;
    case 'enterface'
      opts.dataDir = fullfile(vl_rootnn, 'data/datasets/enterface') ;
      getImdb = @(x) getEnterfaceImdb(x) ;
    case 'rml'
      opts.dataDir = fullfile(vl_rootnn, 'data/datasets/rml') ;
      getImdb = @(x) getRmlImdb(x) ;
    otherwise, error('unknown dataset %s\n', opts.targetDataset) ;
  end

  % work relative to audio files
  if exist(opts.imdbPath, 'file')
    fprintf('loading imdb from memory...') ; tic ;
    imdb = load(opts.imdbPath) ;
    fprintf('done in %g s\n', toc) ;
  else
    fprintf('building imdb...') ; tic ;
    imdb = getImdb(opts) ;
    mkdir(fileparts(opts.imdbPath)) ;
    save(opts.imdbPath, '-struct', 'imdb') ; % avoid compression if poss
    fprintf('done in %g s\n', toc) ;
  end

  [dag, pretrained] = ferPlusZoo(opts.modelName) ;
  assert(pretrained, 'loaded incorrect model') ;

  % remove losses
  lossLayers = arrayfun(@(x) isa(x.block, 'dagnn.Loss'), dag.layers) ;
  removables = {dag.layers(lossLayers).name} ;
  for ii = 1:numel(removables)
    dag.removeLayer(removables{ii}) ;
  end
	dag.mode = 'test' ;
	if numel(opts.gpus), gpuDevice(opts.gpus) ; dag.move('gpu') ; end

	inVars = dag.getInputs() ;
	assert(numel(inVars) == 1, 'too many inputs') ;

  % flatten frames into list, and keep track of the mapping to cells
  frames = zs_flattenCell(imdb.tracks.paths) ;
  frameIdx = arrayfun(@(x) ...
                     {x*ones(1, numel(imdb.tracks.paths{x}))}, ...
                     1:numel(imdb.tracks.paths)) ;
  frameIdx = [frameIdx{:}] ;
  assert(numel(frames) == numel(frameIdx), 'incorrect idx pairing') ;

  % compute for first `limit` tracks
  firstId = frameIdx(1) ; % use first in partition as offset
  numKeep = sum(frameIdx <= firstId + opts.limit) ; % number of tracks
  numIms = min(numel(frames), numKeep) ;
  meta = dag.meta ;
	inVars = dag.getInputs() ;
	assert(numel(inVars) == 1, 'too many inputs') ;

  logits = zeros(numIms, opts.numEmotions, 'single') ;

	fprintf('processing images with %s\n', opts.modelName) ;
	for ii = 1:opts.batchSize:numIms
		tic ;
		batchStart = ii ;
		batchEnd = min(batchStart+opts.batchSize-1, numIms) ;
		batch = batchStart:batchEnd ;
    imPaths = fullfile(opts.dataDir, frames(batch)) ;
		data = getImageBatch(imPaths, dag, meta) ;
		dag.eval({inVars{1}, data}) ;
		out = gather(squeeze(dag.vars(end).value)) ; % risky use of end variable
		logits(batch, :) = out' ;
		rate = numel(batch) / toc ;
    etaStr = zs_eta(rate, ii, numIms) ;
		fprintf(['processed image %d/%d at (%.3f Hz) ' ...
             '(%.3f%% complete) (eta:%s)\n'], ...
             ii, numIms, rate, 100 * ii/numIms, etaStr) ;
	end

  % save the logits alongside the frames for easier processing during training
  keptIdx = frameIdx(1:numIms) ; msg = 'unexpected indices' ;
  assert(isequal(1:numel(unique(keptIdx)), unique(keptIdx)), msg) ;
  numKeptTracks = numel(unique(keptIdx)) ;

  faceLogits = cell(1, numKeptTracks) ;
  for ii = 1:numKeptTracks
    fprintf('splitting logits into cells (%d/%d)\n', ii, numKeptTracks) ;
    sel = frameIdx == ii ;
    faceLogits(ii) = {logits(sel,:)} ;
  end

	fprintf('saving features to %s...', destPath) ; tic ;
  imdb.faceLogits = faceLogits ;
	if ~exist(fileparts(destPath), 'dir')
		zs_mkdirRec(fileparts(destPath)) ;
	end
	save(destPath, '-struct', 'imdb') ;
	fprintf('done in %g (s)\n', toc) ;
	if numel(opts.gpus), dag.move('cpu') ; end
end

% --------------------------------------------------------
function data = getImageBatch(imagePaths, dag, meta)
% --------------------------------------------------------
  numThreads = 10 ;
  opts.prefetch = false ; % can optimise this
  imageSize = meta.normalization.imageSize(1:2) ;

  % Afew is already tightly cropped
  args{1} = {imagePaths, ...
             'NumThreads', numThreads, ...
             'Pack', ...
             'Interpolation', 'bilinear', ... % bilinear to reproduce trainig
             'Resize', imageSize, ...
             'CropLocation', 'center'} ; % centre crop for testing
  args = horzcat(args{:}) ;

  if opts.prefetch
    vl_imreadjpeg(args{:}, 'prefetch') ;
    data = [] ;
  else
    data = vl_imreadjpeg(args{:}) ;
  end

  % throw away color, since it was not used during training
	data = uint8(data{1}) ;
	data_ = permute(data, [1 2 4 3]) ; sz = size(data_) ;
	data_ = reshape(data_, sz(1), sz(2) * sz(3), 3) ;
	gray = rgb2gray(data_) ;
	gray = single(reshape(gray, sz(1), sz(2), 1, [])) ;
	data = normalizeFace(gray, dag) ;
	if strcmp(dag.device, 'gpu'), data = gpuArray(data) ; end
end

% --------------------------------------------------------------------
function face = normalizeFace(greyFace, dag)
% --------------------------------------------------------------------
  greyFace = imresize(greyFace, dag.meta.normalization.imageSize(1:2)) ;
  face = repmat(greyFace, [1 1 3]) ;

  % handle average image consisting of color channel averages
  avgIm = reshape(dag.meta.normalization.averageImage, 1, 1, 3) ;
  face = bsxfun(@minus, face, avgIm) ;
end


classdef SettingsHomogenizedVarComputerFromInterpolation < ....
        SettingsHomogenizedVarComputer

    properties (Access = protected)
        defaultParamsName = 'paramsHomogenizedVarComputerFromInterpolation.json'
    end

    properties (Access = public)
        interpolation
        typeOfMaterial
        constitutiveProperties
        nelem
        ptype
        interpolationSettings
    end

    methods (Access = public)

        function obj = SettingsHomogenizedVarComputerFromInterpolation(varargin)
            if nargin == 1
                obj.loadParams(varargin{1})
            end
            obj.init();
        end

    end

    methods (Access = private)

        function init(obj)
            obj.initConstitutiveProperties();
            obj.initInterpolationSettings();
        end

        function initConstitutiveProperties(obj)
            s = obj.constitutiveProperties;
            obj.constitutiveProperties = SettingsConstitutiveProperties(s);
        end

        function initInterpolationSettings(obj)
            s.interpolation           = obj.interpolation;
            s.dim                     = obj.dim;
            s.typeOfMaterial          = obj.typeOfMaterial;
            s.constitutiveProperties  = obj.constitutiveProperties;
            obj.interpolationSettings = SettingsInterpolation(s);
        end

    end

end


function varargout = process_matlab_eval( varargin )
% PROCESS_MATLAB_EVAL: Evaluate a matlab script.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2013-2015

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Run Matlab command';
    sProcess.FileTag     = 'matlab';
    sProcess.Category    = 'Filter';
    sProcess.SubGroup    = 'Pre-process';
    sProcess.Index       = 80;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/TutUserProcess#Alternative';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data', 'results', 'timefreq', 'raw', 'matrix'};
    sProcess.OutputTypes = {'data', 'results', 'timefreq', 'raw', 'matrix'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;
    sProcess.isSeparator = 1;
    % Default values for some options
    sProcess.isSourceAbsolute = -1;
    sProcess.processDim  = [];
    % === Matlab command
    sProcess.options.matlab.Comment = 'Type your Matlab script below: ';
    sProcess.options.matlab.Type    = 'textarea';
    sProcess.options.matlab.Value   = ['% Available variables: Data, TimeVector' 10 10 ...
                                       'Data = Data;' 10];
    % === Sensor types
    sProcess.options.sensortypes.Comment = 'Sensor types or names (empty=all): ';
    sProcess.options.sensortypes.Type    = 'text';
    sProcess.options.sensortypes.Value   = 'MEG, EEG';
    sProcess.options.sensortypes.InputTypes = {'data', 'raw'};
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function sInput = Run(sProcess, sInput) %#ok<DEFNU>
    % Available variables
    Data = sInput.A;
    TimeVector = sInput.TimeVector;
    Comment = sInput.Comment;
    % Evaluate Matlab code
    try
        eval(sProcess.options.matlab.Value);
    catch
        % Get error message
        e = lasterror();
        if ~isempty(e)
            % Remove HTML tags
            errMsg = str_striptag(e.message);
            % Strip "Error:"
            errMsg = strrep(errMsg, 'Error: ', '');
            % Strip first line
            iNewLine = find(errMsg == 10);
            if ~isempty(iNewLine)
                errMsg = errMsg(iNewLine(1)+1:end);
            end
            errMsg = ['Error while executing Matlab command:' 10 errMsg];
        else
            errMsg = 'Error while executing Matlab command.';
        end
        % Report error
        bst_report('Error', sProcess, sInput, errMsg);
        sInput = [];
        return;
    end
    % Check if time was modified
    if (length(TimeVector) ~= length(sInput.TimeVector))
        % Not allowed for only a few sensors
        if strcmpi(sInput.FileType, 'data') && isfield(sProcess.options, 'sensortypes') && isfield(sProcess.options.sensortypes, 'Value') && ~isempty(sProcess.options.sensortypes.Value)
            sInput = [];
            bst_report('Error', sProcess, sInput, ...
                ['This process can modify the time definition only if all the channels are processed at once.' 10 ...
                 'Either leave the option "Sensor types or names" empty to process all the channels at once,' 10 ...
                 'or keep the number of time points of the original file.']);
            return;
        % Not allowed for raw files
        elseif strcmpi(sInput.FileType, 'raw')
            sInput = [];
            bst_report('Error', sProcess, sInput, 'This process cannot modify the time definition of a continuous file.');
            return;
        end
    end
    % Report results
    sInput.A = Data;
    sInput.TimeVector = TimeVector;
    sInput.Comment = Comment;
    % Do not keep the Std field in the output
    if isfield(sInput, 'Std') && ~isempty(sInput.Std)
        sInput.Std = [];
    end
end


% Replace with the location you download the datasets to
data_dir = [getenv('USERPROFILE') '/Dropbox/AAM/test data/'];

% location of datasets, the datasets are acquired from http://ibug.doc.ic.ac.uk/resources/300-W/
dataset_locs = { [data_dir, '/AFW/'];
                 [data_dir, '/helen/trainset/'];
                 [data_dir, '/helen/testset/'];
                 [data_dir, '/ibug/'];
                 [data_dir, 'lfpw/testset/'];
                 [data_dir, '/lfpw/trainset/'];};

bb_locs = {[data_dir, '/Bounding Boxes/bounding_boxes_afw.mat'];
           [data_dir, '/Bounding Boxes/bounding_boxes_helen_trainset.mat'];
           [data_dir, '/Bounding Boxes/bounding_boxes_helen_testset.mat'];
           [data_dir, '/Bounding Boxes/bounding_boxes_ibug.mat'];
           [data_dir, '/Bounding Boxes/bounding_boxes_lfpw_testset.mat'];
           [data_dir, '/Bounding Boxes/bounding_boxes_lfpw_trainset.mat'];};

for d=1:numel(dataset_locs)

    load(bb_locs{d});

    for i=1:numel(bounding_boxes)
        img_name = bounding_boxes{i}.imgName;
        [~, name, ~] = fileparts(img_name);
%         image = imread([dataset_locs{d}, img_name]);
%         imshow(image);
        bbox = bounding_boxes{i}.bb_detector;

        f = fopen([dataset_locs{d}, name, '.txt'], 'w');

        fprintf(f, '%f %f %f %f\r\n', bbox(1), bbox(2), bbox(3), bbox(4));
        fclose(f);

%         rectangle('Position', [bbox(1), bbox(2), bbox(3)-bbox(1), bbox(4)-bbox(2)]);
%         drawnow expose
%         pause(0);
    end

end


function fmri_FFA_localizerGLMcontrasts

% LO Localizer scans processing code
%
% USER IMPORTANT!!!: Before running this script, make sure that all loloc
% scans have the correct annotation fields and scan groups (are grouped
% correctly). Otherwise, fmri_FFA_checkDataTypesForGLM will fail.
%
% 1. Set GLM parameters for all scans
% 2. Check LO localizer experiments for:
%    a. Datatype and scan numbers
%    b. Record parfiles
%    c. Make sure scan groupings are correct
% 3. Run GLM for LO localizer experiments
% 4. Run contrasts for the LO localizer experiments
%
% Calls the functions:
% * fmri_FFA_setGLMparams (subfunction)
% * fmri_FFA_checkDataTypesForGLM
% * fmri_FFA_computeContrastsLocalizer
%
%
% DY 06/05/2008
% Modified 06/18/2008: there are calls to er_setParams and saveSessions all
% over the place, which results in the params for the MotionComp_RefScan1
% being changed for the worse. I'm not sure how to efficiently prevent this
% from happening, so instead, I let it happen, and just fix the ANNOTATION
% and PARFILE fields at the end, since accuracy here is important.
%
% Code taken from fmri_FFA_motionCompFix

clear all

% Set directory and subject list
% Alternatively: subs = {'sess1','sess2','sess3',...};
if ispc
    fmriDir = 'W:\projects\Kids\fmri\localizer\';
    codeDir = 'W:\projects\Kids\fmri\code';
else
    fmriDir = '/biac2/kgs/projects/Kids/fmri/localizer/';
    codeDir = '/biac2/kgs/projects/Kids/fmri/code/';
end
cd(fmriDir); s=dir('*0*'); subs={s.name}; addpath(codeDir);

% Start a log text file to document successes and failures in preprocessing
dateAndTime=datestr(now); dateAndTime(12)='_'; dateAndTime(15)='h';dateAndTime(18)='m';
logDir=fullfile(fmriDir,'logs');
if ~isdir(logDir), mkdir(logDir), end;
logFile = fullfile(fmriDir,'logs',['LO_Log_' dateAndTime '.txt']);
fid=fopen(logFile,'w');
[junk,logFileName]=fileparts(logFile)
scriptName = 'fmri_FFA_localizerGLMcontrasts.m';
startTime = clock;

% 1. Set GLM parameters
params=fmri_FFA_setGLMparams(fid,logFileName,scriptName); % Subfunction within this script

for ii=1:length(subs)

    % Get rid of all mrVista globals in workspace. Put this at the top,
    % just in case we break from the rest of the loop.
    clear dataTYPES mrSESSION vANATOMYPATH HOMEDIR hI newDt newScan

    thisDir = fullfile(fmriDir,subs{ii}); cd(thisDir);
    fprintf(fid,'\n ------------------------------------------ \n');
    fprintf(fid,'Processing %s\n\n',thisDir);
    fprintf('Processing %s\n\n',thisDir);

    %% Check if the subject already has been processed by script (and thus
    %% should not be re-entered to this script). If they do, skip to the
    %% next subject by using CONTINUE.
    load mrSESSION.mat
    theglm=find(strcmp({dataTYPES.name},'GLMs'));
    if(~isempty(theglm)) && (isfield(dataTYPES(theglm).eventAnalysisParams,'logFile'))
        fprintf(fid,'Error: Subject already processed (has logFile field), skipping... \n\n');
        fprintf('Error: Subject already processed (has logFile field), skipping... \n\n');
        continue
    end

    %% 2a/b/c. Find datatype number for MotionComp_RefScan1, find scan
    %% numbers for lo localizer scans, record parfiles for these scans and
    %% make sure scan groupings are correct. If everything checks out,
    %% proceed with GLM. If not, SKIP THIS SUBJECT.
    [go,s1,s2]=fmri_FFA_checkDataTypesForGLM(fid,dataTYPES);
    %clear dataTYPES mrSESSION vANATOMYPATH

    % If there was a problem in step 3, skip GLM and proceed to next
    % subject
    if go==0
        continue

    %% 3. Otherwise, run GLM (to debug: fid=1)
    elseif go==1
        try
            % Initialize a hidden view of the 'inplane' data (like invoking
            % mrVista without a GUI, dataTYPES/etc in workspace)
            hI = initHiddenInplane(s1.mc, s1.scan);
            params.parfiles={s1.parfile, s2.parfile};
            er_setParams(hI, params); % write params as eventAnalysisParams fields
            tic; [hI, lo_scan] = applyGlm(hI,s1.mc,s1.scangroup,params);
            time=toc;
            fprintf(fid,'GLM COMPLETED -- dt %d, scan %d. Time: %d m %2.2f s \n\n',...
                hI.curDataType,lo_scan,floor(time/60),mod(time,60));
            fprintf('GLM COMPLETED -- dt %d, scan %d. Time: %d m %2.2f s \n\n',...
                hI.curDataType,lo_scan,floor(time/60),mod(time,60));
            glmOK=1;
        catch
            fprintf(fid,'FAILURE TO SUCCESSFULLY RUN GLM \n');
            fprintf('FAILURE TO SUCCESSFULLY RUN GLM \n');
            theerror=lasterror;
            fprintf(fid,'%s \n\n',theerror.message);
            fprintf('%s \n\n',theerror.message);
            glmOK=0;
        end

        %% 4. Compute contrast maps
        if glmOK

            try
                fmri_FFA_computeContrastsLocalizer(hI, lo_scan)
                fprintf(fid,'Computed contrasts using fmri_FFA_computeContrastsLocalizer \n');
                fprintf('Computed contrasts using fmri_FFA_computeContrastsLocalizer \n');
            catch
                fprintf(fid,'FAILURE TO SUCCESSFULLY COMPUTE CONTRASTS \n');
                fprintf('FAILURE TO SUCCESSFULLY COMPUTE CONTRASTS \n');
                theerror=lasterror;
                fprintf(fid,'%s \n\n',theerror.message);
                fprintf('%s \n\n',theerror.message);

            end
        end
    end

    % Fix the annotation and parfile fields for the MotionComp_RefScan
    % dataTYPE, since these are undesirably changed (collateral damage).
    dataTYPES(s1.mc).eventAnalysisParams(s1.scan).annotation='loloc_run1';
    dataTYPES(s2.mc).eventAnalysisParams(s2.scan).annotation='loloc_run2';

    par1=dataTYPES(s1.mc).scanParams(s1.scan).parfile;
    par2=dataTYPES(s2.mc).scanParams(s2.scan).parfile;

    dataTYPES(s1.mc).eventAnalysisParams(s1.scan).parfiles=par1;
    dataTYPES(s2.mc).eventAnalysisParams(s2.scan).parfiles=par2;
    save(fullfile(thisDir,'mrSESSION.mat'),'mrSESSION','dataTYPES', '-append');
    clear par1 par2

end

totalTime=etime(clock,startTime);

fprintf(fid,'\n ------------------------------------------ \n');
fprintf(fid,'Total running time for script: %f minutes \n',totalTime/60);
fprintf('Total running time for script: %f minutes \n',totalTime/60);

fclose(fid); % close out the log file

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function params=fmri_FFA_setGLMparams(fid,logFileName,scriptName)

% Set GLM parameters: We set the PARAMS struct fields to the values on the
% wiki, which are further explained there. Also we print the values to the
% log. http://vpnl.stanford.edu/internal/wiki/index.php/ROIanalysis#GLMs

fprintf(fid,'\n ------------------------------------------ \n');
fprintf(fid,'\n GLM PARAMETERS \n');
fprintf(fid,' ------------------------------------------ \n');

params=er_defaultParams % Initialize param struct with defaults
p.al='params.alpha=0.0500'; eval(p.al); fprintf(fid,'%s \n',p.al);
p.at='params.ampType=''betas'''; eval(p.at); fprintf(fid,'%s \n',p.at);
p.an='params.annotation=''LO localizer Runs 1&2'''; eval(p.an); fprintf(fid,'%s \n',p.an);
p.ap='params.assignParfiles=0'; eval(p.ap); fprintf(fid,'%s \n',p.ap);
p.bp='params.bslPeriod=[-6 -5 -4 -3 -2 -1 0]'; eval(p.bp); fprintf(fid,'%s \n',p.bp);
p.dt='params.detrend=1'; eval(p.dt); fprintf(fid,'%s \n',p.dt);
p.df='params.detrendFrames=20;'; eval(p.df); fprintf(fid,'%s \n',p.df);
p.ea='params.eventAnalysis=1'; eval(p.ea); fprintf(fid,'%s \n',p.ea);
p.eb='params.eventsPerBlock=6'; eval(p.eb); fprintf(fid,'%s \n',p.eb);
p.fp='params.framePeriod=2'; eval(p.fp); fprintf(fid,'%s \n',p.fp);
p.gt='params.glmHRF=3'; eval(p.gt); fprintf(fid,'%s \n',p.gt);
p.gp='params.glmHRF_params=[6 16 1 1 6 0 24]'; eval(p.gp); fprintf(fid,'%s \n',p.gp);
p.gw='params.glmWhiten=0'; eval(p.gw); fprintf(fid,'%s \n',p.gw); % temporal autocorrelation
p.ic='params.inhomoCorrect=1'; eval(p.ic); fprintf(fid,'%s \n',p.ic);
p.lp='params.lowPassFilter=0'; eval(p.lp); fprintf(fid,'%s \n',p.lp);
p.nb='params.normBsl=1'; eval(p.nb); fprintf(fid,'%s \n',p.nb);
p.od='params.onsetDelta=0'; eval(p.od); fprintf(fid,'%s \n',p.od);
p.pf='params.parfiles='''''; eval(p.pf); fprintf(fid,'%s \n',p.pf); % fill in after checkDataTypes...
p.pp='params.peakPeriod=[4 5 6 7 8 9 10 11 12 13 14]'; eval(p.pp); fprintf(fid,'%s \n',p.pp);
p.sh='params.setHRFParams=0'; eval(p.sh); fprintf(fid,'%s \n',p.sh);
p.sc='params.snrConds=1'; eval(p.sc); fprintf(fid,'%s \n',p.sc);
p.tn='params.temporalNormalization=0'; eval(p.tn); fprintf(fid,'%s \n',p.tn);
p.tw='params.timeWindow=[-6:1:24]'; eval(p.tw); fprintf(fid,'%s \n',p.tw);
p.log=['params.logFile=''' logFileName '''']; eval(p.log); fprintf(fid,'%s \n',p.log)
p.script=['params.scriptName=''' scriptName '''']; eval(p.script); fprintf(fid,'%s \n',p.script)

% params.framePeriod = dataTYPES(dt).scanParams(scan).framePeriod;


function gr_test06 ( node_num, node_coordinates, edge_num, edge_nodes );

%*****************************************************************************80
%
%% GR_TEST06 tests GR_GRF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 January 2011
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GR_TEST06:\n' );
  fprintf ( 1, '  GR_GRF creates a GRF file from a graph.\n' );

  gr_grf ( node_num, node_coordinates, ...
    edge_num, edge_nodes );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Created the GRF file "graph.grf".\n' );

  return
end


filename='Cantilever_triangle_coarse';
  ptype = '';
method = '';
materialType = '';
initial_case = '';
cost = {''};
weights = '';
constraint = {''};
optimizer = '';
incrementFactor = 1;
designVariable = '';
filterType = '';

nsteps = 1;
Vfrac_final = '';
Perimeter_target = 1;
optimality_final = '';
constr_final = '';

Vfrac_initial = '';
optimality_initial = '';
constr_initial = '';

TOL.rho_plus = '';
TOL.rho_minus = '';
TOL.E_plus = '';
TOL.E_minus = '';
TOL.nu_plus = '';
TOL.nu_minus = '';

plotting = '';
showBC = '';
monitoring = '';
monitoring_interval = 5;

isOld = false;


function rxToggle(rx, nToggles, pauseForSecs);
% For mrRx: quickly toggle between a prescribed slice image and
% a reference slice for comparison.
%
% rxToggle(rx, [nToggles=3]);
%
%
% ras, 01/06.
% ras, 05/09: added nToggles as an input parameter.
if ~exist('rx', 'var') | isempty(rx),
    cfig = findobj('Tag', 'rxControlFig');
    rx = get(cfig, 'UserData');
end

if notDefined('pauseForSecs')
    pauseForSecs = 0.15;
end

if notDefined('nToggles')
	% # of times to alternate b/w interp and ref images
	nToggles = 3;
end

[interp ref] = rxGetComparisonImages(rx);

if ishandle(rx.ui.compareAxes)
    axes(rx.ui.compareAxes)
else
    figure('Name', 'mrRx: rxToggle');
end

rng = [min(interp(:)) max(interp(:))];

% get cur axis limits and keep them, in case user has zoomed image
x = get(gca, 'xlim');
y = get(gca, 'ylim');

for n = 1:nToggles
    imshow(ref, rng);
    xlim(x); ylim(y);
    pause(pauseForSecs);
    imshow(interp, rng);
    xlim(x); ylim(y);
    pause(pauseForSecs);
end

return


function fuse = spm_cfg_eeg_fuse
% configuration file for fusing M/EEG files
%_______________________________________________________________________
% Copyright (C) 2008-2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: spm_cfg_eeg_fuse.m 5377 2013-04-02 17:07:57Z vladimir $

rev = '$Rev: 5377 $';
D = cfg_files;
D.tag = 'D';
D.name = 'File Names';
D.filter = 'mat';
D.num = [2 Inf];
D.help = {'Select the M/EEG mat files.'};

prefix         = cfg_entry;
prefix.tag     = 'prefix';
prefix.name    = 'Filename Prefix';
prefix.help    = {'Specify the string to be prepended to the filenames of the fused dataset. Default prefix is ''u''.'};
prefix.strtype = 's';
prefix.num     = [1 Inf];
prefix.val     = {'u'};

fuse = cfg_exbranch;
fuse.tag = 'fuse';
fuse.name = 'Fusion';
fuse.val = {D, prefix};
fuse.help = {'Fuse EEG/MEG data.'};
fuse.prog = @eeg_fuse;
fuse.vout = @vout_eeg_fuse;
fuse.modality = {'EEG'};

function out = eeg_fuse(job)
% construct the S struct
S = job;
S.D = char(S.D);

out.D = spm_eeg_fuse(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};

function dep = vout_eeg_fuse(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Fused Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec   = cfg_findspec({{'strtype','e'}});

dep(2) = cfg_dep;
dep(2).sname = 'Fused Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec   = cfg_findspec({{'filter','mat'}});