function model = Learning_MLE_Basis_Stoc( Seqs, model, alg )

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Learning Hawkes processes via maximum likelihood estimation
% Different regularizers (low-rank, sparse, group sparse) of parameters and
% their combinations are considered, which are solved via StochasticADMM.
%
% Reference:
% Xu, Hongteng, Mehrdad Farajtabar, and Hongyuan Zha.
% "Learning Granger Causality for Hawkes Processes."
% International Conference on Machine Learning (ICML). 2016.
%
% Provider:
% Hongteng Xu @ Georgia Tech
% June. 10, 2017
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% initial
Aest = model.A;
muest = model.mu;
% KerFint = struct('dGK', []);
% KerF = struct('gij', []);

if alg.LowRank
    UL = zeros(size(Aest));
    ZL = Aest;
end

if alg.Sparse
    US = zeros(size(Aest));
    ZS = Aest;
end

if alg.GroupSparse
    UG = zeros(size(Aest));
    ZG = Aest;
end

D = size(Aest, 1);

if alg.storeLL
    model.LL = zeros(alg.epoch, 1);
end
if alg.storeErr
    model.err = zeros(alg.epoch, 3);
end

tic;
for o = 1:alg.epoch % the number of epoch for stochastic opt

    rho = alg.rho * (1.1^o);

    idx_seq = randperm(length(Seqs));
    if length(Seqs)<alg.seqbatch;
        N_seq_batch = 1;
        Ns = length(Seqs);
    else
        N_seq_batch = floor(length(Seqs)/alg.seqbatch);
        Ns = alg.seqbatch;
    end

    for n = 1:N_seq_batch

        % initial para
        Amu = zeros(D, 1);
        Bmu = Amu;

        CmatA = zeros(size(Aest));
        AmatA = CmatA;
        BmatA = CmatA;
        if alg.LowRank
            BmatA = BmatA + rho*(UL-ZL);
            AmatA = AmatA + rho;
        end
        if alg.Sparse
            BmatA = BmatA + rho*(US-ZS);
            AmatA = AmatA + rho;
        end
        if alg.GroupSparse
            BmatA = BmatA + rho*(UG-ZG);
            AmatA = AmatA + rho;
        end

        % E-step: evaluate the responsibility using the current parameters
        for ns = 1:Ns
            c = idx_seq(Ns*(n-1)+ns); % the id of current sequence

            if ~isempty(Seqs(c).Time)
                Time = Seqs(c).Time;
                Event = Seqs(c).Mark;
                Tstart = Seqs(c).Start;

                if isempty(alg.Tmax)
                    Tstop = Seqs(c).Stop;
                else
                    Tstop = alg.Tmax;
                    indt = Time < alg.Tmax;
                    Time = Time(indt);
                    Event = Event(indt);
                end

                Nc = length(Time);
%                 if o == 1
%                     KerFint(c).dGK = zeros(alg.historyL, length(model.landmark), Nc-1);
%                     KerF(c).gij = zeros(alg.historyL, length(model.landmark), Nc-1);
%                 end

                idx_event = randperm(Nc);
                if Nc<alg.eventbatch
                    N_event_batch = 1;
                    Ne = Nc;
                else
                    N_event_batch = alg.eventbatch;
                    Ne = floor(Nc/alg.eventbatch);
                end
                TimeNew = [Tstart, Time];
                for m = 1:N_event_batch
                    for ne = 1:Ne
                        i = idx_event(Ne*(m-1)+ne);
                        ui = Event(i);
                        ti = Time(i);
                        ti1 = TimeNew(i);

                        Amu = Amu + ti - ti1;

                        % calculate intensity
                        lambdai = muest(ui);
                        pii = muest(ui);
                        pij = [];

                        if i>1
                            start = max([1, i-alg.historyL]);
                            tj = Time(start:i-1);
                            uj = Event(start:i-1);

                            %if o==1 || isempty(KerF(c).gij)
                                dt = ti - tj;
                                dt1 = ti1 - tj;
                                gij = Kernel(dt, model);

                                %KerF(c).gij(1:length(dt),:,i-1) = gij;

                                GK = Kernel_Integration(dt, model);
                                GK1 = Kernel_Integration(dt1, model);
                                dGK = GK - GK1;
                                %KerFint(c).dGK(1:length(dt),:,i-1) = dGK;
                            %end

                            auiuj = Aest(uj, :, ui);
                            %pij = auiuj .* KerF(c).gij(1:length(uj),:,i-1);%
                            pij = auiuj .* gij;
                            lambdai = lambdai + sum(pij(:));
                        end
                        pii = pii./lambdai;

                        if i>1
                            pij = pij./lambdai;
                            if ~isempty(pij) && sum(pij(:))>0
                                for j = 1:length(uj)
                                    uuj = uj(j);
                                    CmatA(uuj,:,ui) = CmatA(uuj,:,ui) - pij(j,:);

                                    BmatA(uuj,:,:) = BmatA(uuj,:,:) + ...
                                        double(Aest(uuj,:,:)>0).*...
                                        repmat( dGK(j,:), [1,1,D] );
                                        %repmat( KerFint(c).dGK(j,:,i-1), [1,1,D] );
                                end
                            end
                        end
                        Bmu(ui) = Bmu(ui) + pii;

                    end
                end

%                 Amu = Amu + Tstop - Tstart;
%
%                 dT = Tstop - Time;
%                 GK = Kernel_Integration(dT, model);
%
%                 Nc = length(Time);
%                 idx_event = randperm(Nc);
%
%                 if Nc<alg.eventbatch
%                     N_event_batch = 1;
%                     Ne = Nc;
%                 else
%                     N_event_batch = alg.eventbatch;
%                     Ne = floor(Nc/alg.eventbatch);
%                 end
%
%                 for m = 1:N_event_batch
%                     for ne = 1:Ne
%                         i = idx_event(Ne*(m-1) + ne);
%                         ui = Event(i);
%
%                         BmatA(ui,:,:) = BmatA(ui,:,:)+...
%                             double(Aest(ui,:,:)>0).*repmat( GK(i,:), [1,1,D] );
%
%                         ti = Time(i);
%                         lambdai = muest(ui);
%                         pii = muest(ui);
%                         pij = [];
%
%                         if i>1
%                             start = max([1, i-alg.historyL]);
%                             tj = Time(start:i-1);
%                             uj = Event(start:i-1);
%
%                             dt = ti - tj;
%                             gij = Kernel(dt, model);
%                             auiuj = Aest(uj, :, ui);
%                             pij = auiuj .* gij;
%                             lambdai = lambdai + sum(pij(:));
%                         end
%
%                         pii = pii./lambdai;
%
%                         if i>1
%                             pij = pij./lambdai;
%                             if ~isempty(pij) && sum(pij(:))>0
%                                 for j = 1:length(uj)
%                                     uuj = uj(j);
%                                     CmatA(uuj,:,ui) = CmatA(uuj,:,ui) - pij(j,:);
%                                 end
%                             end
%                         end
%
%                         Bmu(ui) = Bmu(ui) + pii;
%                     end
%                 end
            else
                warning('Sequence %d is empty!', c)
            end
        end

        % M-step: update parameters
        mu = Bmu./Amu;
        if alg.Sparse==0 && alg.GroupSparse==0 && alg.LowRank==0
            A = -CmatA./BmatA;%( -BA+sqrt(BA.^2-4*AA*CA) )./(2*AA);
            A(isnan(A))=0;
            A(isinf(A))=0;
        else
            A = ( -BmatA + sqrt(BmatA.^2 - 4*AmatA.*CmatA) )./(2*AmatA);
            A(isnan(A))=0;
            A(isinf(A))=0;
        end

        % check convergence
        Err=sum(sum(sum(abs(A-Aest))))/sum(abs(Aest(:)));
        Aest = A;
        muest = mu;
        model.A = Aest;
        model.mu = muest;
        fprintf('Epoch=%d, EventBatch=%d, RelErr=%f, Time=%0.2fsec\n',...
                o, n, Err, toc);

        if Err<alg.thres || (o==alg.epoch && n==N_seq_batch)
            break;
        end
    end

    % calculate Loglikelihood
    if alg.storeLL
        Loglike = Loglike_Basis( Seqs, model, alg );
        model.LL(o) = Loglike;
    end
    % calculate error
    if alg.storeErr
        Err = zeros(1,3);
        Err(1) = norm(model.mu(:) - alg.truth.mu(:))/norm(alg.truth.mu(:));
        Err(2) = norm(model.A(:) - alg.truth.A(:))/norm(alg.truth.A(:));
        Err(3) = norm([model.mu(:); model.A(:)]-[alg.truth.mu(:); alg.truth.A(:)])...
            /norm([alg.truth.mu(:); alg.truth.A(:)]);
        model.err(o,:) = Err;
    end

    if alg.LowRank
        threshold = alg.alphaLR/rho;
        ZL = SoftThreshold_LR( Aest+UL, threshold );
        UL = UL + (Aest-ZL);
    end

    if alg.Sparse
        threshold = alg.alphaS/rho;
        ZS = SoftThreshold_S( Aest+US, threshold );
        US = US + (Aest-ZS);
    end

    if alg.GroupSparse
        threshold = alg.alphaGS/rho;
        ZG = SoftThreshold_GS( Aest+UG, threshold );
        UG = UG + (Aest-ZG);
    end

end


function NNF = sr_pass(imgTrg, imgSrcPyr, NNF, modelPlane, numIterLvl, opt)
%
% SR_PASS
%
% Nearest neighbor field estimation at the current level using the
% generalized PatchMatch algorithm
%
% Input:
%   - imgTrg:     target image
%   - imgSrcPyr:  source image pyramid
%   - NNF:        the current nearest neighbor field
%   - modelPlane: planar structure model
%   - numIterLvl: number of iterations at the current level
%   - opt:        parameters
% Output:
%   - NNF:        updated nearest neighbor field
% =========================================================================

% =========================================================================
% Compute the initial patch cost at the current level
% =========================================================================
% Prepare target patch
trgPatch = sr_prep_target_patch(imgTrg, opt.pSize);

% Prepare source patch
[srcPatch, srcPatchScale] = sr_prep_source_patch(imgSrcPyr, NNF.uvTformH.data, opt);
% Compute patch matching cost: appearance cost
[NNF.uvCost.data, NNF.uvBias.data] = sr_patch_cost_app(trgPatch, srcPatch, opt);
% Compute patch matching cost: scale cost
if(opt.useScaleCost)
    costScale = opt.lambdaScale*max(0, opt.scaleThres - srcPatchScale);
    NNF.uvCost.data = NNF.uvCost.data + costScale;
end
% Compute patch matching cost: plane compatibility cost
if(opt.usePlaneGuide)
    costPlane = sr_patch_cost_plane(modelPlane.mLogLPlaneProb, NNF.uvPlaneID.data, NNF.uvPix.ind, NNF.uvTformH.data(:,7:8));
    NNF.uvCost.data = NNF.uvCost.data + opt.lambdaPlane*costPlane;
end

% Update cost map
NNF.uvCost.map = sr_update_uvMap(NNF.uvCost.map, NNF.uvCost.data, NNF.uvPix.ind);

% Initialize update index map (for early termination)
% NNF.update.data = true(NNF.uvPix.numUvPix, 1);
% NNF.update.map  = true(NNF.imgH, NNF.imgW);

% Initialize visualization
if(opt.visFlag)
    uvTformMap    = zeros(NNF.imgH, NNF.imgW, 3, numIterLvl);
    uvCostMap     = zeros(NNF.imgH, NNF.imgW, numIterLvl);
    uvCostMapInit = NNF.uvCost.map;
    imgRecSet     = zeros(NNF.imgH, NNF.imgW, 3, numIterLvl);
end

% =========================================================================
% Update the nearest neighbor field using PatchMatch
% =========================================================================

for iter = 1 : numIterLvl
    [NNF, nUpdate] = sr_update_NNF(trgPatch, imgSrcPyr, NNF, modelPlane, opt);
    avgPatchCost = mean(NNF.uvCost.data);

    fprintf('    %3d\t%12d\t%12d\t%14f\n', iter, nUpdate(1), nUpdate(2), avgPatchCost);

    if(0)
        NNFVis = sr_vis_nnf(NNF, imgSrcPyr, opt);

%         uvTformMap(:,:,:, iter) = NNFVis.uvTfomMapVis;
%         uvCostMap(:,:, iter) = NNF.uvCost.map;
%         imgRecSet(:,:,:, iter) = imgRec;

%         figure(1);
%         subplot(2,4,1), imshow(imresize(imgSrcPyr{opt.origResLvl}, [NNF.imgH, NNF.imgW], 'bicubic'));
%         title('Current Image', 'fontsize', 16);
%         subplot(2,4,2), imshow(imgRec);
%         title('Super-resolution Image', 'fontsize', 16);
%         subplot(2,4,3), imshow(NNFVis.uvTformScaleVis);
%         title('Scale map', 'fontsize', 16);
%         subplot(2,4,4), imshow(NNFVis.uvTformRotVis); colormap jet
%         title('Rotation map', 'fontsize', 16);
%         subplot(2,4,5), imshow(NNFVis.uvTfomMapVis);
%         title('Nearest neighbor field', 'fontsize', 16);
%         subplot(2,4,6), imshow(NNFVis.uvPosMap); colormap jet
%         title('Position map', 'fontsize', 16);
%         subplot(2,4,7), imshow(NNFVis.uvCostMapVis); colormap jet
%         title('Cost map', 'fontsize', 16);
%         subplot(2,4,8), imshow(NNFVis.uvPlaneIDMapVis); colormap jet
%         title('Plane ID', 'fontsize', 16);
    end
end

% Visualization
if(opt.visFlag)
    resPath = 'result/nIter';
    if(~exist(resPath, 'dir'))
        mkdir(resPath);
    end
    imgID = opt.imgID;
    maxCost = max(uvCostMapInit(:));
    uvCostMap = uvCostMap/maxCost;

    uvCostMapInit = uvCostMapInit/maxCost;
    h2 = figure(2);
    imshow(uvCostMapInit); colormap jet;
    uvCostMapC = getframe(h2);
    imwrite(uvCostMapC.cdata,  ...
        fullfile(resPath, ['img_', num2str(imgID, '%03d'), '_costMap_iter_00.png']));

    % Position map
    uvPosMap = NNFVis.uvPosMap;

    imwrite(uvPosMap, fullfile(resPath, ...
        ['img_', num2str(imgID, '%03d'), '_uvPosMap.png']));

    for iter = 1: numIterLvl
        % Save uvTformMap
        imwrite(uvTformMap(:,:,:,iter), ...
            fullfile(resPath, ['img_', num2str(imgID, '%03d'),'_tformMap_iter_', num2str(iter, '%02d'), '.png']));

        % Save reconstructed image
        imwrite(imgRecSet(:,:,:,iter),  ...
            fullfile(resPath, ['img_', num2str(imgID, '%03d'),'_rec_iter_', num2str(iter, '%02d'), '.png']));

        % Save matching cost map
        h2 = figure(2);
        imshow(uvCostMap(:,:,iter)); colormap jet;
        uvCostMapC = getframe(h2);
        imwrite(uvCostMapC.cdata,  ...
            fullfile(resPath, ['img_', num2str(imgID, '%03d'), '_costMap_iter_', num2str(iter, '%02d'), '.png']));
    end
end

end


function gT = rbfwhiteKernGradX(kern, t1, t2)

% RBFWHITEKERNGRADX Gradient of RBF-WHITE kernel with respect to a point t.
% FORMAT
% DESC computes the gradient of the RBF-WHITE kernel with respect to the
% input positions.
% ARG kern : kernel structure for which gradients are being computed.
% ARG t1 : locations against which gradients are being computed.
% RETURN gT : the returned gradients. The gradients are returned in
% a matrix which is numData x numInputs x numData. Where numData is
% the number of data points and numInputs is the number of input
% dimensions in t1 (currently always one).
%
% FORMAT
% DESC computes the gradident of the RBF-WHITE kernel with respect to the
% input positions where both the row positions and column positions are
% provided separately.
% ARG kern : kernel structure for which gradients are being
% computed.
% ARG t1 : row locations against which gradients are being computed.
% ARG t2 : column locations against which gradients are being computed.
% RETURN gT : the returned gradients. The gradients are returned in
% a matrix which is numData2 x numInputs x numData1. Where numData1 is
% the number of data points in t1, numData2 is the number of data
% points in t2 and numInputs is the number of input dimensions in t1
% (currently always one).
%
% SEEALSO rbfwhiteKernParamInit, kernGradX, rbfwhiteKernDiagGradX
%
% COPYRIGHT : David Luengo, 2009

% KERN

error('rbfwhiteKernGradX not yet implemented.')


function [aTS, bTS] = cRecon(scanParams, fName, slice, compFlag, rotFlag, shifts)

% [aTS, bTS] = cRecon(scanParams, fName, slice, compFlag, shifts);
%
% Load and crop complex recon data.
% Returns pair of single-slice time-series arrays of size:
% ny x nx x nFrames -- aTS is real and bTS is imaginary;
% the latter is returned only if the optional compFlag
% input is set. Time-duration and spatial cropping are performed,
% but no trend removal. Inputs are pFile name [fName], and
% slice index [slice]. Optional input rotFlag performs a 90
% degree rotation to make functional images match inplanes;
% use MakeMovie.m or similar to check if necessary. Optional
% input shifts allows correction of fallback errors or similar.
% Assumes pwd points to valid session
% directory, and uses global mrSESSION.
%
% DBR 12/00

global mrSESSION
if ~exist('compFlag'), compFlag = 0; end
if ~exist('rotFlag'), rotFlag = 0; end

% Do recon, extract complex time series:
[aTS, bTS] = PaulyRecon(scanParams, fName, slice, compFlag, rotFlag);

% Remove junk frames:
f0 = mrSESSION.junkFirstFrames+1;
totalFrames = size(aTS, 1);
nFrames = totalFrames - f0 + 1;

aTS = aTS(f0:end, :, :);
x0 = mrSESSION.tseriesCrop(1, 1) + shifts(2);
xN = mrSESSION.tseriesCrop(2, 1) + shifts(2);
y0 = mrSESSION.tseriesCrop(1, 2) + shifts(1);
yN = mrSESSION.tseriesCrop(2, 2) + shifts(1);
% Crop in time/space and shuffle to standard t-series shape:
aTS = aTS(:, y0:yN, x0:xN);
aTS = reshape(aTS, nFrames, (yN-y0+1)*(xN-x0+1));
if compFlag
  bTS = bTS(f0:end, :, :);
  bTS = bTS(:, y0:yN, x0:xN);
  bTS = reshape(bTS, nFrames, (yN-y0+1)*(xN-x0+1));
end


function [ labels, valid_ids, vid_ids  ] = extract_SEMAINE_labels( SEMAINE_dir, recs, aus )
%EXTRACT_SEMAINE_LABELS Summary of this function goes here
%   Detailed explanation goes here

    % Get the right eaf file

    aus_SEMAINE = [2 12 17 25 28 45];

    inds_to_use = [];

    for i=1:numel(aus)

        inds_to_use = cat(1, inds_to_use, find(aus_SEMAINE == aus(i)));

    end

    labels = cell(numel(recs), 1);
    valid_ids = cell(numel(recs), 1);
    vid_ids = zeros(numel(recs), 2);

    for i=1:numel(recs)

        file = dir([SEMAINE_dir, '/', recs{i}, '/*.eaf']);

        vid_ids(i,:) = dlmread([SEMAINE_dir, '/', recs{i}, '.txt'], ' ');

        xml_file = [SEMAINE_dir, recs{i}, '\' file.name];
        [root_xml, name_xml, ~] = fileparts(xml_file);
        m_file = [root_xml, name_xml, '.mat'];

        if(~exist(m_file, 'file'))
            activations = ParseSEMAINEAnnotations([SEMAINE_dir, recs{i}, '\' file.name]);
            save(m_file, 'activations');
        else
            load(m_file);
        end
        if(size(activations,1) < vid_ids(i,2))
            vid_ids(i,2) = size(activations,1);
            if(vid_ids(i,2) > 2999)
                vid_ids(i,1) = vid_ids(i,2) - 2999;
            end
        end

        labels{i} = activations(vid_ids(i,1)+1:vid_ids(i,2), 1 + inds_to_use);

        % all indices in SEMAINE are valid
        valid_ids{i} = ones(size(labels{i},1),1);

    end

end


function i4_bset_test ( )

%*****************************************************************************80
%
%% I4_BSET_TEST tests I4_BSET.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  test_num = 2;
  i4_test = [ 101, -31 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST03225\n' );
  fprintf ( 1,'  I4_BSET sets a given bit to 0.\n' );

  for test = 1 : test_num

    i4 = i4_test(test);

    ivec = i4_to_bvec ( i4, 32 );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Working on I4 = %d\n', i4 );
    fprintf ( 1, '\n' );
    fprintf ( 1, '       Pos     Digit       I4_BSET\n' );
    fprintf ( 1, '\n' );

    for pos = 0 : 31

      j1 = i4_bset ( i4, pos );

      fprintf ( 1, '  %8d  %8d  %8d\n', pos, ivec(pos+1), j1 );

    end

  end

  return
end


%GETVALUEOFASSIGNMENT Gets the value of a variable assignment in a factor.
%
%   v = GETVALUEOFASSIGNMENT(F, A) returns the value of a variable assignment,
%   A, in factor F. The order of the variables in A are assumed to be the
%   same as the order in F.var.
%
%   v = GETVALUEOFASSIGNMENT(F, A, VO) gets the value of a variable assignment,
%   A, in factor F. The order of the variables in A are given by the vector VO.
%
%   See also SETVALUEOFASSIGNMENT

% Copyright (C) Daphne Koller, Stanford Univerity, 2012

function v = GetValueOfAssignment(F, A, VO)

if (nargin == 2),
    indx = AssignmentToIndex(A, F.card);
else
    map = zeros(length(F.var), 1);
    for i = 1:length(F.var),
        map(i) = find(VO == F.var(i));
    end;
    indx = AssignmentToIndex(A(map), F.card);
end;

v = F.val(indx);


function a = any(f, dim)
%ANY   True if any element of a SINGFUN is a nonzero number. ANY ignores
%      entries that are NaN (Not a Number).
%   ANY(F, DIM), where DIM is the dimension along which ANY is taken. Note
%   that array-valued SINGFUN is not supported. If DIM is 1, then ANY
%   returns a logical value which is TRUE if any element of F is nonzero.
%   If DIM is 2, ANY returns a SMOOTHFUN which takes the value 1 if F is
%   nonzero.  In this case, F must either be identically zero or have no
%   roots in its domain.  Otherwise, garbage is returned without warning.
%
%   ANY(F) is shorthand for ANY(F, 1).

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

% Parse inputs:
if ( nargin < 2 )
    dim = 1;
end

a = any(f.smoothPart, dim);

end


function [mesh labels labelsmap] = loadMesh(filestr)
% loads a mesh from filestr, supports obj or off

file = fopen( strtrim( filestr ), 'rt');
if file == -1
    warning(['Could not open mesh file: ' filestr]);
    mesh = [];
    return;
end
mesh.filename = strtrim( filestr );

if strcmp( filestr(end-3:end), '.off')
    line = strtrim(fgetl(file));
    skipline = 0;
    if strcmp(line, 'OFF')
        line = strtrim(fgetl(file));
        skipline = 2;
    else
        line = line(4:end);
        skipline = 1;
    end
    [token,line] = strtok(line);
    numverts = eval(token);
    [token,line] = strtok(line);
    numfaces = eval(token);
    mesh.V = zeros( 3, numverts, 'single' );
    mesh.F = zeros( 3, numfaces, 'single' );

    DATA = dlmread(filestr, ' ', skipline, 0);
    DATA = DATA(1:numverts+numfaces, :);
    mesh.V(1:3, 1:numverts) = DATA(1:numverts, 1:3)';
    mesh.F(1:3, 1:numfaces) = DATA(numverts+1:numverts+numfaces, 2:4)' + 1;
elseif strcmp( filestr(end-3:end), '.obj')
    mesh.V = zeros(3, 10^6, 'single');
    mesh.Nv = zeros(3, 10^6, 'single');
    mesh.F = zeros(3, 5*10^6, 'uint32');
    v = 0;
    f = 0;
    vn = 0;

    while(~feof(file))
        line_type = fscanf(file,'%c',2);
        switch line_type(1)
            case {'#', 'g'}
                fgets(file);
            case 'v'
                if line_type(2) == 'n'
                    vn = vn + 1;
                    normal  = fscanf(file, '%f%f%f');
                    mesh.Nv(:, vn) = normal;
                elseif isspace( line_type(2) )
                    v = v + 1;
                    point = fscanf(file, '%f%f%f');
                    mesh.V(:, v) = point;
                else
                    fgets(file);
                end
            case 'f'
                f = f + 1;
                face = fscanf(file, '%u%u%u');
                mesh.F(:, f) = face;
            otherwise
                if feof(file)
                    break;
                end
                if isspace(line_type(1))
                    fseek(file, -1, 'cof');
                    continue;
                end
                fprintf('last string read: %c%c %s', line_type(1), line_type(2), fgets(file));
                fclose(file);
                error('only triangular obj meshes are supported with vertices, normals and faces.');
        end
    end
    mesh.V = mesh.V(:, 1:v);
    mesh.F = mesh.F(:, 1:f);
    mesh.Nv = mesh.Nv(:, 1:v);
end

fclose(file);

end


function S = getStartFinish_StateVisits (vp,T,options)
% Decomposes a Viterbi path into a list of visits, each characterised by
% start time point and finish time point.
%
% S is a (N x K) cell, where N is the number of data time series
% (length of T) and K is the number of states; each element of S contains
% a matrix, which n-th row corresponds to the n-th visit to the
% corresponding state, with two columns (start and finish time points).
% The values of these matrices are in time points (not seconds), and are
% relative to the length of the state time courses, which will be a bit
% shorter if a MAR or a time-delay embedded observation model were used.
%
% T must be a vector with the length of each time series, and vp is the
% Viterbi path as returned by hmmmar or hmmdecode.
% The parameter 'options' must be the same than the one supplied to the
% hmmmar function for training.
%
% Author: Diego Vidaurre, OHBA, University of Oxford (2018)

if nargin<3, options = struct(); options.Fs = 1; options.downsample = 1; end
if ~isfield(options,'Fs'), options.Fs = 1; end
if ~isfield(options,'downsample'), options.downsample = options.Fs; end

if nargin < 2, T = length(vp); end

if iscell(T)
    if size(T,1) == 1, T = T'; end
    for i = 1:length(T)
        if size(T{i},1)==1, T{i} = T{i}'; end
    end
    T = cell2mat(T);
end
N = length(T);

r = 1;
if isfield(options,'downsample') && options.downsample>0
    r = (options.downsample/options.Fs);
end

if isfield(options,'order') && options.order > 0
    T = ceil(r * T);
    T = T - options.order;
elseif isfield(options,'embeddedlags') && length(options.embeddedlags) > 1
    d1 = -min(0,options.embeddedlags(1));
    d2 = max(0,options.embeddedlags(end));
    T = T - (d1+d2);
    T = ceil(r * T);
end

K = length(unique(vp));
S = cell(N,K);

for j = 1:N
    t0 = sum(T(1:j-1));
    ind = (1:T(j)) + t0;
    vp_j = vp(ind);
    for k = 1:K
       vp_jk = zeros(T(j),1);
       vp_jk(vp_j==k) = 1;
       vp_jk_diff = diff(vp_jk);
       Nvisits = sum(vp_jk_diff==1) + (vp_jk(1)==1);
       S{j,k} = zeros(Nvisits,2);
       if vp_jk(1)==1 % first visit is to this state
           S{j,k}(1,1) = 1;
           S{j,k}(2:end,1) = find(vp_jk_diff==1)+1;
       else
           S{j,k}(:,1) = find(vp_jk_diff==1)+1;
       end
       if vp_jk(end)==1 % last visit is to this state
           S{j,k}(1:end-1,2) = find(vp_jk_diff==(-1));
           S{j,k}(end,2) = T(j);
       else
           S{j,k}(:,2) = find(vp_jk_diff==(-1));
       end
    end
end

end


% M1QN3  Solve a UNO using M1QN3
%
% THIS IS A LOW LEVEL FUNCTION - USE opti_m1qn3() INSTEAD!
%
%   [x,fval,exitflag,iter,feval] = m1qn3(fun,grad,x0,opts)
%
%   Input arguments:
%       fun - nonlinear function handle
%       grad - nonlinear gradient function handle (required)
%       x0 - initial solution guess
%       opts - solver options (see below)
%
%   Return arguments:
%       x - solution vector
%       fval - objective value at the solution
%       exitflag - exit status (see below)
%       iter - number of iterations taken by the solver
%       feval - number of function evaluations taken by the solver
%
%   Option Fields (all optional):
%       display - solver display level [0,1,2]
%       tolafun - gradient convergence tolerance
%       maxiter - maximum solver iterations {1000}
%       maxfeval - Maximum number of function evaluations {1500}
%       maxtime - Maximum solver execution time {1000s}
%       nupdate - Number of L-BFGS updates for Hessian (5-10) {5}
%       iterfun - Iteration callback function handle
%
%   Return Status:
%       0 - user exited
%       1 - successful termination
%       2 - input argument error
%       3 - line-search is blocked
%       4 - maximum iterations reached
%       5 - maximum function evaluations reached
%       6 - stop on dxmin during the line-search
%       7 - numerical error
%       8 - maximum time reached
%
%
%   Copyright (C) 2012 Jonathan Currie (I2C2)


%-------------------------------------------------------------------------------------------------------------------%
%
% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear
% 	fluid-structure interaction models. This version of the code is based off of
%	Peskin's Immersed Boundary Method Paper in Acta Numerica, 2002.
%
% Author: Nicholas A. Battista
% Email:  nick.battista@unc.edu
% Date Created: May 27th, 2015
% Institution: UNC-CH
%
% This code is capable of creating Lagrangian Structures using:
% 	1. Springs
% 	2. Beams (*torsional springs)
% 	3. Target Points
%	4. Muscle-Model (combined Force-Length-Velocity model, "HIll+(Length-Tension)")
%
% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting %%	lengths, etc
%
% There are a number of built in Examples, mostly used for teaching purposes.
%
% If you would like us %to add a specific muscle model, please let Nick (nick.battista@unc.edu) know.
%
%--------------------------------------------------------------------------------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION: finds the indices on the Eulerian grid where the 1D Dirac-delta
% kernel is possibly non-zero in BOTH (x,y) directions
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [xInds,yInds] = give_NonZero_Delta_Indices_XY(xLag, yLag, Nx, Ny, dx, dy, supp)

%xLag: gives x-coordinate of Lagrangian position
%yLag: gives y-coordinate of Lagrangian position
%Nx:   # of Eulerian grid pts. in x-dimension
%Ny:   # of Eulerian grid pts. in y-dimension
%dx:   spatial-step along x-dimension of Eulerian grid
%dy:   spatial-step along y-dimension of Eulerian grid
%supp: size of support of the Dirac-delta kernel (should be even)

%Give x-dimension Non-Zero Delta Indices
xIndsAux = give_1D_NonZero_Delta_Indices(xLag, Nx, dx, supp);

%Repeat x-Indices for Non-Zero y-Indices!
xInds = [];
for i=1:supp
   xInds = [xInds xIndsAux]; %Sets up x-INDEX matrix bc we consider BOTH dimensions
end

%Give y-dimension Non-Zero Delta Indices
yIndsAux = give_1D_NonZero_Delta_Indices(yLag, Ny, dy, supp);

%Repeat y-Indices for Non-Zero x-Indices!
yInds = [];
for i=1:supp
    for j=1:supp
        yInds = [yInds yIndsAux(:,i)]; %Sets up y-INDEX matrix bc we consider BOTH dimensions
    end
end


function test_suite = test_createDurerPolyheron
%TEST_CREATEDURERPOLYHERON  Test case for the file createDurerPolyheron
%
%   Test case for the file createDurerPolyheron

%   Example
%   test_createDurerPolyheron
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2012-07-31,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2012 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function test_Simple(testCase) %#ok<*DEFNU>
% Test call of function without argument
[v, f] = createDurerPolyhedron;
testCase.assertEqual([12 3], size(v));
testCase.assertEqual(8, length(f));

function test_VEF(testCase)
% Test call of function without argument
[v, e, f] = createDurerPolyhedron;
testCase.assertEqual([12 3], size(v));
testCase.assertEqual([18 2], size(e));
testCase.assertEqual(8, length(f));


function metsBenchmark = evaluateTendMark( allMets, world )

% Aggregate scores from all sequences
MT = 0; PT = 0; ML = 0; FRA = 0;
falsepositives = 0; missed = 0; idswitches = 0;
Fgt = 0; distsum = 0; Ngt = 0; sumg = 0;
Nc = 0;
numGT = 0; numPRED = 0; IDTP = 0; IDFP = 0; IDFN = 0;

for ind = 1:length(allMets)
    if isempty(allMets(ind).m)
        fprintf('\n\nResults missing for sequence #%d\n', ind)
        continue;
    end
    numGT = numGT + allMets(ind).IDmeasures.numGT;
    numPRED = numPRED + allMets(ind).IDmeasures.numPRED;
    IDTP = IDTP + allMets(ind).IDmeasures.IDTP;
    IDFN = IDFN + allMets(ind).IDmeasures.IDFN;
    IDFP = IDFP + allMets(ind).IDmeasures.IDFP;

    MT = MT + allMets(ind).additionalInfo.MT;
    PT = PT + allMets(ind).additionalInfo.PT;
    ML = ML + allMets(ind).additionalInfo.ML;
    FRA = FRA + allMets(ind).additionalInfo.FRA;
    Fgt = Fgt + allMets(ind).additionalInfo.Fgt;
    Ngt = Ngt + allMets(ind).additionalInfo.Ngt;
    Nc = Nc + sum(allMets(ind).additionalInfo.c);
    sumg = sumg + sum(allMets(ind).additionalInfo.g);
    falsepositives = falsepositives + sum(allMets(ind).additionalInfo.fp);
    missed = missed + sum(allMets(ind).additionalInfo.m);
    idswitches = idswitches + sum(allMets(ind).additionalInfo.mme);
    dists = allMets(ind).additionalInfo.d;
    td = allMets(ind).additionalInfo.td;
    distsum = distsum + sum(sum(dists));
end

IDPrecision = IDTP / (IDTP + IDFP);
IDRecall = IDTP / (IDTP + IDFN);
IDF1 = 2*IDTP/(numGT + numPRED);
if numPRED==0, IDPrecision = 0; end
IDP = IDPrecision * 100;
IDR = IDRecall * 100;
IDF1 = IDF1 * 100;

FAR = falsepositives / Fgt;
MOTP = (1-distsum/Nc) * 100;
if world, MOTP = MOTP / td; end
if isnan(MOTP), MOTP = 0; end
MOTAL=(1-(missed+falsepositives+log10(idswitches+1))/sumg)*100;
MOTA=(1-(missed+falsepositives+idswitches)/sumg)*100;
recall=Nc/sumg*100;
precision=Nc/(falsepositives+Nc)*100;

metsBenchmark = [IDF1, IDP, IDR, recall, precision, FAR, Ngt, MT, PT, ML, falsepositives, missed, idswitches, FRA, MOTA, MOTP, MOTAL];

end


function [limitV,valV,ntcpLim,tcpLim,toolTipC] = getLimits(critS,type,strNum,doseNum,scale)

global planC;
indexS = planC{end};
structListC = {planC{indexS.structures}.structureName};

% Get DVH
[doseBinsV,volHistV] = getDVH(strNum,doseNum,planC);
doseBinsV = doseBinsV.*scale;

%Get val, limit
fieldsC = fieldnames(critS.(type));
valV = zeros(1,numel(fieldsC));
passV = zeros(1,numel(fieldsC));
nFail = 0;
ntcpLim = [];
tcpLim = [];
for m = 1:numel(fieldsC)
    lim = critS.(type).(fieldsC{m}).limit;
    limitV(m) = lim(1); %TEMP SKIP RANGE
    if strcmpi(fieldsC{m},'ntcp')
        ntcpLim = [limitV(m),m];
    end
    if strcmpi(fieldsC{m},'tcp')
        tcpLim = [limitV(m),m];
    end
    if isfield(critS.(type).(fieldsC{m}),'function')
        fn = critS.(type).(fieldsC{m}).function;
        if isfield(critS.(type).(fieldsC{m}),'additionalInputs')
            additionalInputs = critS.(type).(fieldsC{m}).additionalInputs;
            if numel(additionalInputs)==1  %%%TEMP FIX%%%%%%
             valV(m) = feval(fn,doseBinsV,volHistV,additionalInputs);
            else
                valV(m) = feval(fn,doseBinsV,volHistV,additionalInputs(1),additionalInputs(2));
            end
        else
            valV(m) = feval(fn,doseBinsV,volHistV);
        end
    end
    passV(m) = valV(m)<=limitV(m);
    toolTipC{m} = [structListC{strNum},' ',fieldsC{m},': ',num2str(valV(m))];
end

end


function denoised = NCSR_WRAP(image_path, sigma)

    Noisy_Image = imread(image_path);
    par     =   Parameters_setting( sigma );
    par.nim =   double( Noisy_Image );

    denoised = uint8(255 * mat2gray(NCSR_Denoising( par )));

end


% std_findsameica() - find groups of datasets with identical ICA decomposiotions
%
% Usage:
%        >> clusters = std_findsameica(ALLEEG);
%        >> clusters = std_findsameica(ALLEEG,icathreshold);
% Inputs:
%   ALLEEG           - a vector of loaded EEG dataset structures of all sets in the STUDY set.
%   icathreshold     - Threshold to compare icaweights
%
% Outputs:
%   cluster - cell array of groups of datasets
%
% Authors:  Arnaud Delorme, SCCN, INC, UCSD, July 2009-

% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, arno@sccn.ucsd.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

% Coding notes: Useful information on functions and global variables used.

function cluster = std_findsameica(ALLEEG, varargin);

% 6/2/2014 Ramon : Allow ica threshold as input.
if nargin == 1
    icathreshold = 2e-5;
elseif nargin == 2;
    icathreshold = varargin{1};
end

cluster = { [1] };
for index = 2:length(ALLEEG)

    found = 0;
    for c = 1:length(cluster)
        if all(size(ALLEEG(cluster{c}(1)).icaweights) == size(ALLEEG(index).icaweights))
            %if isequal(ALLEEG(cluster{c}(1)).icaweights, ALLEEG(index).icaweights)
            if sum(sum(abs(ALLEEG(cluster{c}(1)).icaweights-ALLEEG(index).icaweights))) < icathreshold
                cluster{c}(end+1) = index;
                found = 1;
                break;
            end;
        end;
    end;
    if ~found
        cluster{end+1} = index;
    end;
end;


function [percentAUCdecrease,varNames] = calcFeatureImportanceRF_HN_Old(pathRF,nPerms,nameOutcome,fSetName,seed)

startpath = pwd;

cd(pathRF), load('training'), load('testing')
if strcmp(nameOutcome,'DeathSign')
    outcome = testing.outcomes.Death;
else
    outcome = testing.outcomes.(nameOutcome);
end
nInst = numel(outcome); % Number of testing patients
perms = zeros(nInst,nPerms); rng(seed)
for p = 1:nPerms
    perms(:,p) = datasample(1:nInst,nInst,'Replace',false)';
end

results = load(['testResultsRF_',fSetName,'_',nameOutcome]); results = struct2cell(results); results = results{1};
AUC_baseline = results.AUC;
RF = load(['RF_',fSetName,'_',nameOutcome]); RF = struct2cell(RF); RF = RF{1};
indClinic = training.clinical.bestAdd.(nameOutcome).(fSetName);
text = testing.textures.(nameOutcome).(fSetName); nText = size(text,2);
tableTest = [text,testing.clinical.table(:,indClinic)];
varNames = tableTest.Properties.VariableNames'; nVar = numel(varNames);
percentAUCdecrease = zeros(nVar,1);
for v = 1:nVar
    tableTemp = tableTest;
    percentAUCdecrease_temp = 0;
    for p = 1:nPerms
        tableTemp(:,v) = tableTest(perms(:,p),v);
        [prob] = predictRF(tableTemp,RF);
        [AUC,~,~,~] = calcPerformMetrics(prob,outcome,0.5);
        percentAUCdecrease_temp = percentAUCdecrease_temp + (AUC - AUC_baseline)/AUC_baseline;
    end
    if percentAUCdecrease_temp > 0, percentAUCdecrease_temp = percentAUCdecrease_temp * -1; end
    percentAUCdecrease_temp = percentAUCdecrease_temp/nPerms;
    percentAUCdecrease(v) = percentAUCdecrease_temp;
end
[percentAUCdecrease,ind] = sort(percentAUCdecrease,'descend');
varNames = varNames(ind);

cd(startpath)
end


function y = square( x )

%SQUARE   Internal cvx version.

% 0 : all others
% 1 : constant
% 2 : real affine
% 3 : monomial, posynomial
narginchk(1,1);
persistent remap
if isempty( remap ),
    remap1 = cvx_remap( 'constant' );
    remap2 = cvx_remap( 'affine' ) & ~remap1;
    remap3 = cvx_remap( 'log-valid' ) & ~remap1;
    remap  = remap1 + 2 * remap2 + 3 * remap3;
end
v = remap( cvx_classify( x ) );

%
% Perform the computations for each expression type separately
%

vu = sort( v(:) );
vu = vu([true;diff(vu)~=0]);
nv = length( vu );
if nv ~= 1,
    y = cvx( size( x ), [] );
end
for k = 1 : nv,

    %
    % Select the category of expression to compute
    %

    vk = vu( k );
    if nv == 1,
        xt = x;
    else
        t = v == vk;
        xt = cvx_subsref( x, t );
    end

    %
    % Perform the computations
    %

    switch vk,
        case 0,
            % Invalid
            error( 'Disciplined convex programming error:\n    Illegal operation: square( {%s} ).', cvx_class( xt, true, true ) );
        case 1,
            % Constant
            yt = cvx_constant( xt );
            yt = cvx( yt .* yt );
        case 2,
            % Real affine
            yt = quad_over_lin( xt, 1, 0 );
        case 3,
            % Monomial, posynomial
            yt = exp( 2 * log( xt ) );
        otherwise,
            error( 'Shouldn''t be here.' );
    end

    %
    % Store the results
    %

    if nv == 1,
        y = yt;
    else
        y = cvx_subsasgn( y, t, yt );
    end

end

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


function [opt_radius,opt_interval,result,r,alldt,nummod,numreal,sigma] = calc_optim(a,rmin,rstep,rmax,tmin,tstep,Nmin,bootloops,maepi,choice)

    % function [opt_radius,opt_interval,result,r,alldt,nummod,numreal,sigma] = calc_optim(a,rmin,rstep,rmax,tmin,tstep,Nmin,bootloops,maepi,choice);
    % -------------------------------------------------------------------------
    %
    % optimisation of free parameters looking for seismic quiescences preceding large aftershocks
    %
    % Input parameters:
    %   a               Earthquake catalog (has to be complete in magnitude!)
    %   rmin,rstep,rmax Radius [degrees]
    %   tmin,tstep      Time [days]
    %   Nmin            minimum earthquake number in catalog
    %   bootloops       number of bootstrap loops
    %   maepi           mainshock (->ZMAP)
    %   choice          Nr. of M5+ aftershock
    %
    % Output parameters:
    %   opt_radius      radius around large aftershock
    %   opt_interval    time interval before large aftershock
    %   result          matrix containing relative seismic quiescences
    %   r, alldt        vectors with radii, forecast intervals
    %   numreal,nummod  observed/modeled nr. of aftershocks in interval
    %   sigma           uncertainty of forecast
    %
    % Samuel Neukomm
    % last update 25.02.2004

report_this_filefun(mfilename('fullpath'));
    % get mainshock / calculate delay times / cut catalogue at mainshock
    [m_main, main] = max(a.Magnitude);
    if size(a,2) == 9
        date_matlab = datenum(a.Date.Year,a.Date.Month,a.Date.Day,a.Date.Hour,a.Date.Minute,zeros(size(a,1),1));
    else
        date_matlab = datenum(a.Date.Year,a.Date.Month,a.Date.Day,a.Date.Hour,a.Date.Minute,a(:,10));
    end
    date_main = date_matlab(main);
    time_aftershock = date_matlab-date_main;
    l = time_aftershock(:) > 0;
    tas = time_aftershock(l);
    eqcatalogue = a.subset(l);

    % choose one of large aftershocks
    l = eqcatalogue(:,6) >= 5;
    largeas = eqcatalogue(l,:);
    largetime = tas(l);
    eq = largeas(choice,:);
    eqt = largetime(choice);

    % get optimum parameters
    dist_lon = eqcatalogue(:,1)-eq(1);
    dist_lat = eqcatalogue(:,2)-eq(2);
    dist_dep = km2deg(eqcatalogue(:,7)-eq(7),6371);
    result = []; i = 1;
    numreal = []; nummod = []; sigma = [];
    for r = rmin:rstep:rmax % range of collection radius
        disp(num2str(r/rmax))
        l = (dist_lon.^2+dist_lat.^2+dist_dep.^2).^0.5 <= r;
        gpi = eqcatalogue(l,:);
        time_as = tas(l);
        l = time_as < eqt;
        gpi = gpi(l,:); % sub-catalogue to be analysed
        time_as = time_as(l); % corresponding delay times

        if length(time_as) >= Nmin
            dt = tmin; % interval before large aftershock
            j = 1; alldt = [];
            while dt < eqt % Changed eqt/2 to eqt
                [rc,realnum,modnum,sig] = calc_optrc(gpi,time_as,eqt-dt,eqt,bootloops,maepi); % determine significance
                if isnan(rc)==0
                    result(i,j) = rc;
                    numreal(i,j) = realnum;
                    nummod(i,j) = modnum;
                    sigma(i,j) = sig;
                else
                    result(i,j) = 0;
                    numreal(i,j) = 0;
                    nummod(i,j) = 0;
                    sigma(i,j) = 0;
                end
                alldt = [alldt; dt];
                dt = dt+tstep;
                j = j+1;
            end
        end
        i = i+1;
    end
    r = (rmin:rstep:rmax)';

    if isempty(result) == 0  &&  max(max(result)) > 0
        % find minimum
        [dum, j] = min(min(result));
        [dum, i] = min(result(:,j));
        opt_radius = r(i);
        opt_interval = alldt(j);

        % contourplot of results
        figure_w_normalized_uicontrolunits('Numbertitle','off','Name','Optimum quiescence')
        lim = ceil(abs(dum));
        pcolor(alldt,r,result)
        set(gca,'pos',[0.15 0.15 0.7 0.7])
        shading interp
        caxis([-lim lim]);
        load fourcolors
        j = [j(256:-1:1,:) ];
        colormap(j)
        set(gcf,'renderer','zbuffer');
        set(gca,'TickDir','out')
        h5 = colorbar;
        set(h5,'Tickdir','out','pos',[0.8 0.3 0.02 0.4]);
        hold on
        plot(opt_interval,opt_radius','*','Markersize',8,'linewidth',2,'color','k');
        string =['Radius = ' num2str(opt_radius) ' deg; Interval = ' num2str(opt_interval) ' days; RC = ' num2str(dum,3) ];
        title(string)
        string = ['Time interval before t1 = ' num2str(round(100*eqt)/100) ' [days]'];
        xlabel(string)
        ylabel('Radius [deg]');
        set(gcf,'color','w');

        l = (dist_lon.^2+dist_lat.^2+dist_dep.^2).^0.5 <= opt_radius;
        optcat = eqcatalogue(l,:);
        time_as = tas(l);
        l = time_as < eqt;
        optcat = optcat(l,:);
        plot_optfit(optcat,eqt-opt_interval,opt_interval,bootloops,maepi);
    else
        opt_radius = NaN;
        opt_interval = NaN;
        alldt = NaN;
    end


function [params, names] = vargplvmExtractParamNoVardist(model)

% VARGPLVMEXTRACTPARAMNOVARDIST Extract a parameter vector from a variational GP-LVM model.
% ignoring the variational distribution. See vargplvmExtractParam.

if nargout > 1
  returnNames = true;
else
  returnNames = false;
end
params = [];
names = {};

% Inducing inputs
if ~model.fixInducing
    if ~isfield(model, 'learnInducing') || (isfield(model, 'learnInducing') && model.learnInducing)
        params =  [params model.X_u(:)'];
        if returnNames
            for i = 1:size(model.X_u, 1)
                for j = 1:size(model.X_u, 2)
                    X_uNames{i, j} = ['X_u(' num2str(i) ', ' num2str(j) ')'];
                end
            end
            names = {names{:}, X_uNames{:}};
        end
    end
end

% Kernel parameters
if returnNames
  [kernParams, kernParamNames] = kernExtractParam(model.kern);
  for i = 1:length(kernParamNames)
    kernParamNames{i} = ['Kernel, ' kernParamNames{i}];
  end
  names = {names{:}, kernParamNames{:}};
else
  kernParams = kernExtractParam(model.kern);
end
params = [params kernParams];

% beta in the likelihood
if model.optimiseBeta

   if ~isstruct(model.betaTransform)
       fhandle = str2func([model.betaTransform 'Transform']);
       betaParam = fhandle(model.beta, 'xtoa');
   else
      if isfield(model.betaTransform,'transformsettings') && ~isempty(model.betaTransform.transformsettings)
          fhandle = str2func([model.betaTransform.type 'Transform']);
          betaParam = fhandle(model.beta, 'xtoa', model.betaTransform.transformsettings);
      else
          error('vargplvmExtractParam: Invalid transform specified for beta.');
      end
   end

   params = [params betaParam(:)'];

   if returnNames
     for i = 1:length(betaParam)
       betaParamNames{i} = ['Beta ' num2str(i)];
     end
     names = {names{:}, betaParamNames{:}};
   end
end


%
% Usage:   B =mexInvSym(A);
%
% Name: mexInvSym
%
% Description: returns the inverse of a symmetric matrix A
%
% Inputs: A:  double n x n matrix
%
% Output: B: double n x n matrix
%
% Author: Julien Mairal, 2009


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D
% shape modeling and analysis toolkit.
% It is a software package developed at Shenlab in Center for Neuroimaging,
% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)
% It is available to the scientific community as copyright freeware
% under the terms of the GNU General Public Licence.
%
% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University
%
% This file is part of SPHARM-MAT.
%
% SPHARM-MAT is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SPHARM-MAT is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% ============================================
% read_coef.m
% function for reading *.coef file and saving the coefficients to *_des.mat
% file

% INPUT: filename, which is the name of the input coef file.
% If not specifying a filename, a dialogue window will be activated for choosing a
% gipl file.
%
% Wan Jing
% 11/06/2008 - create
%============================================

function fvec = read_coef(filename)

fid = fopen(filename,'r');
if(fid<0)
    fprintf('could not open file %s\n',filename);
    return
end

Count = fscanf(fid, '{ %d,', 1);
if(isempty(Count))
    fprintf('The type of this file is not coef. \n');
    return;
end

% read the coefficients to C
C = fscanf(fid, '{%lf, %lf, %lf},\n', [3 inf]);
C = C';
fprintf('The number of coefficients are: %d .\n ',length(C));

if (Count ~= length(C))
    fprintf('The file has error about the number of coefficients');
end

fvec = [];
i = 1;

md = sqrt(length(C))-1;
for L = 0:md
    for M=-L:L
%         disp(sprintf('i=%d, L=%d, M=%d',i,L,M));
        switch sign(M)
            case -1
                fvec(end+1,:) = [0 0 0];
            case 0
                fvec(end+1,:) = C(i,:); i=i+1;
            case 1
                fvec(end+1,:) = complex(C(i,:),C(i+1,:)); i=i+2;
        end
    end
end

fclose('all');

return


function sats=satid2no(satid)

global glc;
sats=0;

[prn,n]=sscanf(satid,'%d');
if n==1
%     prn=str2double(satid);
    if     glc.MINPRNGPS<=prn&&prn<=glc.MAXPRNGPS,sys=glc.SYS_GPS;
    elseif glc.MINPRNQZS<=prn&&prn<=glc.MAXPRNQZS,sys=glc.SYS_QZS;
    else  ,return ;
    end
    sats=satno(sys,prn);
end

[str,n]=sscanf(satid,'%c%d',2);
if n<2,return;end
code=char(str(1)); prn=str(2);
switch code
    case 'G',sys=glc.SYS_GPS;prn=prn+glc.MINPRNGPS-1;
    case 'R',sys=glc.SYS_GLO;prn=prn+glc.MINPRNGLO-1;
    case 'E',sys=glc.SYS_GAL;prn=prn+glc.MINPRNGAL-1;
    case 'C',sys=glc.SYS_BDS;prn=prn+glc.MINPRNBDS-1;
    case 'J'
        sys=glc.SYS_QZS;prn=prn+glc.MINPRNQZS-1;
    otherwise, return;
end
sats=satno(sys,prn);

return


function sys = sdpvar(varargin)
%SDPVAR Create symbolic decision variable
%
%   You can create a sdpvar variable by:
%     X = SDPVAR(n)               Symmetric nxn matrix
%     X = SDPVAR(n,n)             Symmetric nxn matrix
%     X = SDPVAR(n,m)             Full nxm matrix (n~=m)
%
%   Definition of multiple scalars can be simplified
%     SDPVAR x y z w
%
%   The parametrizations supported are
%     X = SDPVAR(n,n,'full')      Full nxn matrix
%     X = SDPVAR(n,n,'symmetric') Symmetric nxn matrix
%     X = SDPVAR(n,n,'toeplitz')  Symmetric Toeplitz
%     X = SDPVAR(n,n,'hankel')    Symmetric Hankel
%     X = SDPVAR(n,n,'skew')      Skew-symmetric
%
%   The letters 'sy','f','ha', 't' and 'sk' are searched for in the third argument
%   hence sdpvar(n,n,'toeplitz') gives the same result as sdpvar(n,n,'t')
%
%   Only square Toeplitz and Hankel matries are supported
%
%   A scalar is defined as a 1x1 matrix
%
%   Higher-dimensional matrices are also supported, although this currently
%   is an experimental feature with limited use. The type flag applies to
%   the lowest level slice.
%
%     X = SDPVAR(n,n,n,'full')      Full nxnxn matrix
%
%   In addition to the matrix type, a fourth argument
%   can be used to obtain a complex matrix. All the
%   matrix types above apply to a complex matrix, and
%   in addition a Hermitian type is added
%
%     X = SDPVAR(n,n,'hermitian','complex') Complex Hermitian nxn matrix (X=X'=conj(X.'))
%
%   The other types are obtained as above
%     X = SDPVAR(n,n,'symmetric','complex') Complex symmetric nxn matrix (X=X.')
%     X = SDPVAR(n,n,'full','complex')      Complex full nxn matrix
%     ... and the same for Toeplitz, Hankel and skew-symmetric
%
%   See also @SDPVAR/SET, INTVAR, BINVAR, methods('sdpvar'), SEE

superiorto('sdpvar');
if nargin==0
    return
end

if isstruct(varargin{1})
    sys = class(varargin{1},'ncvar');
    return
end

% To speed up dualization, we keep track of primal SDP cones
% [0 0] :  Nothing known (cleared in some operator, or none-cone to start with)
% [1 0] :  Primal cone
% [1 1] :  Primal cone + DOUBLE
% [1 2 x] :  Primal cone + SDPVAR
% [-1 1] : -Primal cone + DOUBLE
% [-1 2 x] : -Primal cone + SDPVAR

conicinfo = [0 0];

if ischar(varargin{1})
    switch varargin{1}
        case 'clear'
            disp('Obsolete comand');
            return
        case 'nvars'
            sys = yalmip('nvars');%THIS IS OBSAOLETE AND SHOULD NOT BE USED
            return
        otherwise
            n = length(varargin);
            varnames = varargin;
            for k = 1:n
                varcmd{k}='(1,1)';
                lp=strfind(varargin{k},'(');
                rp=strfind(varargin{k},')');
                if isempty(lp) & isempty(rp)
                    if ~isvarname(varargin{k})
                        error('Not a valid variable name.')
                    end
                else
                    if (~isempty(lp))&(~isempty(rp))
                        if min(lp)<max(rp)
                            varnames{k} = varargin{k}(1:lp-1);
                            varcmd{k}=varargin{k}(lp:rp);
                        else
                            error('Not a valid variable name.')
                        end
                    else
                        error('Not a valid variable name.')
                    end
                end
            end
            for k = 1:n
                if isequal(varnames{k},'i') | isequal(varnames{k},'j')
                    if length(dbstack) == 1
                        assignin('caller',varnames{k},eval(['sdpvar' varcmd{k}]));
                    else
                        error(['Due to a bug in MATLAB, use ' varnames{k} ' = sdpvar' varcmd{k} ' instead.']);
                    end
                else
                    assignin('caller',varnames{k},eval(['ncvar' varcmd{k}]));
                end
            end
            return
    end
end

% *************************************************************************
% Maybe new NDSDPVAR syntax
% *************************************************************************
if nargin > 2 & isa(varargin{3},'double') & ~isempty(varargin{3})
    sys = ndsdpvar(varargin{:});
    return
end

% Supported matrix types
% - symm
% - full
% - skew
% - hank
% - toep
switch nargin
    case 1 %Bug in MATLAB 5.3!! sdpvar called from horzcat!!!!????
        if isempty(varargin{1})
            sys = varargin{1};
            return
        end
        if isa(varargin{1},'sdpvar')
            sys = varargin{1};
            sys.typeflag = 0;
            return
        end
        n = varargin{1};
        m = varargin{1};
        if sum(n.*m)==0
            sys = zeros(n,m);
            return
        end
        if (n==m)
            matrix_type = 'symm';
            nvar = sum(n.*(n+1)/2);
            conicinfo = [1 0];
        else
            matrix_type = 'full';
            nvar = sum(n.*m);
        end
    case 2
        n = varargin{1};
        m = varargin{2};
        if length(n)~=length(m)
            error('The dimensions must have the same lengths')
        end
        if sum(n.*m)==0
            sys = zeros(n,m);
            return
        end
        if (n==m)
            matrix_type = 'symm';
            nvar = sum(n.*(n+1)/2);
            conicinfo = [1 0];
        else
            matrix_type = 'full';
            nvar = sum(n.*m);
        end
    case {3,4}
        n = varargin{1};
        m = varargin{2};
        if sum(n.*m)==0
            sys = zeros(n,m);
            return
        end

        % Check for complex or real
        if (nargin == 4)
            if isempty(varargin{4})
                varargin{4} = 'real';
            else
                if ~ischar(varargin{4})
                    help sdpvar
                    error('Fourth argument should be ''complex'' or ''real''')
                end
            end
            index_cmrl = strmatch_octavesafe(varargin{4},{'real','complex'});
            if isempty(index_cmrl)
                error('Fourth argument should be ''complex'' or ''real''. See help above')
            end
        else
            if ~ischar(varargin{3})
                help sdpvar
                error('Third argument should be ''symmetric'', ''full'', ''hermitian'',...See help above')
            end
            index_cmrl = 1;
        end;

        if isempty(varargin{3})
            if n==m
                index_type = 7; %Default symmetric
            else
                index_type = 4;
            end
        else
            if ~isempty(strmatch_octavesafe(varargin{3},{'complex','real'}))
                % User had third argument as complex or real
                error(['Third argument should be ''symmetric'', ''full'', ''toeplitz''... Maybe you meant sdpvar(n,n,''full'',''' varargin{3} ''')'])
            end
            index_type = strmatch_octavesafe(varargin{3},{'toeplitz','hankel','symmetric','full','rhankel','skew','hermitian'});
        end

        if isempty(index_type)
            error(['Matrix type "' varargin{3} '" not supported'])
        else
            switch index_type+100*(index_cmrl-1)
                case 1
                    if n~=m
                        error('Toeplitz matrix must be square')
                    else
                        matrix_type = 'toep';
                        nvar = n;
                    end

                case 2
                    if n~=m
                        error('Hankel matrix must be square')
                    else
                        matrix_type = 'hank';
                        nvar = n;
                    end

                case 3
                    if n~=m
                        error('Symmetric matrix must be square')
                    else
                        matrix_type = 'symm';
                        nvar = sum(n.*(n+1)/2);
                    end

                case 4
                    matrix_type = 'full';
                    nvar = sum(n.*m);
                    if nvar==1
                        matrix_type = 'symm';
                    end

                case 5
                    if n~=m
                        error('Hankel matrix must be square')
                    else
                        matrix_type = 'rhankel';
                        nvar = 2*n-1;
                    end

                case 6
                    if n~=m
                        error('Skew symmetric matrix must be square')
                    else
                        matrix_type = 'skew';
                        nvar = (n*(n+1)/2)-n;
                    end

                case 7
                    if n~=m
                        error('Symmetric matrix must be square')
                    else
                        matrix_type = 'symm';
                        nvar = n*(n+1)/2;
                    end

                case 101
                    if n~=m
                        error('Toeplitz matrix must be square')
                    else
                        matrix_type = 'toep complex';
                        nvar = 2*n;
                    end

                case 102
                    if n~=m
                        error('Hankel matrix must be square')
                    else
                        matrix_type = 'hank complex';
                        nvar = (2*n);
                    end

                case 103
                    if n~=m
                        error('Symmetric matrix must be square')
                    else
                        matrix_type = 'symm complex';
                        nvar = 2*n*(n+1)/2;
                    end

                case 104
                    matrix_type = 'full complex';
                    nvar = 2*n*m;
                    if nvar==1
                        matrix_type = 'symm complex';
                    end

                case 105
                    if n~=m
                        error('Hankel matrix must be square')
                    else
                        matrix_type = 'rhankel complex';
                        nvar = 2*(2*n-1);
                    end

                case 106
                    if n~=m
                        error('Skew symmetric matrix must be square')
                    else
                        matrix_type = 'skew complex';
                        nvar = 2*((n*(n+1)/2)-n);
                    end

                case 107
                    if n~=m
                        error('Hermitian matrix must be square')
                    else
                        matrix_type = 'herm complex';
                        nvar = n*(n+1)/2+(n*(n+1)/2-n);
                    end

                otherwise
                    error('Bug! Report!');
            end

        end

    case 5 % Fast version for internal use
        sys.basis = varargin{5};
        sys.lmi_variables=varargin{4};
        sys.dim(1) = varargin{1};
        sys.dim(2) = varargin{2};
        sys.typeflag = 0;
        sys.savedata = [];
        sys.extra = [];
        sys.extra.expanded = [];
        sys.extra.createTime = definecreationtime;
        sys.originalbasis = [];
        sys.leftfactors{1} = [];
        sys.rightfactors{1} = [];
        sys.midfactors{1} = [];
        sys.conicinfo = 0;

        % Find zero-variables
        constants = find(sys.lmi_variables==0);
        if ~isempty(constants);
            sys.lmi_variables(constants)=[];
            sys.basis(:,1) = sys.basis(:,1) + sum(sys.basis(:,1+constants),2);
            sys.basis(:,1+constants)=[];
        end
        if isempty(sys.lmi_variables)
            sys = full(reshape(sys.basis(:,1),sys.dim(1),sys.dim(2)));
        else
            sys = class(sys,'sdpvar');
        end
        return
    case 6 % Fast version for internal use
        sys.basis = varargin{5};
        sys.lmi_variables=varargin{4};
        sys.dim(1) = varargin{1};
        sys.dim(2) = varargin{2};
        sys.typeflag = varargin{6};
        sys.savedata = [];
        sys.extra = [];
        sys.extra.expanded = [];
        sys.extra.createTime = definecreationtime;
        sys.conicinfo = 0;
        sys.originalbasis = [];
        sys.leftfactors{1} = [];
        sys.rightfactors{1} = [];
        sys.midfactors{1} = [];
        % Find zero-variables
        constants = find(sys.lmi_variables==0);
        if ~isempty(constants);
            sys.lmi_variables(constants)=[];
            sys.basis(:,1) = sys.basis(:,1) + sum(sys.basis(:,1+constants),2);
            sys.basis(:,1+constants)=[];
        end
        if isempty(sys.lmi_variables)
            sys = full(reshape(sys.basis(:,1),sys.dim(1),sys.dim(2)));
        else
            sys = class(sys,'ncvar');
        end
        return
    case 7 % Fast version for internal use
        sys.basis = varargin{5};
        sys.lmi_variables=varargin{4};
        sys.dim(1) = varargin{1};
        sys.dim(2) = varargin{2};
        sys.typeflag = varargin{6};
        sys.savedata = [];
        sys.extra = varargin{7};
        sys.extra.expanded = [];
        sys.extra.createTime = definecreationtime;
        sys.conicinfo = varargin{7};
        % Find zero-variables
        constants = find(sys.lmi_variables==0);
        if ~isempty(constants);
            sys.lmi_variables(constants)=[];
            sys.basis(:,1) = sys.basis(:,1) + sum(sys.basis(:,1+constants),2);
            sys.basis(:,1+constants)=[];
        end
        if isempty(sys.lmi_variables)
            sys = full(reshape(sys.basis(:,1),sys.dim(1),sys.dim(2)));
        else
            sys = class(sys,'sdpvar');
        end
        return

    otherwise
        error('Wrong number of arguments in sdpvar creation');
end

if isempty(n) | isempty(m)
    error('Size must be integer valued')
end;
if ~((abs((n-ceil(n)))+ abs((m-ceil(m))))==0)
    error('Size must be integer valued')
end

nonCommutingTable = yalmip('nonCommutingTable');
[monomtable,variabletype] = yalmip('monomtable');
lmi_variables = (1:nvar)+max(size(nonCommutingTable,1),size(monomtable,1));

for blk = 1:length(n)
    switch matrix_type

        case 'full'
            basis{blk} = [spalloc(n(blk)*m(blk),1,0) speye(n(blk)*m(blk))];%speye(nvar)];

        case 'full complex'
            basis = [spalloc(n*m,1,0) speye(nvar/2) speye(nvar/2)*sqrt(-1)];

        case 'symm'
            if 0
                basis = spalloc(n^2,1+nvar,n^2);
                l = 2;
                an_empty = spalloc(n,n,2);
                for i=1:n
                    temp = an_empty;
                    temp(i,i)=1;
                    basis(:,l)=temp(:);
                    l = l+1;
                    for j=i+1:n,
                        temp = an_empty;
                        temp(i,j)=1;
                        temp(j,i)=1;
                        basis(:,l)=temp(:);
                        l = l+1;
                    end
                end
            else
                % Hrm...fast but completely f*d up

                Y = reshape(1:n(blk)^2,n(blk),n(blk));
                Y = tril(Y);
                Y = (Y+Y')-diag(sparse(diag(Y)));
                [uu,oo,pp] = unique(Y(:));
                if 1
                    basis{blk} = sparse(1:n(blk)^2,pp+1,1);
                else
                    basis{blk} = lazybasis(n^2,1+(n*(n+1)/2),1:n(blk)^2,pp+1,ones(n(blk)^2,1));
                end

            end

        case 'symm complex'
            basis = spalloc(n^2,1+nvar,2);
            l = 2;
            an_empty = spalloc(n,n,2);
            for i=1:n
                temp = an_empty;
                temp(i,i)=1;
                basis(:,l)=temp(:);
                l = l+1;
                for j=i+1:n,
                    temp = an_empty;
                    temp(i,j)=1;
                    temp(j,i)=1;
                    basis(:,l)=temp(:);
                    l = l+1;
                end
            end
            for i=1:n
                temp = an_empty;
                temp(i,i)=sqrt(-1);
                basis(:,l)=temp(:);
                l = l+1;
                for j=i+1:n,
                    temp = an_empty;
                    temp(i,j)=sqrt(-1);
                    temp(j,i)=sqrt(-1);
                    basis(:,l)=temp(:);
                    l = l+1;
                end
            end

        case 'herm complex'
            basis = spalloc(n^2,1+nvar,2);
            l = 2;
            an_empty = spalloc(n,n,2);
            for i=1:n
                temp = an_empty;
                temp(i,i)=1;
                basis(:,l)=temp(:);
                l = l+1;
                for j=i+1:n,
                    temp = an_empty;
                    temp(i,j)=1;
                    temp(j,i)=1;
                    basis(:,l)=temp(:);
                    l = l+1;
                end
            end
            for i=1:n
                for j=i+1:n,
                    temp = an_empty;
                    temp(i,j)=sqrt(-1);
                    temp(j,i)=-sqrt(-1);
                    basis(:,l)=temp(:);
                    l = l+1;
                end
            end

        case 'skew'
            basis = spalloc(n^2,1+nvar,2);
            l = 2;
            an_empty = spalloc(n,n,2);
            for i=1:n
                for j=i+1:n,
                    temp = an_empty;
                    temp(i,j)=1;
                    temp(j,i)=-1;
                    basis(:,l)=temp(:);
                    l = l+1;
                end
            end

        case 'skew complex'
            basis = spalloc(n^2,1+nvar,2);
            l = 2;
            an_empty = spalloc(n,n,2);
            for i=1:n
                for j=i+1:n,
                    temp = an_empty;
                    temp(i,j)=1;
                    temp(j,i)=-1;
                    basis(:,l)=temp(:);
                    l = l+1;
                end
            end
            for i=1:n
                for j=i+1:n,
                    temp = an_empty;
                    temp(i,j)=sqrt(-1);
                    temp(j,i)=-sqrt(-1);
                    basis(:,l)=temp(:);
                    l = l+1;
                end
            end

        case 'toep'
            basis = spalloc(n^2,1+nvar,2);
            an_empty = spalloc(n,1,1);
            for i=1:n,
                v = an_empty;
                v(i)=1;
                temp = sparse(toeplitz(v));
                basis(:,i+1) = temp(:);
            end

            % Notice, complex Toeplitz not Hermitian
        case 'toep complex'
            basis = spalloc(n^2,1+nvar,2);
            an_empty = spalloc(n,1,1);
            for i=1:n,
                v = an_empty;
                v(i)=1;
                temp = sparse(toeplitz(v));
                basis(:,i+1) = temp(:);
            end
            for i=1:n,
                v = an_empty;
                v(i)=sqrt(-1);
                temp = sparse(toeplitz(v));
                basis(:,n+i+1) = temp(:);
            end

        case 'hank'
            basis = spalloc(n^2,1+nvar,2);
            an_empty = spalloc(n,1,1);
            for i=1:n,
                v = an_empty;
                v(i)=1;
                temp = sparse(hankel(v));
                basis(:,i+1) = temp(:);
            end

        case 'hank complex'
            basis = spalloc(n^2,1+nvar,2);
            an_empty = spalloc(n,1,1);
            for i=1:n,
                v = an_empty;
                v(i)=1;
                temp = sparse(hankel(v));
                basis(:,i+1) = temp(:);
            end
            for i=1:n,
                v = an_empty;
                v(i)=sqrt(-1);
                temp = sparse(hankel(v));
                basis(:,n+i+1) = temp(:);
            end

        case 'rhankel'
            basis = spalloc(n^2,1+nvar,2);
            an_empty = spalloc(2*n-1,1,1);
            for i=1:nvar,
                v = an_empty;
                v(i)=1;
                temp = sparse(hankel(v(1:n),[v(n);v(n+1:2*n-1)]));
                basis(:,i+1) = temp(:);
            end

        case 'rhankel complex'
            basis = spalloc(n^2,1+nvar,2);
            an_empty = spalloc(2*n-1,1,1);
            for i=1:nvar/2,
                v = an_empty;
                v(i)=1;
                temp = sparse(hankel(v(1:n),[v(n);v(n+1:2*n-1)]));
                basis(:,i+1) = temp(:);
            end
            for i=1:nvar/2,
                v = an_empty;
                v(i)=sqrt(-1);
                temp = sparse(hankel(v(1:n),[v(n);v(n+1:2*n-1)]));
                basis(:,nvar/2+i+1) = temp(:);
            end

        otherwise
            error('Bug! Report')
    end

end

% Update noncommuting table and monomtables
nonCommutingTable(lmi_variables,1) = nan;
nonCommutingTable(lmi_variables,2) = lmi_variables;
yalmip('nonCommutingTable',nonCommutingTable);
variabletype(lmi_variables) = 0;
monomtable(lmi_variables(end),lmi_variables(end)) = 0;
yalmip('setmonomtable',monomtable,variabletype);
%if strcmp(matrix_type,'NonHermitian')
%    yalmip('setNonHermitianNonCommuting',lmi_variables);
%end

% Create an object
if isa(basis,'cell')
    top = 1;
    for blk = 1:length(n)
        sys{blk}.basis=basis{blk};
        nn = size(sys{blk}.basis,2)-1;
        sys{blk}.lmi_variables = lmi_variables(top:top+nn-1);
        top = top + nn;
        sys{blk}.dim(1) = n(blk);
        sys{blk}.dim(2) = m(blk);
        sys{blk}.typeflag = 0;
        sys{blk}.savedata = [];
        sys{blk}.extra = [];
        sys{blk}.extra.expanded = [];
        sys{blk}.extra.createTime = definecreationtime;
        sys{blk}.conicinfo = conicinfo;
        sys{blk}.originalbasis = [];
        sys{blk}.leftfactors{1} = [];
        sys{blk}.rightfactors{1} = [];
        sys{blk}.midfactors{1} = [];
        sys{blk} = class(sys{blk},'ncvar');
    end
    if length(n)==1
        sys = sys{1};
    end
else
    sys.basis=basis;
    sys.lmi_variables = lmi_variables;
    sys.dim(1) = n;
    sys.dim(2) = m;
    sys.typeflag = 0;
    sys.savedata = [];
    sys.extra = [];
    sys.extra.expanded = [];
    sys.extra.createTime = definecreationtime;
    sys.conicinfo = conicinfo;
    sys.originalbasis = [];
    sys.leftfactors{1} = [];
    sys.rightfactors{1} = [];
    sys.midfactors{1} = [];
    sys = class(sys,'ncvar');
    if ~isreal(basis)
        % Add internal information about complex pairs
        complex_elements = find(any(imag(basis),2));
        complex_pairs = [];
        for i = 1:length(complex_elements)
            complex_pairs = [complex_pairs;lmi_variables(find(basis(complex_elements(i),:))-1)];
        end
        complex_pairs = uniquesafe(complex_pairs,'rows');
        yalmip('addcomplexpair',complex_pairs);
    end
end


load uav3
abs = states.data;
t = 0;
n = size(abs,1);
A = [];
for i = 1:n
a1 = [t abs(i,1)  abs(i,2) abs(i,3) abs(i,4) abs(i,8) abs(i,7) abs(i,16)];
A = [A;a1];

t = t+0.01;
end

n1 = n;
plot3(A(1:n1,2), A(1:n1,3),A(1:n1,4));
axis equal


function seed = randomseed(seed)
% RANDOMSEED   Get or set the random seed.
% SEED = RANDOMSEED returns the current random seed for lightspeed random
% number routines.  SEED is a vector of 3 integers.
% RANDOMSEED(NEW_SEED) sets a new random seed.
% The seed determines the sequence of numbers that will be generated.
% Only the routines randgamma, randbinom, and sample_hist are affected.
%
% Example:
% randomseed([4 5 6])
% randgamma(repmat(3,1,3))   % 3 random numbers
% randomseed([4 5 6])
% randgamma(repmat(3,1,3))   % the same 3 numbers

error('You must first run install_lightspeed.m');


function p = exp_part(x,idx)
% Get a specific part of an expression; can be more efficient than exp_parts.
% Parts = exp_part(Expression, Index)
%
% In:
%   Expression  : any expression
%   Index       : index of the part;
%                  * 0 is the expression's head
%                  * 1..n is the expression's parts, n being exp_length(Expression)
%                  * negative indices count parts from the end
%                  * index vectors denote paths into the expression tree
%
% Out:
%   Part        : the selected part of the expression, as in exp_parts
%
% See also:
%   exp_head, exp_parts, exp_length
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-04-26

while isfield(x,'tracking') && isfield(x.tracking,'expression')
    x = x.tracking.expression; end

try
    if length(idx)==1
        if idx > 0
            % positive indices behave as exp_parts(x){idx} (if that could be written in MATLAB...)
            if isfield(x,{'head','parts'})
                p = x.parts{idx};
            elseif has_function_symbol(x)
                p = get_function_symbol(x);
            elseif idx == 1
                p = x;
            else
                error; %#ok<LTARG>
            end
        elseif idx == 0
            % part 0 is the head
            p = exp_head(x);
        elseif idx < 0
            % negative indices count from the end (-1 is the last part)
            p = exp_part(x,exp_length(x)+idx+1);
        end
    else
        % index vectors specify paths into the expression
        p = exp_part(exp_part(x,idx(1)),idx(2:end));
    end
catch
    error('out-of-range part accessed.');
end


function out = cfg_example_run_add2(job)
% Example function that returns the sum of two numbers given in job.a in
% out. The output is referenced as out(1), this is defined in
% cfg_example_vout_add2.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg_example_run_add2.m 1716 2008-05-23 08:18:45Z volkmar $

rev = '$Rev: 1716 $'; %#ok

out = sum(job.a);


function roi = dtiRoiMakePlane(cornerCoords, roiName, roiColor)
%
% roi = dtiRoiMakePlane(cornerCoords, name, color)
%
% e.g.:
% roi = dtiRoiMakePlane([-60,-30,-60; 60,-30,80], 'coronal_plane', 'c')
%
% For a more complex sample, edit this function to see the code below the
% return.
%
% 2008.10.01 RFD: wrote it.

if(~exist('roiName','var') || isempty(roiName))
    roiName = 'plane';
end
if(~exist('roiColor','var') || isempty(roiColor))
    roiColor = 'r';
end
lc = min(cornerCoords);
uc = max(cornerCoords);
[x,y,z] = ndgrid([lc(1):uc(1)], [lc(2):uc(2)], [lc(3):uc(3)]);

roi = dtiNewRoi(roiName, roiColor, [x(:),y(:),z(:)]);

return;

% To run this on a bunch of subjects:
bd = '/biac3/wandell4/data/reading_longitude/dti_y4';
[subList,subCodes,subDirs] = findSubjects(fullfile(bd,'/*'),'dti06');
x = [-70 70];
z = [-60 80];
y = [-30 -31 -34 -30 ];
for(ii=1:numel(subList))
    roi = dtiRoiMakePlane([x(1),y(ii),z(1); x(2),y(ii),z(2)], 'coronal', 'c');
    roiFileName = fullfile(subDirs{ii},'ROIs','IPSproject','coronal');
    dtiWriteRoi(roi,roiFileName);
end


function volROI = ip2volROI(ipROI,ipView,volView)
%
% volROI = ip2volROI(ipROI,ipView,volView)
%
% Creates a volume ROI from an inplane ROI by mapping
% coordinates, keeping track of partial voluming
%
% ipROI and volROI are ROI structures, like those found in
% view.ROIs
%
% ipView must be the INPLANE structure.
% volView must be the VOLUME structure.
%
% djh, 8/98.
global mrSESSION
global vANATOMYPATH

% check that some more-recently-implemented fields are defined
% (ras, 02/2007)
ipROI = roiCheck(ipROI);

% Get voxel sizes to make sure that the transformation preserves volume
ipVoxSize = viewGet(ipView, 'voxel size');
volVoxSize = readVolAnatHeader(vANATOMYPATH);

% Transform ROI coordinates
xform = mrSESSION.alignment;

coords = xformROIcoords(ipROI.coords, xform, ipVoxSize, volVoxSize);

if isempty(coords)
    % put a warning, but only if these aren't hidden views
    if ~isequal(viewGet(ipView,'Name'), 'hidden') && ~isequal(viewGet(volView,'Name'), 'hidden')
        msg = sprintf(['No voxels from %s map to the volume view. ' ...
                       'No ROI created.'], ipROI.name);
        myWarnDlg(msg);
        volROI = [];
        return
    end
end

% Toss coords outside the volume
volSize = viewGet(volView,'Size');
indices = ((coords(1,:) >= 1) & (coords(1,:) <= volSize(1)) & ...
    (coords(2,:) >= 1) & (coords(2,:) <= volSize(2)) & ...
    (coords(3,:) >= 1) & (coords(3,:) <= volSize(3)));
coords = coords(:,indices);

% Set the other fields and sort
volROI = ipROI;
volROI.coords = coords;
volROI.viewType = volView.viewType;

return;

%%%%%%%%%%%%%%
% Debug/test %
%%%%%%%%%%%%%%

ipROI = INPLANE{1}.ROIs(INPLANE{1}.selectedROI);
volROI = ip2volROI(ipROI,INPLANE{1},VOLUME{1});
newipROI = vol2ipROI(volROI,VOLUME{1},INPLANE{1});
ipROI.coords
newipROI.coords


function [ebsd,options] = loadEBSD_generic(fname,varargin)
% load ebsd data from generic text files
%
% Description
%
% *loadEBSD_generic* loads EBSD data from text or exel files that have a
% column oriented format as
%
%  x1 y1 phi1_1 Phi_1 phi2_1 phase_1
%  x2 y2 phi1_2 Phi_2 phi2_2 phase_2
%  x2 y3 phi1_3 Phi_3 phi2_3 phase_3
%  .      .       .       .
%  .      .       .       .
%  .      .       .       .
%  xM yM phi1_M Phi_M phi2_M phase_m
%
% The assoziation of the columns as Euler angles, phase informationl, etc.
% is specified by the options |ColumnNames| and |Columns|. The files can be
% contain any number of header lines.
%
% Syntax
%   ebsd   = loadEBSD_generic(fname,'ColumnNames',{'x','y','Euler1','Euler2','Euler3','phase'},'cs',cs)
%
% Input
%  fname - file name (text files only)
%  cs - @crystalSymmetry or cell array of @crystalSymmetry
%
% Options
%  ColumnNames       - names of the colums to be imported, mandatory are euler 1, euler 2, euler 3
%  Columns           - postions of the columns to be imported
%  radians           - treat input in radiand
%  delimiter         - delimiter between numbers
%  header            - number of header lines
%  Bunge             - [phi1 Phi phi2] Euler angle in Bunge convention (default)
%  ABG               - [alpha beta gamma] Euler angle in Mathies convention
%  passive           -
%
%
% Example
%
%   fname = fullfile(mtexDataPath,'EBSD','85_829grad_07_09_06.txt');
%   CS = {'notIndexed',...
%          crystalSymmetry('m-3m','mineral','Fe'),...
%          crystalSymmetry('m-3m','mineral','Mg')};
%   SS = specimenSymmetry('triclinic');
%   ebsd = loadEBSD_generic(fname,'CS',CS,'SS',SS, 'ColumnNames', ...
%     {'Index' 'Phase' 'x' 'y' 'Euler1' 'Euler2' 'Euler3' 'MAD' 'BC' 'BS'...
%     'Bands' 'Error' 'ReliabilityIndex'}, 'Bunge')
%
% See also
% ImportEBSDData loadEBSD ebsd_demo

max_num_phases = 40;

try
  % load data
  if ~isnumeric(fname)
    [d,options,header,c] = load_generic(char(fname),varargin{:});
    varargin = options;
  else
    d = fname;
  end

  % no data found
  if size(d,1) < 1 || size(d,2) < 3
    error('Generic interface could not detect any numeric data in %s',fname);
  end

  % no options given -> ask
  if ~check_option(varargin,'ColumnNames')

    options = generic_wizard('data',d(1:end<101,:),'type','EBSD','header',header,'columns',c);
    if isempty(options), ebsd = []; return; end
    varargin = [options,varargin];

  end

  loader = loadHelper(d,varargin{:});

  q      = loader.getRotations();

  % assign phases
  if loader.hasColumn('Phase')

    phase = loader.getColumnData('Phase');

  else

    phase = ones(length(q),1);

  end

  if max(phase)>max_num_phases

    warning('MTEX:toomanyphases', ...
      ['Found more than ' num2str(max_num_phases) '. I''m going to ignore them all.']);
    phase = ones(size(d,1),1);

  end

  % compute unit cells
  if loader.hasColumn({'x' 'y'})

    varargin = [varargin,'unitCell',....
      calcUnitCell(loader.getColumnData({'x' 'y' 'z'}),varargin{:})];

  end

  % return varargin as options
  opt = loader.getOptions('ignoreColumns','Phase');

  % set up EBSD variable
  CSList{1} = 'notIndexed';
  for k = 1:max(1,length(unique(phase))-1)
    CSList{k+1} = crystalSymmetry('432','mineral',['unknown' int2str(k)]);
  end
  CSList = get_option(varargin,'CS',CSList);
  ebsd = EBSD(q,phase,CSList,opt,varargin{:});

catch
  interfaceError(fname)
end


function [l,n,k,k2] = get_dim(dat)
%   [numEx,vDim,oDim,numCls]=get_dim(data)
%    return (in given order) the number of examples, the dimension of vectors
%    the number of output dimensions and the number of classes.
%
%    Note:
%    Sometimes the number of classes differs from the output dimension
%    (e.g. in binary pattern recognition often oDim equals 1 and numCls
%    equals 2).

  l=length(dat.index);
  n=length(dat.findex);
  k=size(dat.Y,2);
  k2=k;

  if k2==1
    f1=find(dat.Y==1); f2=find(dat.Y==-1);
    if length(f1)>0 & length(f2)>0 & (length(f1)+length(f2))==l
      k2=2;  % -1s and +1s => two classes
    end
  end


bg = 0.7;
im = bg*ones(50,50);

im = ipaste(im, ones(20,20), [5,5]);
im = ipaste(im, ones(10,15), [30,30]);
c = kcircle(10);
c(c==0) = bg;
im = ipaste(im, c, [5,27]);


 function ob = Gtomo2(chat)
%function ob = Gtomo2(chat)
%
%	create default "parent" 2D tomography object (structure)
%	with some basic methods common to all child tomography objects
%	chat: 0 to disable debugging messages, >=1 to display them
%
%	Copyright Mar 2001, Jeff Fessler, University of Michigan

if nargin < 1, chat = 0; end

%
%	the dimensions are usually [ob.nb * ob.na, ob.nx * ob.ny]
%	unless masked, in which case [ob.nb * ob.na, sum(mask(:))]
%	or if tranposed (in which case swapped)
%
ob.dims = [0 0];

ob.nx = 0;	% input image size
ob.ny = 0;
ob.nb = 0;	% output sinogram size (bins)
ob.na = 0;	% output sinogram size (angles)

ob.apower	= 1;		% array power, becomes 2 for G.^2
ob.scale	= 1;		% global scaling factor used in some children
ob.mask		= [];		% [nx,ny] logical array
ob.chat		= chat;
ob.index1	= [];		% row indices (unless transposed) e.g. G(3:9,:)
ob.index2	= [];		% col indices (unless transposed) e.g. G(:,3:9)
				% the empty default means *all* rows/cols
ob.is_transpose = false;
ob.is_masked	= false;	% set to 1 if G(:,mask(:))
%ob.version	= 1.0;

%ob = class(ob, 'Gtomo2');	% matlab inheritence sucks


function load_existing_bgrid_version_A()
    % load existing b-value grid
    % VERSION A
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    report_this_filefun();
    % extracted from the various b cross routines

    [file1,path1] = uigetfile('*.mat','b-value gridfile');
    if length(path1) > 1

        load([path1 file1])
        xsecx = newa(:,end)';
        xsecy = newa(:,7);
        xvect = gx; yvect = gy;
        tmpgri=zeros((length(xvect)*length(yvect)),2);

        normlap2=nan(length(tmpgri(:,1)),1)
        normlap2(ll)= bvg(:,1);
        valueMap=reshape(normlap2,length(yvect),length(xvect));

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

        normlap2(ll)= bvg(:,6);
        meg=reshape(normlap2,length(yvect),length(xvect));

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

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

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

        normlap2(ll)= bvg(:,9);
        stanm=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= bvg(:,10);
        maxm=reshape(normlap2,length(yvect),length(xvect));

        old = valueMap;

        view_bv2
    else
        return
    end
end


function [header_mat,data_mat] = mhdrload(file)
%MHDRLOAD Load data from an ASCII file containing multiple text
% headers throughout the file.
% [header, data] = MHDRLOAD('filename.ext') reads a data file
% called 'filename.ext', which contains a text header.  There
% is no default extension; any extensions must be explicitly
% supplied.
%
% The first output, HEADER, is the header information, returned
% as a text array.
% The second output, DATA, is the data matrix.  This data matrix
% has the same dimensions as the data in the file, one row per
% line of ASCII data in the file.  If the data is not regularly
% spaced (i.e., each line of ASCII data does not contain the
% same number of points), the data is returned as a column
% vector.
%
% Limitations:  No lines of the text header can begin with
% a number.  The header must come before the data.
%
% MODIFIED from hdrload.m: Dec 20, 2002  Jeff Daniels, NSWCCD - ARD
% UPDATED September 20, 2006, J. Daniels
%
% See also LOAD, SAVE, SPCONVERT, FSCANF, FPRINTF, STR2MAT, HDRLOAD.
% See also the IOFUN directory.
%
% EXAMPLE:
%   If example_data.txt is:
%   Recorded Data: 12/15/2001
%   header 1
%   rows = 2 cols = 2
%   12 23
%   34 21
%   header 2
%   rows = 3 cols = 3
%   19 73 13
%   33 32 47
%   34 12 68
%
%   MHDRLOAD returns:
% 	header(:,:,1) =
%
% 	Recorded Data: 12/15/2001
% 	header 1
% 	rows = 2 cols = 2
%
% 	header(:,:,2) =
%
% 	header 2
% 	rows = 3 cols = 3
%
% 	data(:,:,1) =
%
%        12    23     0
%        34    21     0
%         0     0     0
%
% 	data(:,:,2) =
%
%        19    73    13
%        33    32    47
%        34    12    68

% check number and type of arguments
if nargin < 1
    error('Function requires one input argument');
elseif ~ischar(file)
    error('Input argument must be a string representing a filename');
end

% Open the file.  If this returns a -1, we did not open the file
% successfully.
fid = fopen(file);
if fid==-1
    error('File not found or permission denied.');
end

% Initialize loop variables
% We store the number of lines in the header, and the maximum length
% of any one line in the header.  These are used later in assigning
% the 'header' output variable.
no_lines = 0;
max_line = 0;

% We also store the number of columns in the data we read.  This way
% we can compute the size of the output based on the number of
% columns and the total number of data points.
ncols = 0;

% Finally, we initialize the data to [].
data = [];
j=1;

% Start processing.
line = fgetl(fid);
if ~ischar(line)
    disp('Warning: file contains no header and no data')
end;

while line~=-1
    [data, ncols, errmsg, nxtindex] = sscanf(line, '%f');
    % One slight problem, pointed out by Peter VanderWal: If the first
    % character of the line is 'e', then this will scan as 0.00e+00.
    % We can trap this case specifically by using the 'next index'
    % output: in the case of a stripped 'e' the next index is one,
    % indicating zero characters read.  See the help entry for 'sscanf'
    % for more information on this output parameter.
    % We loop through the file one line at a time until we find some
    % data.  After that point we stop checking for header information.
    % This part of the program takes most of the processing time, because
    % fgetl is relatively slow (compared to fscanf, which we will use
    % later).
    while isempty(data) | nxtindex==1
		no_lines = no_lines+1;
		max_line = max([max_line, length(line)]);
		% Create unique variable to hold this line of text information.
		% Store the last-read line in this variable.
		eval(['line', num2str(no_lines), '=line;'])
		line = fgetl(fid);
		if ~ischar(line)
			disp('Warning: file contains no data')
		break
		end;
		[data, ncols, errmsg, nxtindex] = sscanf(line, '%f');
    end % while

    % Create header output from line information. The number of lines and
	% the maximum line length are stored explicitly, and each line is
	% stored in a unique variable using the 'eval' statement within the
	% loop. Note that, if we knew a priori that the headers were 10 lines
	% or less, we could use the STR2MAT function and save some work.
	% First, initialize the header to an array of spaces.
	header_mat(1:no_lines,1:max_line,j) = char(' '*ones(no_lines, max_line));
	for i = 1:no_lines
		if length(eval(['line' num2str(i)]))
          		varname = eval(['line' num2str(i)]);
        	else
            		varname = ['line',num2str(i)];
        	end
		% Note that we only assign this line variable to a subset of this
		% row of the header array.  We thus ensure that the matrix sizes in
		% the assignment are equal.
		%eval(['header(i, 1:length(' varname ')) = ' varname ';']);
		header_mat(i,1:length(varname),j)=varname;
	end

    % Now that we have read in the first line of data, we can skip the
    % processing that stores header information, and just read in the
    % rest of the data.
    data = [data; fscanf(fid, '%f')];
    % Resize output data, based on the number of columns (as returned
    % from the sscanf of the first line of data) and the total number of
    % data elements. Since the data was read in row-wise, and MATLAB
    % stores data in columnwise format, we have to reverse the size
    % arguments and then transpose the data.  If we read in irregularly
    % spaced data, then the division we are about to do will not work.
    % Therefore, we will trap the error with an EVAL call; if the reshape
    % fails, we will just return the data as is.
    eval('data_mat(1:length(data)/ncols,1:ncols,j) = reshape(data, ncols, length(data)/ncols)'';', '')
    line = fgetl(fid);
    j=j+1;
    no_lines = 0;
end

fclose(fid);
% And we're done!


% test_all_mex
% make sure all mex files can execute
% by running the internal "check" of each.

list_spline = {
	'BsplCo2GdXMirr', ...
	'BsplCo2GdXTranMirr', ...
	'BsplCo2GdXTranZero', ...
	'BsplCo2GdXZero', ...
	'BsplCo2GdYMirr', ...
	'BsplCo2GdYTranMirr', ...
	'BsplCo2GdYTranZero', ...
	'BsplCo2GdYZero', ...
	'BsplCo2GdZMirr', ...
	'BsplCo2GdZTranMirr', ...
	'BsplCo2GdZTranZero', ...
	'BsplCo2GdZZero', ...
	'BsplCo2ValMirr', ...
	'BsplCo2ValTranMirr', ...
	'BsplCo2ValTranZero', ...
	'BsplCo2ValTranZeroFilt', ...
	'BsplCo2ValZero', ...
	'BsplCo2ValZeroFilt', ...
	'BsplExpand', ...
	'BsplReduce', ...
	'BsplVal2CoMirr', ...
	'BsplVal2CoZero'
};

list = {
	'jf_mex', ...
	'dtft_mex', ...
	'exp_xform_mex', ...
	'mri_exp_mult_mex', ...
...
	'interp1_table_adj_mex', ...
	'interp1_table_mex', ...
	'interp2_table_adj_mex', ...
	'interp2_table_mex', ...
	'interp3_table_adj_mex', ...
	'interp3_table_mex', ...
...
	'penalty_mex', ...
	'rotmex', ...
	'wtfmex', ...
	'f3d_mex', ...
...
	'delaysum1_mex', ...
	'ir_shrink1_mex', ...
	'ir_tridiag_inv_mex', ...
...
	list_spline{:}
};

% check for UM-only mex files
if exist('dd_ge1_mex') == 3
	list{end+1} = 'dd_ge1_mex';
end
if exist('dd_ge2_mex') == 3
	list{end+1} = 'dd_ge2_mex';
end

is_missing = false(1, numel(list));
for ii=1:numel(list)
	mex = list{ii};
%	pr mex
	if exist(mex) ~= 3
		is_missing(ii) = true;
	end
end

if any(is_missing)
	printf(' ')
	printm('These mex files are missing:')
%	pr find(is_missing)
%	list{is_missing}
	pr list(is_missing)
prompt
	list = list(~is_missing);
end

passed = '';
failed = '';
missing = '';
for ii=1:numel(list)
	mex = list{ii};
	pr mex
	if exist(mex) ~= 3
		missing = [missing ' ' mex];
		continue;
	end
	try
		fun = str2func(mex);
		fun('check')
		passed = [passed ' ' mex];
	catch
		failed = [failed ' ' mex];
	end
end

if ~isempty(missing) || ~isempty(failed)

	if ~isempty(missing)
		printm(['\nThese mex files are missing: ' missing])
	end

	if ~isempty(failed)
		printm(['\nThese mex files failed: ' failed])
	end

	if ~isempty(passed)
		printm(['\nThese mex files passed: ' passed])
		printm 'So perhaps some things will still work.'
	end

	printm 'Sorry, you seem to have mex problems. :-('
	printm 'Probably you are a PC user and Windoze is not supported.'
	printm 'Or (in linux) there may be a gcc library version issue?'
	printm 'Or you may have a path problem.'

else
	printm '\n----------------------------------------------------------'
	printm(['All mex files present and passed:\n' passed])
	printm '----------------------------------------------------------\n'
end