function [planC, leksellInfo] = importLeksellPlan(planDir)
%"importLeksellPlan"
%   Imports a Leksell gamma knife plan into CERR format.  The directory
%   structure of the Leksell plan must be intact.
%
%By JRA 06/24/05
%
%LM: KRK, 05/31/07, all readLeksell<...>File functions are now complete and
%                   included in the importLeksellPlan function
%    KRK, 06/01/07, corrected the transform matrices of the scans
%    KRK, 06/04/07, added missing code in the structure import section to
%                   account for non associated scans
%    KRK, 06/05/07, added a second output variable (leksellInfo) to hold all
%                   information from the plan directory for easy access into
%                   the variables not currently used in CERR (metadata)
%    KRK, 06/07/07, the code for converting the normalized percentages in
%                   the dose matrices to units of Gy is now complete
%    KRK, 06/08/07, rescaled the imported scan images' intensities (MR only)
%                   so that they can now be viewed with the CERR CT Window
%                   preset "Head"
%    DK , 07/01/08, Rewrote the way directories are read. Change in file
%                   names and missing directories causing errors. Typo
%                   errors in converting mm to cm. Also typo error in
%                   reading CT Loop.
%
%Usage:
%   planC = importLeksellPlan(planDir)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

LekC = [];

files = dir(planDir);
lekSellDirStr = {files.name};

%%%%%%%%%%%%%%%%% Importing directories %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1: length(lekSellDirStr)
    if files(i).isdir
        if strfind(upper(lekSellDirStr{i}), 'MR')
            LekC = readLeksellDir(planDir,'MR', LekC, lekSellDirStr{i});
        elseif strfind(lekSellDirStr{i},'CT')
            LekC = readLeksellDir(planDir,'CT', LekC, lekSellDirStr{i});
        else
            %             try
            LekC = readLeksellDir(planDir, lekSellDirStr{i}, LekC, lekSellDirStr{i});
            %             catch
            %                 disp(['No Import Options for ' lekSellDirStr{i} ' ...'])
            %                 continue
            %             end
        end
    end
end

%--------Initialize planC-------------------------------------------------%
planC   = initializeCERR;
indexS  = planC{end};
planC{indexS.CERROptions} = CERROptions;

%--------Initialize scan information--------------------------------------%
if isfield(LekC, 'mrScanS')
    for i=1:length(LekC.mrScanS)
        planC{indexS.scan}(i).scanType = LekC.mrScanS(i).scanInfo(1).scanType;
        bool = ismember({LekC.studyS.modality}, LekC.mrScanS(i).scanInfo(1).scanType);
        matches = find(bool);
        if isempty(matches)
            planC{indexS.scan}(i).transM = [];
        else
            planC{indexS.scan}(i).transM = LekC.studyS(matches(1)).rcsToxyzTransM;
        end

        planC{indexS.scan}(i).scanArray = LekC.mrScanS(i).scanArray;
        planC{indexS.scan}(i).scanInfo = LekC.mrScanS(i).scanInfo;

        planC{indexS.scan}(i).scanUID = createUID('scan');

        scanTypeC = {planC{indexS.scan}(i).scanInfo(:).scanType};
        matchC = strfind(upper(scanTypeC), 'COR');
        toDelete = [];
        for indMatch = 1:length(matchC)
           if ~isempty(matchC{indMatch})  && matchC{indMatch} == 1
              toDelete = [toDelete indMatch];
           end
        end

        planC{indexS.scan}(i).scanInfo(toDelete) = [];

        planC{indexS.scan}(i).scanArray(:,:,toDelete) = [];

        for indSI = 1:length(planC{indexS.scan}(i).scanInfo)
           planC{indexS.scan}(i).scanInfo(indSI).imageType = 'MR';
        end

    end
end

if isfield(LekC, 'ctScanS')

    for i = 1:length(LekC.ctScanS)
        indX = length(planC{indexS.scan}) + 1;
        planC{indexS.scan}(indX).scanType = LekC.ctScanS(i).scanInfo(1).scanType;

        bool = ismember({LekC.studyS.modality}, LekC.ctScanS(i).scanInfo(1).scanType);
        matches = find(bool);
        planC{indexS.scan}(indX).transM = LekC.studyS(matches(1)).rcsToxyzTransM;

        planC{indexS.scan}(indX).scanArray = LekC.ctScanS(i).scanArray;
        planC{indexS.scan}(indX).scanInfo = LekC.ctScanS(i).scanInfo;

        planC{indexS.scan}(indX).scanUID = createUID('scan');

        for indSI = 1:length(planC{indexS.scan}(indX).scanInfo)
           planC{indexS.scan}(indX).scanInfo(indSI).imageType = 'CT';
        end

    end
end

%Remove transM if importing only one scan
if length(planC{indexS.scan}) == 1
    planC{indexS.scan}(1).savedtransM.transM = planC{indexS.scan}(1).transM;
    planC{indexS.scan}(1).savedtransM.name = 'GammaKnifeImport';
    planC{indexS.scan}(1).transM = [];
end

%Set the uniformized scan data in the plan (planC{indexS.scan})
planC = setUniformizedData(planC);
%The original transformation matrices read in by the readLeksellStudy
%function contained scaling as well as transformation/rotation.  Since CERR
%is compatible with only transformation/rotation matrices and scales
%according to its 3 voxel sizes, the scaling needs to be removed from the
%current transformation matrices.  To do this, multiply the original transM
%by the inverse of the pure scaling matrix (multiplied by 10 since the
%voxel sizes are in cm and must be mm).
for i=1:length(planC{indexS.scan})
    if ~isempty(planC{indexS.scan}(i).transM)
        planC{indexS.scan}(i).transM = planC{indexS.scan}(i).transM / [planC{indexS.scan}(i).uniformScanInfo.grid1Units*10 0 0 0; 0 planC{indexS.scan}(i).uniformScanInfo.grid2Units*10 0 0; 0 0 planC{indexS.scan}(i).uniformScanInfo.sliceThickness*10 0; 0 0 0 1];
        planC{indexS.scan}(i).transM(3,4) = planC{indexS.scan}(i).transM(3,4) - planC{indexS.scan}(i).uniformScanInfo.firstZValue;
    end
end

%-----------------Load structure(s)---------------------------------------%
structNum = 1;
nonAssocCounter = 0;
for i=1:length(LekC.volS)
    %Check if the scan is either MR or CT, if not, disregard
    regTo = LekC.volS(i).registeredTo;
    bool = ismember({planC{indexS.scan}.scanType}, regTo);
    associatedScan = find(bool);
    if isempty(associatedScan)
        %Continue if not associated with any scan, eg Leksell Skull.
        nonAssocCounter = nonAssocCounter + 1; %keep a count of the non associated scans to index associated scans correctly
        continue;
    end

    %Check for contours done on fused images (slicenums are therefore out of
    %the range CT and MR images).  There may be a way to map these fusion
    %contours to MR or CT, possibly using the information from
    %LekC.fusionS, but it hasn't been completed yet.
    fusionContour = 0;
    for j=1:length(LekC.volS(i).contour)
        for k=1:length(planC{indexS.scan})
            if(LekC.volS(i).contour(j).sliceNum > length(planC{indexS.scan}(k).scanInfo))
                fusionContour = 1;
                break;
            end
        end
    end
    if(fusionContour ~= 0)
        nonAssocCounter = nonAssocCounter + 1;
        continue;
    end

    %After checking if its associated, put in the structure information
    newStructS = newCERRStructure(associatedScan, planC);
    planC{indexS.structures} = dissimilarInsert(planC{indexS.structures},newStructS,i - nonAssocCounter);
    planC{indexS.structures}(i - nonAssocCounter).structureName = LekC.volS(i).structName;
    contour = LekC.volS(i).contour;
    for j=1:length(contour)
        sliceNum = contour(j).sliceNum + 1; %+ 1 to match Matlab's indexing (1-n+1 rather than 0-n)
        %scale the xy points based on the voxel sizes
        xyPoints = contour(j).contour;
        xyPoints(:,1) = planC{indexS.scan}(associatedScan).uniformScanInfo.grid1Units * contour(j).contour(:,1);
        xyPoints(:,2) = planC{indexS.scan}(associatedScan).uniformScanInfo.grid2Units * contour(j).contour(:,2);
        %set z values for the current x,y vertices
        xyPoints = [xyPoints ones(size(xyPoints(:,1)))*planC{indexS.scan}(associatedScan).scanInfo(sliceNum).zValue];
        %store the xyz points of each vertex
        planC{indexS.structures}(i - nonAssocCounter).contour(sliceNum).segments.points = xyPoints;
    end
    structNum = structNum + 1; %keep a count of all of the associated structures
    planC{indexS.structures}(i - nonAssocCounter).strUID = createUID('structure');
    planC{indexS.structures}(i - nonAssocCounter).assocScanUID = planC{indexS.scan}(associatedScan).scanUID;

    %Remove the contours from the second return variable to save space.
    %Only do this if the contour is read into CERR. In other words, don't
    %remove the contours from this return variable if they are from a non
    %associated scan (any contour not done on MR or CT, ex: fused).
    LekC.volS(i).contour = [];
end
%Calculate how to display the contoured segments inside of CERR
planC = getRasterSegs(planC);

%------------Load dose information----------------------------------------%
normalizingConst = -1; %used to find the global maximum normalizing constant in the dose matrix (see readLeksellDoseGroupFile for more information)
%Put dose info into the CERR data structure.

if isfield(LekC,'shotS')
    for i=1:length(LekC.shotS.doseMatrixInfo)
        dMI = LekC.shotS.doseMatrixInfo(i);

        planC{indexS.dose}(i).fractionGroupID = dMI.name;
        planC{indexS.dose}(i).horizontalGridInterval = dMI.gridSize;
        planC{indexS.dose}(i).verticalGridInterval = dMI.gridSize;
        planC{indexS.dose}(i).depthGridInterval = dMI.gridSize;

        try
            planC{indexS.dose}(i).doseArray = LekC.doses{i};
        catch
            planC{indexS.dose}(i) = [];
            continue
        end

        % Temporarily hold the max of each dose matrix to see if it is larger
        % than the other dose matrices' max value. If it is, store the new
        % larger value in normalizingConst (this only affects plans with multiple DMs).
        tmpNorm = max(planC{indexS.dose}(i).doseArray(:));
        if(tmpNorm > normalizingConst)
            normalizingConst = tmpNorm;
        end

        planC{indexS.dose}(i).coord1OFFirstPoint = LekC.shotS.doseMatrixInfo(i).minExtent(1);
        planC{indexS.dose}(i).coord2OFFirstPoint = LekC.shotS.doseMatrixInfo(i).minExtent(2);
        planC{indexS.dose}(i).coord3OfFirstPoint = LekC.shotS.doseMatrixInfo(i).minExtent(3);

        siz = size(planC{indexS.dose}(i).doseArray);
        planC{indexS.dose}(i).sizeOfDimension1 = siz(2);
        planC{indexS.dose}(i).sizeOfDimension2 = siz(1);
        planC{indexS.dose}(i).sizeOfDimension3 = siz(3);

        planC{indexS.dose}(i).zValues = linspace(LekC.shotS.doseMatrixInfo(i).minExtent(3), LekC.shotS.doseMatrixInfo(i).maxExtent(3), siz(3));

        planC{indexS.dose}(i).doseUID = createUID('dose');
        planC{indexS.dose}(i).doseUnits = 'Gy';
        planC{indexS.dose}(i).assocScanUID = [];
    end
end
%Normalize the dose arrays and convert them to Gy using previously found max.
%This converts all dose matrix values into CERR's native radiation units, Gy.
for i=1:length(planC{indexS.dose})
    planC{indexS.dose}(i).doseArray = (LekC.superS.globalMaxDose)*(planC{indexS.dose}(i).doseArray)/normalizingConst;
end

%Log end of import

%-------------------Store metadata----------------------------------------%
%Put all information obtained from the readLeksell<...>File functions into
%the other return variable to view and/or possibly incorporate into CERR.
%Also, get rid of some of the larger pieces of data (doses, pixel arrays)
%that have already been read into the CERR variable to save space.  See the
%"Load Structures" section of this function to see how the contours are
%removed from this variable.

LekC.doses = [];
try
    for i=1:length(LekC.ctScanS)
        LekC.ctScanS(i).scanArray = [];
    end
end
try
    for i=1:length(LekC.mrScanS)
        LekC.mrScanS(i).scanArray = [];
    end
end
leksellInfo = LekC;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%% READ THE DIRECTORY STRUCTURE OF LEKSELL %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function LekC = readLeksellDir(planDir,dirName, LekC, mrctdir)

switch dirName

    case 'Fusions'
        %Get Fusion info. (not used in CERR currently)
        disp('Reading Fusion info...')
        % fusionsFilename = fullfile(planDir, 'Fusions', 'Fusion.1');
        fusionsFilename = getLeksellFilesNames(fullfile(planDir, 'Fusions'), 'Fusion');
        for i = 1:length(fusionsFilename)
            LekC(i).fusionS = readLeksellFusionFile(fullfile(planDir, 'Fusions', fusionsFilename{i}));
        end

    case 'Orientations'
        %Get Orientations info. (not used in CERR currently)
        disp('Reading Orientations info...')
        % oriFilename = fullfile(planDir, 'Orientations', 'Orientation.1');
        oriFilename = getLeksellFilesNames(fullfile(planDir, 'Orientations'), 'Orientation');
        for i = 1:length(oriFilename)
            LekC(i).oriS = readLeksellOrientationFile(fullfile(planDir, 'Orientations', oriFilename{i}));
        end

    case 'SRdata'
        %Get Dosegroup data.
        disp('Reading Dosegroup info...')
        % doseFilename = fullfile(planDir, 'SRdata', ['DoseGroup' num2str(doseNum) '.1']);

        doseFilename = getLeksellFilesNames(fullfile(planDir, 'SRdata'), 'DoseGroup');

        for i = 1:length(doseFilename)
            LekC.doses{i} = readLeksellDoseGroupFile(fullfile(planDir, 'SRdata', doseFilename{i}));
        end

        %Get skull info. (not used in CERR currently)
        disp('Reading Skull info...')
        % skullFilename = fullfile(planDir, 'SRdata', 'Skull.1');
        skullFilename = getLeksellFilesNames(fullfile(planDir, 'SRdata'), 'Skull');
        for i = 1:length(skullFilename)
            LekC(i).skullS = readLeksellSkullFile(fullfile(planDir, 'SRdata', skullFilename{i}));
        end

        %Get super info.
        disp('Reading Super info...')

        % superFilename = fullfile(planDir, 'SRdata', 'Super.1');
        superFilename = getLeksellFilesNames(fullfile(planDir, 'SRdata'), 'Super');
        for i = 1:length(superFilename )
            LekC(i).superS = readLeksellSuperFile(fullfile(planDir, 'SRdata', superFilename{i}));
        end

        %Get target frame info. (not used in CERR currently)
        disp('Reading TargetFrame info...')
        % targetframeFilename = fullfile(planDir, 'SRdata', 'TargetFrame.1');
        targetframeFilename = getLeksellFilesNames(fullfile(planDir, 'SRdata'), 'TargetFrame');
        for i = 1:length(targetframeFilename)
            LekC(i).targetframeS = readLeksellTargetframeFile(fullfile(planDir, 'SRdata', targetframeFilename{i}));
        end

    case 'Shots'
        %Get the shot info.
        disp('Reading Shot info...')

        % shotFilename = fullfile(planDir, 'Shots', 'Shot.1');
        shotFilename = getLeksellFilesNames(fullfile(planDir, 'Shots'), 'Shot');

        if isempty(shotFilename)
            shotFilename = getLeksellFilesNames(fullfile(planDir, 'Shots'), 'Group');
        end

        for i = 1:length(shotFilename)
            LekC(i).shotS = readLeksellShotsFile(fullfile(planDir, 'Shots', shotFilename{i}));
        end

    case 'Studyregs'
        %Get the studyReg info. (not used in CERR currently)
        disp('Reading StudyReg info...')
        % srFilename = fullfile(planDir, 'Studyregs', 'Studyreg.1');
        srFilename = getLeksellFilesNames(fullfile(planDir, 'Studyregs'), 'studyreg');
        for i = 1:length(srFilename)
            LekC(i).studyRegS = readLeksellStudyregFile(fullfile(planDir, 'Studyregs', srFilename{i}));
        end

    case 'Studys'
        %Get the study info.
        disp('Reading Study info...')
        % studyFilename = fullfile(planDir, 'Studys', 'Study.1');
        studyFilename = getLeksellFilesNames(fullfile(planDir, 'Studys'), 'Study');
        for i = 1:length(studyFilename)
            LekC(i).studyS = readLeksellStudyFile(fullfile(planDir, 'Studys', studyFilename{i}));
        end

    case 'Volumes'
        %Get volume info.
        disp('Reading Volume info...')
        % volFilename = fullfile(planDir, 'Volumes', 'Volume.1');
        volFilename  = getLeksellFilesNames(fullfile(planDir, 'Volumes'), 'Volume');
        for i = 1:length(volFilename)
            LekC(i).volS = readLeksellVolumeFile(fullfile(planDir, 'Volumes', volFilename{i}));
        end

    case 'Plugs'
        %Get plug info. (not used in CERR currently)
        disp('Reading Plug info...')

        % plugFilename = fullfile(planDir, 'Plugs', 'Plug.1');
        plugFilename = getLeksellFilesNames(fullfile(planDir, 'Plugs'), 'Plug');
        for i = 1:length(plugFilename)
            LekC(i).plugS = readLeksellPlugFile(fullfile(planDir, 'Plugs', plugFilename{i}));
        end

    case 'Sortings'
        %Get sorting info. (not used in CERR currently)
        disp('Reading Sorting info...')
        % sortingFilename = fullfile(planDir, 'Sortings', 'Sorting.1');
        sortingFilename = getLeksellFilesNames(fullfile(planDir, 'Sortings'), 'Sorting');
        for i = 1:length(sortingFilename)
            LekC(i).sortingS = readLeksellSortingFile(fullfile(planDir, 'Sortings', sortingFilename{i}));
        end

    case 'Thresholds'
        %Get threshold info. (not used in CERR currently)
        disp('Reading Threshold info...')
        % thresholdFilename = fullfile(planDir, 'Thresholds', 'Threshold.1');
        thresholdFilename = getLeksellFilesNames(fullfile(planDir, 'Thresholds'), 'Threshold');
        for i = 1:length(thresholdFilename)
            LekC(i).thresholdS = readLeksellThresholdFile(fullfile(planDir, 'Thresholds', thresholdFilename{i}));
        end

    case 'MR'
        disp('Reading MR scan info...')

        if isfield(LekC,'mrScanS')
            indX = length(LekC.mrScanS) + 1;
        else
            indX = 1;
        end

        imageDir = fullfile(planDir, mrctdir);
        [mat, scanInfo] = readLeksellImageset(imageDir,'MR');
        if isempty(mat)
            return
        end
        LekC.mrScanS(indX).scanArray = mat;
        LekC.mrScanS(indX).scanInfo = scanInfo;
        %Put the pixel intensities in the range of 1000-1700. This code works, but
        %is not generally correct.  Modify the commented code under this to correct
        %the MR pixel intensity problem.
        %LekC.mrScanS(indX).scanArray = LekC.mrScanS(indX).scanArray - median(LekC.mrScanS(indX).scanArray(:)) + 1000;
        LekC.mrScanS(indX).scanArray = LekC.mrScanS(indX).scanArray; % - median(LekC.mrScanS(indX).scanArray(:)) + 1000;
        %Match the scan to the study, then subtract the lower of the ranges to
        %standardize the pixel intensity ranges (make it go from 0-722 rather than
        %its original values in the range of 32000-33000).
        %    for j=1:length(LekC.studyS)
        %        if(strmatch(LekC.studyS(j).modality, LekC.mrScanS(indX).scanInfo(1).scanType))
        %            LekC.mrScanS(indX).scanArray = LekC.mrScanS(indX).scanArray -
        %            LekC.studyS(j).pixelIntensityRange(1);
        %            break;
        %        end
        %    end

    case 'CT'
        if isfield(LekC,'ctScanS')
            indX = length(LekC.ctScanS) + 1;
        else
            indX = 1;
        end
        disp('Reading CT scan info...')

        imageDir = fullfile(planDir, mrctdir);

        [mat, scanInfo] = readLeksellImageset(imageDir,'CT');
        if isempty(mat)
            return
        end

        LekC.ctScanS(indX).scanInfo = scanInfo;

        LekC.ctScanS(indX).scanArray = mat;
end


function gui_sc (action)
%
% This file is used by FASTICAG

% This file holds the callbacks for save-dialog

% @(#)$Id$

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Global variables

% Handle to the window
global hf_FastICA_Save;

% Handles to some of the controls in window
global he_FastICA_suffix;

% The needed main variables
global g_FastICA_ica_sig;
global g_FastICA_ica_A;
global g_FastICA_ica_W;
global g_FastICA_white_sig;
global g_FastICA_white_wm;
global g_FastICA_white_dwm;
global g_FastICA_pca_E;
global g_FastICA_pca_D;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This should not take long...
watchonInFigure = watchon;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch action
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'Save'

 suffix = deblank(get(he_FastICA_suffix, 'String')); % The suffix for the variables

 fprintf('Saving results in variables in Matlab workspace.\n');
 assignin('base',['IC' suffix],g_FastICA_ica_sig);
 assignin('base',['A' suffix],g_FastICA_ica_A);
 assignin('base',['W' suffix],g_FastICA_ica_W);
 assignin('base',['whitesig' suffix],g_FastICA_white_sig);
 assignin('base',['whiteningMatrix' suffix],g_FastICA_white_wm);
 assignin('base',['dewhiteningMatrix' suffix],g_FastICA_white_dwm);
 assignin('base',['E' suffix],g_FastICA_pca_E);
 assignin('base',['D' suffix],g_FastICA_pca_D);

 close(hf_FastICA_Save);                  % close the dialog

 % Use return to avoid reaching the watchoff statement at the end
 % (There used to be a 'break' statement here, but it resulted in
 % errors in more recent version of Matlab -- jarmo)
 return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'Cancel'

 close(hf_FastICA_Save);                       % do nothing just exit

 % Use return to avoid reaching the watchoff statement at the end
 % (There used to be a 'break' statement here, but it resulted in
 % errors in more recent version of Matlab -- jarmo)
 return;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'Help'

 gui_help('gui_sc');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end    % switch

watchoff (watchonInFigure);


classdef TensorVoigtConverterFactory < handle

    properties (Access = protected)
        input
    end

    methods (Access = protected)

        function itIs = isStrainTensor(obj)
            itIs = strcmp(obj.input.getFieldName(),'strain');
        end

        function itIs = isStressTensor(obj)
            itIs = strcmp(obj.input.getFieldName(),'stress');
        end

        function itIs = isComplianceTensor(obj)
            itIs = strcmp(obj.input.getFieldName,'compliance');
        end

        function itIs = isStiffnessTensor(obj)
            itIs = strcmp(obj.input.getFieldName,'stiffness');
        end

        function itIs = is3D(obj)
            itIs = strcmp(obj.input.getElasticityCase,'3D');
        end

        function itIs = isPlaneStress(obj)
            itIs = strcmp(obj.input.getElasticityCase,'planeStress');
        end

    end

    methods (Access = private, Static)

        function showError()
            error('Not admitted object to transform')
        end
    end

end


function [seq_info]=load_seq_info(base_path,seq_name)
%This function loads the information of the video corresponding to the
%given path seq_path, which is modified from
    % GENCONFIG
    % Generate a configuration of a sequence
    %
    % INPUT:
    %   dataset - The name of dataset ('otb','vot2013','vot2014','vot2015')
    %   seqName - The name of a sequence in the given dataset
    %
    % OUTPUT:
    %   config - The configuration of the given sequence
    %
    % Hyeonseob Nam, 2015
    %
% Input:
%       base_path - the base path of the sequences
%       seq_name -  the name of the sequence
% Output:
%       seq_info - a two-filed block including the path of each image file
%       (seq_info.img) and the groundtruth (seq_info.gt).

% By Xin Li, 2017-3-8
%%
seq_info.seq_name=seq_name;

%% load images
% handle special sequences
switch(seq_info.seq_name)
    case {'Jogging-1', 'Jogging-2'}
        seq_info.img_dir = fullfile(base_path, 'Jogging', 'img');
    case {'Skating2-1', 'Skating2-2'}
        seq_info.img_dir = fullfile(base_path, 'Skating2', 'img');
    otherwise
        seq_info.img_dir = fullfile(base_path, seq_info.seq_name, 'img');
end

 if(~exist(seq_info.img_dir,'dir'))
        error('%s does not exist!!',seq_info.img_dir);
 end

 % parse img list
  seq_info.img_list = parseImg(seq_info.img_dir);
  switch(seq_info.seq_name)
      case 'David'
          seq_info.img_list = seq_info.img_list(300:end);
      case 'Tiger1'
          seq_info.img_list = seq_info.img_list(6:end);
  end

  % load gt
  switch(seq_info.seq_name)
      case 'Jogging-1'
          gtPath = fullfile(base_path, 'Jogging', 'groundtruth_rect.1.txt');
      case 'Jogging-2'
          gtPath = fullfile(base_path, 'Jogging', 'groundtruth_rect.2.txt');
      case 'Skating2-1'
          gtPath = fullfile(base_path, 'Skating2', 'groundtruth_rect.1.txt');
      case 'Skating2-2'
          gtPath = fullfile(base_path, 'Skating2', 'groundtruth_rect.2.txt');
      case 'Human4'
          gtPath = fullfile(base_path, 'Human4', 'groundtruth_rect.txt');
      otherwise
          gtPath = fullfile(base_path, seq_info.seq_name, 'groundtruth_rect.txt');
  end

  if(~exist(gtPath,'file'))
      error('%s does not exist!!',gtPath);
  end

  gt = importdata(gtPath);
  switch(seq_info.seq_name)
      case 'Tiger1'
          gt = gt(6:end,:);
      case {'Board','Twinnings'}
          gt = gt(1:end-1,:);
  end

  seq_info.gt = gt;

  nFrames = min(length(seq_info.img_list), size(seq_info.gt,1));
  seq_info.img_list = seq_info.img_list(1:nFrames);
  seq_info.gt = seq_info.gt(1:nFrames,:);
  seq_info.nFrames = nFrames;


function stability=step_computeStability(partRate,net,layerID,theConf,fileRoot,partList)
selectPatternRatio=1.0;
patchNumPerPattern=100;
load(sprintf('%s/imdb.mat',fileRoot),'meta');
Name_batch=net.meta.classes.name{1};

if(strcmp(Name_batch,'n01443537'))
    partList=1;
end

convnet=getConvNetPara(net);
net=vl_simplenn_tidy(net);
net=our_vl_simplenn_move(net,'gpu') ;
assert(layerID>0);
stability=computeStability(partRate,net,Name_batch,selectPatternRatio,patchNumPerPattern,partList,theConf,layerID,convnet,meta.dataMean);
disp(stability);
end


%%train network config
param.caffe_path=fullfile(fileparts(pwd),'matcaffe');
param.solver_netfile=fullfile(fileparts(pwd),'model','solver_bn.prototxt');
param.fintune_model=fullfile(fileparts(pwd),'pretrain_model','googlenet_bn.caffemodel');
param.test_net_file=fullfile(fileparts(pwd),'model','test_bn.prototxt');
param.test_batch_size=16;
param.result_save_file='result.txt';
param.save_model_file='model_cross';
param.save_model_name='base_train_cross';
param.test_interval=500;
param.train_maxiter=4000;
param.data_path=fullfile(fileparts(pwd),'generate_data');
param.traindata_filename='train_data_Prid';
param.testdata_filename='test_data_Prid';
param.use_data_split_index=1;
param.data_split_num=1;
param.train_person_num=150;
param.use_gpu=1;
param.gpu_id=0;
%%
for split_index=param.use_data_split_index:param.data_split_num
    if ~exist(strcat(param.save_model_file,num2str(split_index)),'file')
        mkdir(strcat(param.save_model_file,num2str(split_index)));
    end
    load(strcat(param.data_path,param.traindata_filename,num2str(split_index),'/train_data.mat'));
    %% find caffe
    cur_path=pwd;
    addpath(genpath(param.caffe_path))
    cd(param.caffe_path);
    caffe.reset_all;
    caffe.init_log(fullfile(cur_path,'log'));
    addpath(param.caffe_path);
    if param.use_gpu
        caffe.set_mode_gpu;
    else
        caffe.set_mode_cpu;
    end
    cd(cur_path);
    caffe_solver=caffe.get_solver(param.solver_netfile,param.gpu_id);
    net=caffe.get_net(param.test_net_file,'test');
    caffe_solver.use_caffemodel(param.fintune_model);
    input_data_shape=caffe_solver.nets{1}.blobs('data').shape;
    batch_size=input_data_shape(4);
    batch_data=zeros(input_data_shape,'single');
    batch_label=zeros(1,1,1,batch_size,'single');
    train_x_axis=[];
    train_y_axis=[];
    iter=0;
    while iter<param.train_maxiter

        [batch_data,batch_label]=get_train_minibatch(batch_data,batch_label,batch_size,train_data_cam1,train_data_cam2,label_train_cam1,label_train_cam2);
        caffe_solver.nets{1}.blobs('data').set_data(batch_data);
        caffe_solver.nets{1}.blobs('label').set_data(batch_label);
        caffe_solver.step(1);
        iter = caffe_solver.iter;
        if mod(iter,10)==0
            soft_loss=caffe_solver.nets{1}.blobs('loss3/loss').get_data;
            acc=caffe_solver.nets{1}.blobs('loss3/top-1').get_data;
            loss1=caffe_solver.nets{1}.blobs('loss1/loss').get_data;
            loss2=caffe_solver.nets{1}.blobs('loss2/loss').get_data;
%             loss4=caffe_solver.net.blobs('loss4').get_data;
            train_x_axis=[train_x_axis,iter];
            train_y_axis=[train_y_axis,soft_loss];
            plot(train_x_axis,train_y_axis);
            drawnow;
            fprintf('iter= %d ,softmaxloss= %f ,loss1=%f  loss2=%f\n',iter,soft_loss,loss1,loss2);
        end
        if mod(iter,param.test_interval)==0
            caffe_solver.nets{1}.save(strcat(param.save_model_file,num2str(split_index),'/',param.save_model_name,'_',num2str(iter),'.caffemodel'));
            net.copy_from(strcat(param.save_model_file,num2str(split_index),'/',param.save_model_name,'_',num2str(iter),'.caffemodel'));
            net.blobs('data').reshape([224 224 3 param.test_batch_size]);
            load(strcat(param.data_path,param.testdata_filename,num2str(split_index),'/test_data.mat'));
            test_script;
        end
        if iter>100 && mod(iter,100)==0
            caffe_solver.nets{1}.save(strcat(param.save_model_file,num2str(split_index),'/',param.save_model_name,'_',num2str(iter),'.caffemodel'));
        end
    end
%     test_network;
end


function x = utl_purify_expression(x)
% Recursively remove impure elements from an expression.
% Output-Expression = utl_purify_expression(Input-Expression)
%
% In particular, x.tracking.expression is replaced by x. It is assumed that the head is not an impure expression.
%
%                                                     Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                                     2010-05-23

if isscalar(x) && all(isfield(x,{'head','parts'}))
    % x is a canonical expression: recurse
    for i=1:length(x.parts)
        x.parts{i} = utl_purify_expression(x.parts{i}); end
elseif isfield(x,'tracking') && isfield(x.tracking,'expression')
    % x is an impure expression: purify & recurse
    x = utl_purify_expression(x.tracking.expression);
end


function plan = read_pinnacle_plan_trial(filename,trialname)
%
%	plan = read_pinnacle_plan_trial(filename,trialname)
%	read_pinnacle_plan_trial(filename) to list all trials

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

lineno = 0;
lastlineistrial = 0;
trialno = 0;
plan = [];

% Scan the whole file for all available trials
while 1
	tl = fgetl(fid);
	lineno = lineno+1;

	if feof(fid)
		break;
	end

	if length(tl) >= 10 && strcmp(tl(1:10),'  Name = "') == 1 && lastlineistrial == 1
		outl = strsplit_cerr('=',tl);
		tname = ddeblank(outl{2});
		tname = tname(1:end-2);
		tname = tname(2:end);
		trialnames{trialno,1} = tname;
		%triallines(trialno) = lineno-1;
        triallines(trialno) = trialLineNo;
	end

% 	if strcmp(tl,'Trial ={') == 1
% 		lastlineistrial = 1;
% 		trialno = trialno + 1;
% 	else
% 		lastlineistrial = 0;
% 	end
	if strcmp(tl,'Trial ={') == 1
		lastlineistrial = 1;
		trialno = trialno + 1;
        trialLineNo = lineno - 1;
    elseif strcmp(tl,'};') == 1
		lastlineistrial = 0;
	end

end

if ~exist('trialname','var')
	if length(trialnames) > 1
		disp('Trial names');
		trialnames
		return;
	else
		trialname = trialnames{1};
		fprintf('Trail name = %s\n',trialname);
	end
end

if ~exist('triallines','var')
    disp('Trail is not found');
    fclose(fid);
    return;
end

% find the trial
found = 0;
for k = 1:length(triallines)
	if strcmp(trialnames{k},trialname)
		found = 1;
		break;
	end
end

if found == 0
	disp('Trail is not found');
	fclose(fid);
	return;
end

fclose(fid);

fid = fopen(filename,'r');
lineno = 0;
while lineno < triallines(k)-1
	fgetl(fid);
	lineno = lineno + 1;
end

% Read the whole trial into the MATLAB structure
[planname,plan] = read_1_field_pinnacle(fid);

fclose(fid);

return;


% mtimesx_build compiles mtimesx.c with BLAS libraries
%******************************************************************************
%
%  MATLAB (R) is a trademark of The Mathworks (R) Corporation
%
%  Function:    mtimesx_build
%  Filename:    mtimesx_build.m
%  Programmer:  James Tursa
%  Version:     1.40
%  Date:        October 4, 2010
%  Copyright:   (c) 2009, 2010 by James Tursa, All Rights Reserved
%
%  This code uses the BSD License:
%
%  Redistribution and use in source and binary forms, with or without
%  modification, are permitted provided that the following conditions are
%  met:
%
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%
%  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
%  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%  POSSIBILITY OF SUCH DAMAGE.
%
%--
%
%  mtimesx_build compiles mtimesx.c and mtimesx_RealTimesReal.c with the BLAS
%  libraries libmwblas.lib (if present) or libmwlapack.lib (if libmwblas.lib
%  is not present). This function basically works as follows:
%
%  - Opens the current mexopts.bat file in the directory [prefdir], and
%    checks to make sure that the compiler selected is cl or lcc. If it
%    is not, then a warning is issued and the compilation continues with
%    the assumption that the microsoft BLAS libraries will work.
%
%  - Looks for the file libmwblas.lib or libmwlapack.lib files in the
%    appropriate directory: [matlabroot '\extern\lib\win32\microsoft']
%                       or  [matlabroot '\extern\lib\win32\lcc']
%                       or  [matlabroot '\extern\lib\win64\microsoft']
%                       or  [matlabroot '\extern\lib\win64\lcc']
%
%  - Changes directory to the directory of the file mtimesx.m.
%
%  - Compiles mtimesx.c (which includes mtimesx_RealTimesReal.c) along with
%    either libmwblas.lib or libmwlapack.lib depending on the version of
%    MATLAB. The resulting exedcutable mex file is placed in the same
%    directory as the source code. The files mtimesx.m, mtimesx.c, and
%    mtimesx_RealTimesReal.c must all be in the same directory.
%
%  - Changes the directory back to the original directory.
%
%  Change Log:
%  2009/Sep/27 --> 1.00, Initial Release
%  2010/Feb/15 --> 1.10, Fixed largearrardims typo to largeArrayDims
%  2010/Oct/04 --> 1.40, Updated support for OpenMP compiling
%
%**************************************************************************

function mtimesx_build(x)
disp(' ');
disp('... Build routine for mtimesx');

TRUE = 1;
FALSE = 0;

%\
% Check for number of inputs & outputs
%/

noopenmp = FALSE;
if( nargin == 1 )
    if( isequal(upper(x),'NOOPENMP') )
        noopenmp = TRUE;
    else
        error('Invalid input.');
    end
elseif( nargin ~= 0 )
    error('Too many inputs. Expected none.');
end
if( nargout ~= 0 )
    error('Too many outputs. Expected none.');
end

%\
% Check for non-PC
%/

disp('... Checking for PC');
try
    % ispc does not appear in MATLAB 5.3
    pc = ispc ;
catch
    % if ispc fails, assume we are on a Windows PC if it's not unix
    pc = ~isunix ;
end

if( ~pc )
    disp('building linux version');
    mex('mtimesx.c','-DDEFINEUNIX','-largeArrayDims','-lmwblas');
    return;
end

%\
% Check to see that mtimesx.c source code is present
%/

disp('... Finding path of mtimesx C source code files');
try
    mname = mfilename('fullpath');
catch
    mname = mfilename;
end
cname = [mname(1:end-6) '.c'];
if( isempty(dir(cname)) )
    disp('Cannot find the file mtimesx.c in the same directory as the');
    disp('file mtimesx_build.m. Please ensure that they are in the same');
    disp('directory and try again. The following file was not found:');
    disp(' ');
    disp(cname);
    disp(' ');
    error('Unable to compile mtimesx.c');
end
disp(['... Found file mtimesx.c in ' cname]);

%\
% Check to see that mtimesx_RealTimesReal.c source code is present
%/

rname = [mname(1:end-13) 'mtimesx_RealTimesReal.c'];
if( isempty(dir(rname)) )
    disp('Cannot find the file mtimesx_RealTimesReal.c in the same');
    disp('directory as the file mtimesx_build.m. Please ensure that');
    disp('they are in the same directory and try again. The');
    disp('following file was not found:');
    disp(' ');
    disp(rname);
    disp(' ');
    error('Unable to compile mtimesx.c');
end
disp(['... Found file mtimesx_RealTimesReal.c in ' rname]);

%\
% Open the current mexopts.bat file
%/

matlab_ver = version('-release');
if str2num(matlab_ver(1:4)) >= 2014
    mexopts = [prefdir '\mex_C++_win64.xml'];
else
    mexopts = [prefdir '\mexopts.bat'];
end
fid = fopen(mexopts);
if( fid == -1 )
    error('A C/C++ compiler has not been selected with mex -setup');
end
disp(['... Opened the mexopts.bat file in ' mexopts]);
disp('... Reading the mexopts.bat file to find the compiler and options used.');

%\
% Check for the correct compiler selected.
%/

ok_cl = FALSE;
ok_lcc = FALSE;
omp_option = '';
compiler = '(unknown)';
compilername = '';
while( TRUE )
    tline = fgets(fid);
    if( isequal(tline,-1) )
        break;
    else
        if( isempty(compilername) )
            y = findstr(tline,'OPTS.BAT');
            if( ~isempty(y) )
                x = findstr(tline,'rem ');
                if( ~isempty(x) )
                    compilername = tline(x+4:y-1);
                end
            end
        end
        x = findstr(tline,'COMPILER=lcc');
        if( ~isempty(x) )
            ok_lcc = TRUE;
            libdir = 'lcc';
            compiler = 'LCC';
            disp(['... ' compiler ' is the selected compiler']);
            break;
        end
        x = findstr(tline,'COMPILER=cl');
        if( ~isempty(x) )
            ok_cl = TRUE;
            libdir = 'microsoft';
            compiler = ['Microsoft_' compilername '_cl'];
            omp_option = ' /openmp';
            disp(['... ' compiler ' is the selected compiler']);
            break;
        end
        x = findstr(tline,'COMPILER=bcc32');
        if( ~isempty(x) )
            ok_cl = TRUE;
            libdir = 'microsoft';
            compiler = ['Borland_' compilername '_bcc32'];
            disp(['... ' compiler ' is the selected compiler']);
            disp('... Assuming that Borland will link with Microsoft libraries');
            break;
        end
        x = findstr(tline,'COMPILER=icl');
        if( ~isempty(x) )
            ok_cl = TRUE;
            if( pc )
                omp_option = ' -Qopenmp';
            else
                omp_option = ' -openmp';
            end
            libdir = 'microsoft';
            compiler = ['Intel_' compilername '_icl'];
            disp(['... ' compiler ' is the selected compiler']);
            disp('... Assuming that Intel will link with Microsoft libraries');
            break;
        end
        x = findstr(tline,'COMPILER=wc1386');
        if( ~isempty(x) )
            ok_cl = TRUE;
            libdir = 'microsoft';
            compiler = ['Watcom_' compilername '_wc1386'];
            disp(['... ' compiler ' is the selected compiler']);
            disp('... Assuming that Watcom will link with Microsoft libraries');
            break;
        end
        x = findstr(tline,'COMPILER=gcc');
        if( ~isempty(x) )
            ok_cl = TRUE;
            libdir = 'microsoft';
            omp_option = ' -fopenmp';
            compiler = 'GCC';
            disp(['... ' compiler ' is the selected compiler']);
            disp('... Assuming that GCC will link with Microsoft libraries');
            break;
        end
    end
end
fclose(fid);

%\
% MS Visual C/C++ or lcc compiler has not been selected
%/

if( ~(ok_cl | ok_lcc) )
    warning('... Supported C/C++ compiler has not been selected with mex -setup');
    warning('... Assuming that Selected Compiler will link with Microsoft libraries');
    warning('... Continuing at risk ...');
    libdir = 'microsoft';
end

%\
% If an OpenMP supported compiler is potentially present, make sure that the
% necessary compile option is present in the mexopts.bat file on the COMPFLAGS
% line.  If necessary, build a new mexopts.bat file with the correct option
% added to the COMPFLAGS line.
%/

while( TRUE )
ok_openmp = FALSE;
ok_compflags = FALSE;
xname = '';
if( isempty(omp_option) )
    disp('... OpenMP compiler not detected ... you may want to check this website:');
    disp('    http://openmp.org/wp/openmp-compilers/');
elseif( noopenmp )
    disp(['... OpenMP compiler potentially detected, but not checking for ''' omp_option ''' compile option']);
else
    disp('... OpenMP compiler potentially detected');
    disp(['... Checking to see that the ''' omp_option ''' compile option is present']);
    fid = fopen(mexopts);
    while( TRUE )
        tline = fgets(fid);
        if( isequal(tline,-1) )
            break;
        else
            x = findstr(tline,'set COMPFLAGS');
            if( ~isempty(x) )
                ok_compflags = TRUE;
                x = findstr(tline,omp_option);
                if( ~isempty(x) )
                    ok_openmp = TRUE;
                end
                break;
            end
        end
    end
    fclose(fid);
    if( ~ok_compflags )
        warning(['... COMPFLAGS line not found ... ''' omp_option ''' will not be added.']);
    elseif( ~ok_openmp )
        disp(['... The ''' omp_option ''' compile option is not present ... adding it']);
        xname = [mname(1:end-6) '_mexopts.bat'];
        disp(['... Creating custom options file ' xname ' with the ''' omp_option ''' option added.']);
        fid = fopen(mexopts);
        fidx = fopen(xname,'w');
        if( fidx == -1 )
            xname = '';
            warning(['... Unable to create custom mexopts.bat file ... ''' omp_option ''' will not be added']);
        else
            while( TRUE )
                tline = fgets(fid);
                if( isequal(tline,-1) )
                    break;
                else
                    x = findstr(tline,'set COMPFLAGS');
                    if( ~isempty(x) )
                        n = numel(tline);
                        e = n;
                        while( tline(e) < 32 )
                            e = e - 1;
                        end
                        tline = [tline(1:e) omp_option tline(e+1:n)];
                    end
                    fwrite(fidx,tline);
                end
            end
            fclose(fidx);
        end
        fclose(fid);
    end
end

%\
% Construct full file name of libmwblas.lib and libmwlapack.lib. Note that
% not all versions have both files. Earlier versions only had the lapack
% file, which contained both blas and lapack routines.
%/

comp = computer;
mext = mexext;
lc = length(comp);
lm = length(mext);
cbits = comp(max(1:lc-1):lc);
mbits = mext(max(1:lm-1):lm);
if( isequal(cbits,'64') | isequal(mbits,'64') )
    compdir = 'win64';
    largearraydims = '-largeArrayDims';
else
    compdir = 'win32';
    largearraydims = '';
end

lib_blas = [matlabroot '\extern\lib\' compdir '\' libdir '\libmwblas.lib'];
d = dir(lib_blas);
if( isempty(d) )
    disp('... BLAS library file not found, so linking with the LAPACK library');
    lib_blas = [matlabroot '\extern\lib\' compdir '\' libdir '\libmwlapack.lib'];
end
disp(['... Using BLAS library lib_blas = ''' lib_blas '''']);

%\
% Save old directory and change to source code directory
%/

cdold = cd;
if( length(mname) > 13 )
    cd(mname(1:end-13));
end

%\
% Do the compile
%/

disp('... Now attempting to compile ...');
disp(' ');
try
    if( isunix )
        if( isempty(largearraydims) )
            if( isempty(xname) )
                disp(['mex(''-DDEFINEUNIX'',''' cname ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex('-DDEFINEUNIX',cname,lib_blas,['-DCOMPILER=' compiler]);
            else
                disp(['mex(''-f'',''' xname ''',''-DDEFINEUNIX'',''' cname ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex('-f',xname,'-DDEFINEUNIX',cname,lib_blas,['-DCOMPILER=' compiler]);
            end
        else
            if( isempty(xname) )
                disp(['mex(''-DDEFINEUNIX'',''' cname ''',''' largearraydims ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex('-DDEFINEUNIX',largearraydims,cname,lib_blas,['-DCOMPILER=' compiler]);
            else
                disp(['mex(''-f'',''' xname ''',''-DDEFINEUNIX'',''' cname ''',''' largearraydims ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex('-f',xname,'-DDEFINEUNIX',largearraydims,cname,lib_blas,['-DCOMPILER=' compiler]);
            end
        end
    else
        if( isempty(largearraydims) )
            if( isempty(xname) )
                disp(['mex(''' cname ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex(cname,lib_blas,['-DCOMPILER=' compiler]);
            else
                disp(['mex(''-f'',''' xname ''',''' cname ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex('-f',xname,cname,lib_blas,['-DCOMPILER=' compiler]);
            end
        else
            if( isempty(xname) )
                disp(['mex(''' cname ''',''' largearraydims ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex(cname,largearraydims,lib_blas,['-DCOMPILER=' compiler]);
            else
                disp(['mex(''-f'',''' xname ''',''' cname ''',''' largearraydims ''',lib_blas,''-DCOMPILER=' compiler ''')']);
                disp(' ');
                mex('-f',xname,cname,largearraydims,lib_blas,['-DCOMPILER=' compiler]);
            end
        end
    end
    disp('... mex mtimesx.c build completed ... you may now use mtimesx.');
    disp(' ');
    mtimesx;
    break;
catch
    if( noopenmp )
        cd(cdold);
        disp(' ');
        disp('... Well, *that* didn''t work either!');
        disp(' ');
        disp('The mex command failed. This may be because you have already run');
        disp('mex -setup and selected a non-C compiler, such as Fortran. If this');
        disp('is the case, then rerun mex -setup and select a C/C++ compiler.');
        disp(' ');
        error('Unable to compile mtimesx.c');
    else
        disp(' ');
        disp('... Well, *that* didn''t work ...');
        disp(' ');
        if( isequal(omp_option,' /openmp') )
            disp('This may be because an OpenMP compile option was added that the');
            disp('compiler did not like. For example, the Standard versions of the');
            disp('Microsoft C/C++ compilers do not support OpenMP, only the');
            disp('Professional versions do. Attempting to compile again but this');
            disp(['time will not add the ''' omp_option ''' option.'])
        else
            disp('This may be because an OpenMP compile option was added that the');
            disp('compiler did not like. Attempting to compile again, but this time');
            disp(['will not add the ''' omp_option ''' option.'])
        end
        disp(' ');
        noopenmp = TRUE;
    end
end
end

%\
% Restore old directory
%/

cd(cdold);

return
end


function settings = meshMatchSettings(src, tgt, varargin);
% Adjust the view settings on one or more target meshes to match that on
% the source mesh.
%
%   settings = meshMatchSettings([sourceMesh=current mesh], [targetMeshes], [gray/volume view]);
%
% INPUTS:
%	sourceMesh: mesh whose view settings you want to replicate on other
%	meshes. You can provide a mesh structure, the number of a mesh in the
%	current gray view, or the number of the mesh window as a character (e.g.,
%	use '1' for a mesh window named 'mrMesh 1', but use 1 for the
%	first mesh in the view). [Default: selected mesh in gray view].
%
%	targetMeshes: specification of one or more meshes whose view settings
%	will match that of the source mesh. Can be specified in the same way as
%	sourceMesh. If you want to specify multiple target meshes, you can
%	specify them as a cell array (or, in the case of numeric mesh indexes,
%	a numeric array, or a struct array in the case of full mesh strucures).
%	[Default: prompt user to select meshes].
%
%	[gray/volume view]: a gray or volume view structure which has the
%	relevant meshes loaded. This isn't needed if you're providing the full
%	mesh structures as inputs. [Default: use selected gray view]
%
% RETURNS:
%	settings: settings structure from the source mesh.
%
% SEE ALSO: meshSettings, meshStoreSettings, meshRetrieveSettings.
%
% ras, 08/2009.

% I allow several target meshes to be input as varargin (allowing me to type the
% IDs as strings): the view G is always the last of these, if it's specified.
if ~isempty(varargin)
	if isstruct(varargin{end})
		G = varargin{end};
	else
		G = [];
	end
	tgt = [{tgt} varargin];
end

if notDefined('G')
	% don't call getSelectedGray if both src and target are provided as
	% structures -- we don't want to force this code to depend on the
	% mrVista data structure if we don't need to.
	if ( isstruct(src) | (iscell(src) & isstruct(src{1})) ) & ...
		( isstruct(tgt) | (iscell(tgt) & isstruct(tgt{1})) )
		G = [];
	else
		G = getSelectedGray;
	end
end

if notDefined('src'),
	src = G.mesh{G.meshNum3d};
end

% parse the source mesh structure
if ~isstruct(src)
	src = parseMeshStructure(src, G);
end

% get the source mesh settings
settings = meshSettings(src);

if notDefined('tgt'),
	% user dialog
	dlg.fieldName = 'whichMeshes';
	dlg.style = 'listbox';
	dlg.string = sprintf(['Apply Mesh Settings from Mesh %i to which ' ...
						  'other meshes?'], src.id);
	for n = 1:length(G.mesh)
		dlg.list{n} = [num2str(G.mesh{n}.id) '. ' G.mesh{n}.name];
	end
	dlg.value = 1;

	[resp ok] = generalDialog(dlg, mfilename);
	if ~ok, fprintf('[%s]: User aborted.\n', mfilename); return; end

	for n = 1:length(resp.whichMeshes)
		tgt(n) = cellfind(dlg.list, resp.whichMeshes{n});
	end
end

% parse the target mesh specification
if ~ischar(tgt) & length(tgt) > 1
	% iteratively apply to several meshes
	for n = 1:length(tgt)
		if iscell(tgt)
			currTarget = parseMeshStructure(tgt{n}, G);
		else
			currTarget = parseMeshStructure(tgt(n), G);
		end
		meshApplySettings(currTarget, settings);
	end

else
	tgt = parseMeshStructure(tgt, G);
	meshApplySettings(tgt, settings);

end

return
% /--------------------------------------------------------------------/ %

% /--------------------------------------------------------------------/ %
function msh = parseMeshStructure(msh, G);
% given a mesh specification (which could be one of many things) and a view
% with meshes, return a mesh structure.
if isstruct(msh),
	% we're good...
	return;
end

if iscell(msh)
	for n = 1:length(msh)
		msh(n) = parseMeshStructure(msh{n}, G);
	end
	return
end

if ischar(msh)
	% id of mesh window ... find it in this view:
	targetID = str2num(msh);
	for n = 1:length(G.mesh)
		ids(n) = G.mesh{n}.id;
	end
	msh = find(ids==targetID);
	if isempty(msh)
		error('Couldn''t find mesh id %i in view.', targetID);
	end

	% now it's numeric, so it should go through the indexing code below...
end

if isnumeric(msh)
	% numeric index into G's meshes
	whichMeshes = msh;  clear msh
	for n = 1:length(whichMeshes)
		msh(n) = G.mesh{whichMeshes(n)};
	end
end

if isempty(msh)
	error('Empty mesh specification.')
end

return


function [freq] = ft_appendfreq(cfg, varargin)

% FT_APPENDFREQ concatenates multiple frequency or time-frequency data structures
% that have been processed separately. If the input data structures contain different
% channels, it will be concatenated along the channel direction. If the channels are
% identical in the input data structures, the data will be concatenated along the
% repetition dimension.
%
% Use as
%  combined = ft_appendfreq(cfg, freq1, freq2, ...)
%
% The configuration should contain
%   cfg.parameter  = string, the name of the field to concatenate
%
% The configuration can optionally contain
%   cfg.appenddim  = string, the dimension to concatenate over (default is automatic)
%   cfg.tolerance  = scalar, tolerance to determine how different the frequency and/or
%                    time axes are allowed to still be considered compatible (default = 1e-5)
%
% To facilitate data-handling and distributed computing you can use
%   cfg.inputfile   =  ...
%   cfg.outputfile  =  ...
% If you specify one of these (or both) the input data will be read from a
% *.mat file on disk and/or the output data will be written to a *.mat file.
% These mat files should contain only a single variable, corresponding with
% the input/output structure.
%
% See also FT_FREQANALYSIS, FT_DATATYPE_FREQ, FT_APPENDDATA, FT_APPENDTIMELOCK,
% FT_APPENDSENS

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

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble debug
ft_preamble loadvar    varargin
ft_preamble provenance varargin

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  return
end

% check if the input data is valid for this function
for i=1:length(varargin)
  varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'freq', 'freq+comp'}, 'feedback', 'yes');
end

% set the defaults
cfg.channel    = ft_getopt(cfg, 'channel', 'all');
cfg.channelcmb = ft_getopt(cfg, 'channelcmb', {'all' 'all'});
cfg.parameter  = ft_getopt(cfg, 'parameter', []);
cfg.appenddim  = ft_getopt(cfg, 'appenddim', []);
cfg.tolerance  = ft_getopt(cfg, 'tolerance',  1e-5); % this is passed to append_common, which passes it to ft_selectdata
cfg.appendsens = ft_getopt(cfg, 'appendsens', 'no');

hastime = isfield(varargin{1}, 'time');
hasfreq = isfield(varargin{1}, 'freq');

if isempty(cfg.appenddim) || strcmp(cfg.appenddim, 'auto')
  if hastime && hasfreq
    if checkchan(varargin{:}, 'identical') && checkfreq(varargin{:}, 'identical', cfg.tolerance) && checktime(varargin{:}, 'identical', cfg.tolerance)
      cfg.appenddim = 'rpt';
    elseif checkfreq(varargin{:}, 'unique', cfg.tolerance) && checktime(varargin{:}, 'identical', cfg.tolerance)
      cfg.appenddim = 'freq';
    elseif checktime(varargin{:}, 'unique', cfg.tolerance) && checkfreq(varargin{:}, 'identical', cfg.tolerance)
      cfg.appenddim = 'time';
    elseif checkchan(varargin{:}, 'unique')
      cfg.appenddim = 'chan';
    else
      ft_error('cfg.appenddim should be specified');
    end
  else
    if checkchan(varargin{:}, 'identical') && checkfreq(varargin{:}, 'identical', cfg.tolerance)
      cfg.appenddim = 'rpt';
    elseif checkfreq(varargin{:}, 'unique', cfg.tolerance)
      cfg.appenddim = 'freq';
    elseif checkchan(varargin{:}, 'unique')
      cfg.appenddim = 'chan';
    else
      ft_error('cfg.appenddim should be specified');
    end
  end
end
ft_info('concatenating over the "%s" dimension\n', cfg.appenddim);

if isempty(cfg.parameter)
  fn = fieldnames(varargin{1});
  for i=2:numel(varargin)
    fn = intersect(fn, fieldnames(varargin{i}));
  end
  cfg.parameter = setdiff(fn, ignorefields('appendfreq'));
elseif ischar(cfg.parameter)
  cfg.parameter = {cfg.parameter};
end
assert(~isempty(cfg.parameter), 'cfg.parameter should be specified');

% use a low-level function that is shared with the other ft_appendxxx functions
freq = append_common(cfg, varargin{:});

% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble previous   varargin
ft_postamble provenance freq
ft_postamble history    freq
ft_postamble savevar    freq


function V = spm_vol(P)
% Get header information for images
% FORMAT V = spm_vol(P)
% P - a char or cell array of filenames
% V - a structure array containing image volume information
%     The elements of the structures are:
%       V.fname - the filename of the image.
%       V.dim   - the x, y and z dimensions of the volume
%       V.dt    - A 1x2 array.  First element is datatype (see spm_type).
%                 The second is 1 or 0 depending on the endian-ness.
%       V.mat   - a 4x4 affine transformation matrix mapping from
%                 voxel coordinates to real world coordinates.
%       V.pinfo - plane info for each plane of the volume.
%              V.pinfo(1,:) - scale for each plane
%              V.pinfo(2,:) - offset for each plane
%                 The true voxel intensities of the jth image are given
%                 by: val*V.pinfo(1,j) + V.pinfo(2,j)
%              V.pinfo(3,:) - offset into image (in bytes).
%                 If the size of pinfo is 3x1, then the volume is assumed
%                 to be contiguous and each plane has the same scalefactor
%                 and offset.
%__________________________________________________________________________
%
% The fields listed above are essential for the mex routines, but other
% fields can also be incorporated into the structure.
%
% Note that spm_vol can also be applied to the filename(s) of 4-dim
% volumes. In that case, the elements of V will point to a series of 3-dim
% images.
%__________________________________________________________________________
% Copyright (C) 1999-2014 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_vol.m 5958 2014-04-16 17:13:41Z guillaume $

if ~nargin
    V = struct('fname',   {},...
               'dim',     {},...
               'dt',      {},...
               'pinfo',   {},...
               'mat',     {},...
               'n',       {},...
               'descrip', {},...
               'private', {});

elseif isempty(P)
    V = spm_vol;
    if iscell(P), V = {V}; end

elseif isstruct(P)
    V = P;

elseif iscell(P)
    V = cellfun(@spm_vol,P, 'UniformOutput',false);

else
    V = spm_vol;
    cnt = 0;
    for i=1:size(P,1)
        v = spm_vol_hdr(deblank(P(i,:)));

        f = fieldnames(v);
        for j=1:numel(f)
            [V(cnt+1:cnt+size(v,2),1).(f{j})] = deal(v.(f{j}));
        end
        cnt = cnt + size(v,2);
    end
end

%==========================================================================
% function V = spm_vol_hdr(p)
%==========================================================================
function V = spm_vol_hdr(p)
[pth,nam,ext,n] = spm_fileparts(p);
p = fullfile(pth,[nam ext]);
n = str2num(n);
if ~spm_existfile(p)
    error('File "%s" does not exist.', p);
end
switch ext
    case {'.nii','.NII'}
        % Do nothing

    case {'.img','.IMG'}
        if ~spm_existfile(fullfile(pth,[nam '.hdr'])) && ...
           ~spm_existfile(fullfile(pth,[nam '.HDR']))
            error('File "%s" does not exist.', fullfile(pth,[nam '.hdr']));
        end

    case {'.hdr','.HDR'}
        ext = '.img';
        p   = fullfile(pth,[nam ext]);
        if ~spm_existfile(p)
            error('File "%s" does not exist.', p);
        end

    case {'.gz','.GZ'}
        fprintf('Compressed NIfTI files are not supported.\n');
        tmpname = tempname;
        try
            tmpname = char(gunzip(p,tmpname));
        catch
            error('Cannot uncompress "%s".',p);
        end
        try
            if isempty(n), n = ''; else n = [',' num2str(n)]; end
            V = spm_vol_hdr([tmpname n]);
            for i=1:numel(V)
                V(i).dat   = spm_read_vols(V(i));
                V(i).private.dat.fname = spm_file(p,'ext','');
                V(i).fname = p;
                V(i).dt(1) = 64;
                V(i).pinfo = [1 0 0]';
            end
        catch
            warning('Cannot read uncompressed file "%s".',p);
        end
        spm_unlink(tmpname);
        rmdir(fileparts(tmpname));
        return

    otherwise
        error('File "%s" is not of a recognised type.', p);
end

V = spm_vol_nifti(p,n);

if isempty(n) && length(V.private.dat.dim) > 3
    V0(1) = V;
    for i = 2:V.private.dat.dim(4)
        V0(i) = spm_vol_nifti(V.private, i);
    end
    V = V0;
end


function word_indices = processEmail(email_contents)
%PROCESSEMAIL preprocesses a the body of an email and
%returns a list of word_indices
%   word_indices = PROCESSEMAIL(email_contents) preprocesses
%   the body of an email and returns a list of indices of the
%   words contained in the email.
%

% Load Vocabulary
vocabList = getVocabList();

% Init return value
word_indices = [];

% ========================== Preprocess Email ===========================

% Find the Headers ( \n\n and remove )
% Uncomment the following lines if you are working with raw emails with the
% full headers

% hdrstart = strfind(email_contents, ([char(10) char(10)]));
% email_contents = email_contents(hdrstart(1):end);

% Lower case
email_contents = lower(email_contents);

% Strip all HTML
% Looks for any expression that starts with < and ends with > and replace
% and does not have any < or > in the tag it with a space
email_contents = regexprep(email_contents, '<[^<>]+>', ' ');

% Handle Numbers
% Look for one or more characters between 0-9
email_contents = regexprep(email_contents, '[0-9]+', 'number');

% Handle URLS
% Look for strings starting with http:// or https://
email_contents = regexprep(email_contents, ...
                           '(http|https)://[^\s]*', 'httpaddr');

% Handle Email Addresses
% Look for strings with @ in the middle
email_contents = regexprep(email_contents, '[^\s]+@[^\s]+', 'emailaddr');

% Handle $ sign
email_contents = regexprep(email_contents, '[$]+', 'dollar');

% ========================== Tokenize Email ===========================

% Output the email to screen as well
fprintf('\n==== Processed Email ====\n\n');

% Process file
l = 0;

while ~isempty(email_contents)

    % Tokenize and also get rid of any punctuation
    [str, email_contents] = ...
       strtok(email_contents, ...
              [' @$/#.-:&*+=[]?!(){},''">_<;%' char(10) char(13)]);

    % Remove any non alphanumeric characters
    str = regexprep(str, '[^a-zA-Z0-9]', '');

    % Stem the word
    % (the porterStemmer sometimes has issues, so we use a try catch block)
    try str = porterStemmer(strtrim(str));
    catch str = ''; continue;
    end;

    % Skip the word if it is too short
    if length(str) < 1
       continue;
    end

    % Look up the word in the dictionary and add to word_indices if
    % found
    % ====================== YOUR CODE HERE ======================
    % Instructions: Fill in this function to add the index of str to
    %               word_indices if it is in the vocabulary. At this point
    %               of the code, you have a stemmed word from the email in
    %               the variable str. You should look up str in the
    %               vocabulary list (vocabList). If a match exists, you
    %               should add the index of the word to the word_indices
    %               vector. Concretely, if str = 'action', then you should
    %               look up the vocabulary list to find where in vocabList
    %               'action' appears. For example, if vocabList{18} =
    %               'action', then, you should add 18 to the word_indices
    %               vector (e.g., word_indices = [word_indices ; 18]; ).
    %
    % Note: vocabList{idx} returns a the word with index idx in the
    %       vocabulary list.
    %
    % Note: You can use strcmp(str1, str2) to compare two strings (str1 and
    %       str2). It will return 1 only if the two strings are equivalent.
    %

    for i = 1:size(vocabList)
      if (strcmp(str, vocabList(i)))
        word_indices = [ word_indices; i];
      endif
    endfor

    % =============================================================

    % Print to screen, ensuring that the output lines are not too long
    if (l + length(str) + 1) > 78
        fprintf('\n');
        l = 0;
    end
    fprintf('%s ', str);
    l = l + length(str) + 1;

end

% Print footer
fprintf('\n\n=========================\n');

end


function mov = make3Davi(varargin)
% ::
%
%    mov = make3Davi([opt] Options_Structure)
%
% Makes an avi movie file called head3d[x].avi or whatever you specify.
%
% :Options:
%
%   **O.name:**
%        'output_name.avi';
%
%   **O.fps:**
%        frames per second
%
%   **O.length:**
%        length of movie in s
%
%   **O.H:**
%        cluster handles in vector   (for adjusting transparency with time)
%
%   **O.timecourse{i}:**
%        cell array of time courses for each cluster
%
%   **O.timeres:**
%        resolution, in s, of timecourse data
%
%   **O.azOffset:**
%        azimuth value to offset, positive = move clockwise
%
%   **O.elOffset:**
%        elevation value to move through, positive = inf to superior
%
%   **O.zoom:**
%        zoom value to end up with
%
%   **O.add2movie:**
%        add to existing movie - enter mov structure in this field
%
%   **O.closemovie:**
%        1 or 0, close the movie afterward or not.
%
% Blank fields for az, el, zoom, timecourse indicate that these functions should not be performed
% This script spirals up, right, and in 36 degrees
%
% Notes: my indeo5 one wouldn't work in media player
%        also only seems to work if you add clusters before head isosurfaces
%        for Mac OS X / UNIX, choose "no compression"
%
% start with the image in the location you want to zoom in on
% but with no zoom.
%
% The movie FINISHES at the current axis locations
%
% :Example:  "Surface tour"
% ::
%
%    O = struct('name','all4_union_bg_surf.avi','fps',10,'length',6,'azOffset',180,'zoom',1,'elOffset',90,'closemovie',0); mov = make3davi(O);
%    view(90,0);lightfollowview;O = struct('name','all4_union_bg_surf.avi','add2movie',mov,'fps',10,'length',6,'azOffset',90,'zoom',1,'elOffset',-90,'closemovie',0); mov = make3davi(O);
%    view(0,90);lightfollowview;O = struct('name','all4_union_bg_surf.avi','add2movie',mov,'fps',10,'length',6,'azOffset',-90,'zoom',1,'elOffset',90,'closemovie',0); mov = make3davi(O);
%    mov = close(mov);
%
% ..
%    By Tor Wager, 10/07/01
% ..

% ..
%    set default values and inputs
% ..
myName = 'head3d1.avi'; i = 1;                      % set name to first unused file #
while exist(myName) == 2, myName = ['head3d' num2str(i) '.avi'];, i = i+1;,end
O.name = myName;
O.fps = 10;
O.length = 8;
O.H = [];
O.timecourse = [];
O.timeres = 1;
O.azOffset = 36;                                    % positive starts from left, moves r
                                                    % spins brain clockwise
O.elOffset = 20;                                    % positive starts from below, moves up
O.zoom = 2;                                         % final image will be this many times closer than at start
O.add2movie = [];                                   % existing movie structure to add to.  [] = new movie file.
O.closemovie = 1;                                   % close movie after finishing.  0 to add more frames later.

if nargin > 0
    inO = varargin{1};
    if isfield(inO,'name'), O.name = inO.name;,end
    if isfield(inO,'fps'), O.fps = inO.fps;,end
    if isfield(inO,'length'), O.length = inO.length;,end
    if isfield(inO,'H'), O.H = inO.H;,end
    if isfield(inO,'timecourse'), O.timecourse = inO.timecourse;,end
    if isfield(inO,'timeres'), O.timeres = inO.timeres;,end
    if isfield(inO,'azOffset'), O.azOffset = inO.azOffset;,end
    if isfield(inO,'elOffset'), O.elOffset = inO.elOffset;,end
    if isfield(inO,'zoom'), O.zoom = inO.zoom;,end
    if isfield(inO,'add2movie'), O.add2movie = inO.add2movie;,end
    if isfield(inO,'closemovie'), O.closemovie = inO.closemovie;,end
end

numFrames = O.fps .* O.length;
interpValue = O.fps ./ O.timeres;

% -------------------------------------------
% * check values to make sure everything's ok
% -------------------------------------------

if ~isempty(O.timecourse) & length(O.H) ~= length(O.timecourse), error('Number of handles and timecourses must be equal.'),end
if interpValue ~= round(interpValue), error('Frames per second must be a multiple of time res - adjust either one.'),end
if any(~ishandle(O.H)),
    warning('At least one cluster handle is not a valid object. Searching for handles by Tag name cluster[x]')
    for i = 1:length(O.H)
        O.H(i) = findobj('Tag',['cluster' num2str(i)]);
    end
    if any(~ishandle(O.H)), error('Cannot find valid cluster handles.'),end
end

% -------------------------------------------
% * create transparency values from timecourses
% -------------------------------------------
% normalize all timecourses to alpha values, from 0 to 1, by dividing by max value
if ~isempty(O.timecourse)
  for i = 1:length(O.timecourse),
    %O.timecourse{i} = O.timecourse{i} - min(O.timecourse{i});       % prevent negative values, set min to 0
    %min(O.timecourse{i})
    %O.timecourse{i} = O.timecourse{i} ./ max(abs(O.timecourse{i})); % max is one
    numSeconds = ceil(length(O.timecourse{i}) .* O.timeres);
    %numFrames = numSeconds .* O.fps;                               % adjust length
    alphaVal{i} = interp(O.timecourse{i},interpValue);              % interpolate to number of frames
    %alphaVal{i} = alphaVal{i} - min(alphaVal{i});                   % prevent negative values, set min to 0
    %alphaVal{i} = alphaVal{i} ./ max(abs(alphaVal{i}));             % max is one
    alphaVal{i} = [ alphaVal{i} zeros(1,max([0 numFrames - length(alphaVal{i})])) ];   % pad with zeros

    if any(alphaVal{i} < 0 | alphaVal{i} > 1),
        alphaVal{i},min(alphaVal{i}),max(alphaVal{i})
        error('Script error: alpha values must be between 0 and 1.')
    end
  end
end

% -------------------------------------------
% * set initial view and parameters
% -------------------------------------------
%set(gcf,'Color','w')
axis off
[az,el] = view;
if ~isempty(O.azOffset),az = az - O.azOffset;,az2add = O.azOffset ./ numFrames;,end
if ~isempty(O.elOffset),el = el - O.elOffset;,el2add = O.elOffset ./ numFrames;,end
view(az,el)
lightFollowView
if ~isempty(O.zoom), myZoom = 1 + ((O.zoom-1) ./ numFrames);, end

% -------------------------------------------
% * initialize movie file, if necessary
% -------------------------------------------

if isempty(O.add2movie)
    try
        %mov = avifile(O.name,'Quality',75,'Compression','Indeo5','Fps',O.fps);
        mov = avifile(O.name,'Quality',75,'Compression','none','Fps',O.fps);
    catch
        error('Cannot open movie file.  Probably already open: Try changing filename.')
    end
else
    mov = O.add2movie;
end

try

H = gca;

% -------------------------------------------
% * rotate, zoom, etc. and add frames
% -------------------------------------------
for i = 1:numFrames

	if ~isempty(O.azOffset),az = az + az2add;,end
    if ~isempty(O.elOffset),el = el + el2add;,end
	if ~isempty(O.azOffset) | ~isempty(O.elOffset)
        view(az,el);
        lightFollowView
    end
	if ~isempty(O.zoom),camzoom(myZoom);,end
    if ~isempty(O.timecourse)
        for j = 1:length(alphaVal)
            set(O.H(j),'FaceAlpha',alphaVal{j}(i))
        end
        myTime = i ./ O.fps;
        if myTime == round(myTime)
            title(['Time = ' num2str(i ./ O.fps) '.0 s'],'Color','w','FontSize',18)
        else
            title(['Time = ' num2str(i ./ O.fps) ' s'],'Color','w','FontSize',18)
        end

    end
    drawnow
	try
        mov = addframe(mov,H);
    catch
        error('Cannot write frame.  Failed to set stream format??')
    end

end

catch, lasterr, warning('There was an error making this movie file.  No frames written.')
    mov = close(mov);
end

% -------------------------------------------
% * close the movie
% -------------------------------------------

if O.closemovie, mov = close(mov);, end

return


function [path, fileList, matches] = DPMpcNEW(leak, planC, stateS, nhist, OutputError)
% written by KZ
% Calculate IM struct, call DPM, get
%
% Usage: IIMCalc = calculateBeamIM(0.018, 'DPM_10beams_planC', 1, 1, 5)
%   leak = 0.018
%   planC_File = file name contained planC, eg. 'DPM_10beams_planC'
%   indexBeam = Beam Index: 1, 2, ...
%   imin = Beamlet index
%   imax = Beamlet index
%
%   eval(['load Beam',num2str(indexBeam),'_w']);
%   where, Beam1_w.mat (Beam2_w.mat) need to be in the current directory. It's the weight of
%   the beamlets for each beam.
%
% JC. Aug 10, 2005, Need to make planC read from the disk, since in the
% stand-alone mode, no matlab run is expected.
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

% open planC_File
% In matlab release 14, "eval" can be compiled.
Error = []; %Initialize Error to NULL.
% load(planC_File);
%eval(['load ',planC_File]);
%leak = 0.018; %leakage in per *100
% leak = str2num(leak)
currentDir = cd;

[FileName,path] = uigetfile('*.*','Select DICOM Dose File, RD');

if path == 0
    errordlg('DICOM Dose File Should exist');
    error('DICOM Dose File Should exist');
end

cd(path);

fileList = dir;

filesToRun = {};

matches = strmatch('RD', {fileList.name});

cd(currentDir);

for i = 1:length(matches)
    [maxDose, dA] = getDICOMMaxDose([path fileList(matches(i)).name]);
    dM(i) = maxDose;
end

for indexBeam = 1 : planC{7}.FractionGroupSequence.Item_1.NumberOfBeams

    bs = planC{7}.BeamSequence.(['Item_' num2str(indexBeam)]);

    LS = getDICOMLeafPositions(bs);

    [inflMap, xV, yV, colDividerXCoord, rowDividerYCoord, rowLeafPositions] = getLSInfluenceMapFactor(LS,leak,bs.BeamNumber);

    gA = bs.ControlPointSequence.Item_1.GantryAngle;
    iC = bs.ControlPointSequence.Item_1.IsocenterPosition;

    IMBase.beams(1).gantryAngle = gA;
    IMBase.beams(1).isocenter.x = iC(1)/10;
    IMBase.beams(1).isocenter.y = -iC(2)/10;
    IMBase.beams(1).isocenter.z = -iC(3)/10;

    IMBase.beams(1).isodistance = bs.SourceAxisDistance/10;

    IMBase.beams(1).xRel = IMBase.beams(1).isodistance * sindeg(IMBase.beams(1).gantryAngle);

    IMBase.beams(1).yRel = IMBase.beams(1).isodistance * cosdeg(IMBase.beams(1).gantryAngle);

    IMBase.beams(1).beamEnergy = bs.ControlPointSequence.Item_1.NominalBeamEnergy;

    [PBX] = getPBXCoorFromFluence(inflMap, rowLeafPositions, 2, 50, colDividerXCoord, rowDividerYCoord, 10);

    [xPosV, yPosV, beamlet_delta_x, beamlet_delta_y, w_field] = getPBVectors(PBX,rowLeafPositions,colDividerXCoord,rowDividerYCoord,inflMap);

    %Visualization
%         figure;hAxis1 = axes;imagesc([xV(1)+.05 xV(end)-.05], [yV(1)+.05, yV(end)-.05], inflMap);
%         set(gcf, 'renderer', 'zbuffer')
%         figure;hAxis2 = axes;hold on;
%         set(gcf, 'renderer', 'zbuffer')
%         xL = get(hAxis1, 'xlim');
%         yL = get(hAxis1, 'ylim');
%         set(hAxis2, 'xlim', xL);
%         set(hAxis2, 'ylim', yL);
%         axis(hAxis2, 'manual');
%     %     w_colors = floor((w_field ./ max(w_field))*255)+1;
%         set(gcf, 'doublebuffer', 'on');
%         for i=1:length(xPosV)
%             patch([xPosV(i) - beamlet_delta_x(i)/2 xPosV(i) - beamlet_delta_x(i)/2 xPosV(i) + beamlet_delta_x(i)/2 xPosV(i) + beamlet_delta_x(i)/2 xPosV(i) - beamlet_delta_x(i)/2], [yPosV(i) - beamlet_delta_y(i)/2 yPosV(i) + beamlet_delta_y(i)/2 yPosV(i) + beamlet_delta_y(i)/2 yPosV(i) - beamlet_delta_y(i)/2 yPosV(i) - beamlet_delta_y(i)/2], w_field(i));
%         end
%         axis([hAxis1 hAxis2], 'ij');
%         kids = get(hAxis2, 'children');
%     %     set(kids, 'edgecolor', 'none');
%         cMap = colormap('jet');
%         set(hAxis2, 'color', cMap(1,:));

    xPosV = xPosV/10;
    yPosV = yPosV/10;
    beamlet_delta_x = beamlet_delta_x/10;
    beamlet_delta_y = beamlet_delta_y/10;

    IMBase.goals.PBMargin = 0.5;
    IMBase.goals.structNum = 2;
    IMBase.params.xyDownsampleIndex = 1;
    IMBase.goals.isTarget(1) = 'y';
    IMBase.goals.xySampleRate = 2;
    IMBase.params.numCTSamplePts = 300;

    IMBase.beams(1).zRel = 0;
    IMBase.beams(1).xRel =  IMBase.beams(1).isodistance * sindeg(IMBase.beams(1).gantryAngle);
    IMBase.beams(1).yRel =  IMBase.beams(1).isodistance * cosdeg(IMBase.beams(1).gantryAngle);

    %IMBase.params.algorithm = 'VMC++';
    %IMCalc = IMRTP_MapCheck(IMBase);

    IMBase.params.algorithm = 'DPM';
    IMCalc = IMRTP_MapCheck(IMBase, planC, stateS, xPosV, yPosV, beamlet_delta_x, beamlet_delta_y, gA);
    % JC. 11 Aug, 05 Added more arguments to IMRTP_MapCheck,

    %disp('OK_BIG1'); pause(5);
    % JC. Aug. 3, 2005
    % Add fields to IMCalc, necessary for generateDPMInfluence.m
    IMCalc.beams.couchAngle = 0;
    IMCalc.beams.collimatorAngle = 0;
    IMCalc.params.ScatterMethod = 'exponential';
    IMCalc.params.Scatter.Threshold = 0.01;
    IMCalc.params.Scatter.RandomStep = 30;
    IMCalc.beamlets = struct;
    %eval(['load Beam',num2str(indexBeam),'_w']);
    IMCalc = DPMInfluenceNEW(IMCalc,'photon.spectrum',nhist, OutputError,planC,stateS)
    %     filename = ['IMCalc_Beam',num2str(indexBeam)];
    %     save(filename, 'IMCalc');

    IMCalc = DoseScale(IMCalc);

    dose3D = getIMDose(IMCalc, w_field, 1);
    %dose3D = (dose3D/max(dose3D(:)));

%     if ~exist('dose')
%         dose = dose3D;
%     else
%         dose = dose + dose3D;
%     end

    filename = ['dose3D_',num2str(indexBeam)];
    currentDir = pwd;
    mkdir([getCERRPath,'planCheck\MC\doseMC']);
    cd([getCERRPath,'planCheck\MC\doseMC']);
    save(filename, 'dose3D');
    save dM dM;
    cd(currentDir);
    %    eval(['save IMCalc_Beam',num2str(indexBeam),' IMCalc']);

   clear  dose3D;

end

% dose3D = dose;

%showIMDosePlanCheck;


function importIBSIPhase2DataToCERR(dataDir)
% importIBSIPhase2DataToCERR.m
% Download datasets from: https://github.com/theibsi/data_sets/
%-------------------------------------------------------------------------
% AI 10/06/2020
% AI 11/18/2022 Extnded for phase 2
% AI 12/10/2022 Extended for phase 3

%% Phase-1 : Synthetic phantoms
cerrPath = getCERRPath;
idxV = strfind(getCERRPath,filesep);
savePath = fullfile(cerrPath(1:idxV(end-1)),...
    'Unit_Testing\data_for_cerr_tests\IBSI2_synthetic_phantoms');

subDir = 'ibsi_2_digital_phantom';
synthDataDir = fullfile(dataDir,subDir,'nifti');
dirS = dir(synthDataDir);
dirS(1:2) = [];
for nDataset = 1:length(dirS)

    %Import scan
    synthDatasetName = fullfile(synthDataDir,dirS(nDataset).name,'image');
    synthDatasetDirS = dir([synthDatasetName,filesep,'*.nii.gz']);
    fileName = synthDatasetDirS.name;
    scanName = strtok(fileName,'.');
    filePath = fullfile(synthDatasetName,synthDatasetDirS.name);

    planC = nii2cerr(filePath,scanName,[],0);
    planC = updatePlanFields(planC);
    planC = quality_assure_planC(fileName,planC);

    %Create 'wholeScan' structure
    addMask3M = true(size(getScanArray(1,planC)));
    planC = maskToCERRStructure(addMask3M,0,1,...
        'wholeScan',planC);

    save_planC(planC,[],'PASSED',fullfile(savePath,...
        [scanName,'.mat']));

end

%% Phase-2 CT phantom
subDir = 'ibsi_2_ct_radiomics_phantom';
savePath = fullfile(cerrPath(1:idxV(end-1)),...
    'Unit_Testing\data_for_cerr_tests\IBSI2_CT_phantom');
scanName = subDir;
dcmMaskDir = fullfile(dataDir,subDir,'dicom','mask');
maskDirS = dir([dcmMaskDir,filesep,'*.dcm']);
dcmMaskPath = fullfile(dcmMaskDir,maskDirS.name);
outFileName = [savePath,filesep,'ibsi_2_ct_radiomics_phantom.mat'];

dcmScanDir = fullfile(dataDir,subDir,'dicom','image');
%Copy RT struct to be 'image' dir
copyfile(dcmMaskPath,dcmScanDir);

%planC = dcmdir2planC(dcmDataDir);
planC = importDICOM(dcmScanDir,savePath,true);
movefile([savePath,filesep,'image.mat'],outFileName);
planC = loadPlanC(outFileName,tempdir);
planC = updatePlanFields(planC);
planC = quality_assure_planC(outFileName,planC);

%Rename structure
indexS = planC{end};
planC{indexS.structures}(1).structureName = 'ROI';

save_planC(planC,[],'PASSED',outFileName);

%% IBSI2 phase 3
subDir = 'IBSI2_multimodal_data';
savePath = fullfile(cerrPath(1:idxV(end-1)),...
    'Unit_Testing\data_for_cerr_tests\IBSI2_multimodal_data');
allData = fullfile(dataDir,subDir);
modC = {'CT','MR_T1','PET'};

scanDirS = dir(allData);
scanDirS(1:2) = [];

for nDir = 1:length(scanDirS)

    scanName = scanDirS(nDir).name;
    outFileName = [savePath,filesep,scanName,'.mat'];

    for nMod = 1:length(modC)

        %Scan dir
        dcmScanDir = fullfile(dataDir,subDir,scanName,modC{nMod},'image');

        %Copy RT struct to be 'image' dir
        dcmMaskDir = fullfile(dataDir,subDir,scanName,modC{nMod},'mask');
        maskDirS = dir([dcmMaskDir,filesep,'*.dcm']);
        dcmMaskPath = fullfile(dcmMaskDir,maskDirS.name);
        copyfile(dcmMaskPath,dcmScanDir);

        %Import to CERR
        planD = importDICOM(dcmScanDir,savePath,true);
        movefile([savePath,filesep,'image.mat'],outFileName);
        planD = loadPlanC(outFileName,tempdir);
        planD = updatePlanFields(planD);
        planD = quality_assure_planC(outFileName,planD);
        if nMod==1
            planC = planD;
        else
            planC = planMerge(planC,planD,'all','all','all',outFileName);
        end

        %Rename structure
        indexS = planC{end};
        planC{indexS.structures}(end).structureName = [modC{nMod},'_ROI'];
    end

    save_planC(planC,[],'PASSED',outFileName);
    clear planC
end

end


function pri=getcodepri(sys,code,opt) %#ok

global glc

codepris=glc.codepris;
switch sys
    case glc.SYS_GPS,i=1;optstr='-GL';%#ok
    case glc.SYS_GLO,i=2;optstr='-RL';%#ok
    case glc.SYS_GAL,i=3;optstr='-EL';%#ok
    case glc.SYS_BDS,i=4;optstr='-BL';%#ok
    case glc.SYS_QZS,i=5;optstr='-QL';%#ok
end

pri=0;

[obs,j]=code2obs(code,sys);
if strcmp(obs,'')||j==0,return;end
obs=char(obs);

ind=strfind(char(codepris(i,j)),obs(2)); %i:sys j:freq
if any(ind)
    pri=15-ind;
else
    pri=0;
end

return


%% Example
% used to test the timing characteristic of the connection between IIWA and PC

% First run the following script in Matlab
% Then start the client on the KUKA iiwa controller

% Mohammad SAFEEA, 24th of April 2018

close all,clear all;clc;

ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
global t_Kuka;
t_Kuka=net_establishConnection( ip );

if ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')
  disp('Connection could not be establised, script aborted');
  return;
else
    disp('Connection established')
end
pause(1);
disp('This will take up a minute or so to finish, please wait')

[time_stamps,time_delay]=net_updateDelay(t_Kuka);

net_turnOffServer( t_Kuka );


function var = getvariables(F)
var = getvariables(lmi(F));


function initializeTrackTypePanel( horizontalBar, leftBottom, panelSize, hdls, fontSize )
%INITIALIZETRACKTYPEPANEL Initialize track type panel with a dropdown list of different track type

track_type_readable_list = { 'All', 'None'};

is_none = @(tag) 0;
is_all = @(tag) 1;

filter_functions = {is_all, is_none};

trackTypePanel = uipanel(horizontalBar, ...
    'Units', 'normalized', ...
    'Position', [leftBottom panelSize], ...
    'BorderType', 'None');

uicontrol(trackTypePanel, ...
    'String', 'Track type', ...
    'Style', 'text',...
    'Units', 'normalized', ...
    'FontSize', fontSize, ...
    'Position', [0 .5 1 .5]);

uicontrol(trackTypePanel, ...
    'String', track_type_readable_list, ...
    'Style', 'popup',...
    'Units', 'normalized', ...
    'FontSize', fontSize, ...
    'Position', [0 0 1 .5], ...
    'Callback', {@trackTypeBoxCallback, hdls, filter_functions});

hdls.track_type_filter_function = is_all;
end

function trackTypeBoxCallback(hObject, ~, hdls, filter_functions)

track_type_index = get(hObject, 'Value');
switch track_type_index
    case 1 % ALL
        hdls.is_plotting_all = true;
        hdls.is_plotting_none = false;
    case 2 % NONE
        hdls.is_plotting_none = true;
        hdls.is_plotting_all = false;
    otherwise
        hdls.track_type_filter_function = filter_functions{track_type_index};
        hdls.is_plotting_all = false;
        hdls.is_plotting_none = false;
end

hdls.generate_data();

end


% Add additional initialization if you want to.
% You can use this space to pre-compute the trajectory to avoid
% repeatedly computing the same trajectory in every call of the
% "trajectory_generator" function

% Generate trajectory
disp('Generating Trajectory ...');
trajectory_generator([], [], map, path);


function tutor = svctutor(arg)

% SVCTUTOR
%
% Constructor for a class of tutor objects used to train support vector
% classification networks.  Note this is an abstract base class, you cannot
% train an svc object using an svctutor.

%
% File        : @svctutor/svctutor.m
%
% Date        : Tuesday 12th September 2000
%
% Author      : Dr Gavin C. Cawley
%
% Description : Part of an object-oriented implementation of Vapnik's Support
%               Vector Machine, as described in [1].
%
% References  : [1] V.N. Vapnik,
%                   "The Nature of Statistical Learning Theory",
%                   Springer-Verlag, New York, ISBN 0-387-94559-8,
%                   1995.
%
% History     : 07/07/2000 - v1.00
%               12/09/2000 - v1.01 minor improvements to comments and help
%                                  messages
%
% Copyright   : (c) Dr Gavin C. Cawley, September 2000
%
%    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
%

if nargin == 0

   % this is the default constructor

   tutor.dummy = [];
   tutor       = class(tutor, 'svctutor');

elseif isa(arg, 'svctutor');

   % this is the copy constructor

   tutor = arg;

else

   % there are no other constructors

   help svctutor

end

% bye bye...


function title = p03_title ( )

%*****************************************************************************80
%
%% P03_TITLE returns the title of problem 3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, the title of the problem.
%
  title = 'The pulse data, 0 0 0 0 0 1 0 0 0 0 0';

  return
end


function tssk = t_mp_dm_converter_mpc2(quiet)
%T_MP_DM_CONVERTER_MPC2  Tests for MP.DM_CONVERTER_MPC2.

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

if nargin < 1
    quiet = 0;
end

% define_constants;
if quiet
    verbose = 0;
else
    verbose = 1;
end

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

casefile = 't_case_ext';
mpc0 = loadcase(casefile);
mpc0.bus(end, MU_VMIN) = 0;         %% add columns
mpc0.gen(end, MU_QMIN) = 0;         %% add columns
mpc0.branch(end, MU_ANGMAX) = 0;    %% add columns
dmc = mp.dm_converter_mpc2().build();

t_begin(27, quiet);

t = 'dmc constructor : ';
dmc = mp.dm_converter_mpc2();
t_ok(isa(dmc, 'mp.dm_converter'), [t 'class']);
t_is(length(dmc.element_classes), 5, 12, [t '# of element_classes']);
t_ok(isempty(dmc.elements), [t 'elements empty']);

t = 'dmc.build() : ';
dmc.build();
t_is(length(dmc.elements), 5, 12, [t '# of elements']);
t_str_match(dmc.elements{1}.name, 'bus', [t 'element{1} is bus']);
t_str_match(dmc.elements{2}.name, 'gen', [t 'element{2} is gen']);
t_str_match(dmc.elements{3}.name, 'load', [t 'element{3} is load']);
t_str_match(dmc.elements{4}.name, 'branch', [t 'element{4} is branch']);
t_str_match(dmc.elements{5}.name, 'shunt', [t 'element{5} is shunt']);

t = 'dm constructor : ';
dm = mp.data_model_cpf();
t_ok(isa(dm, 'mp.data_model'), [t 'class']);
t_is(length(dm.element_classes), 5, 12, [t '# of element_classes']);
t_ok(isempty(dm.elements), [t 'elements empty']);

t = 'dm.build(mpc, dmc) : ';
dm.build(mpc0, dmc);
t_is(length(dm.elements), 5, 12, [t '# of elements']);
t_str_match(dm.elements{1}.name, 'bus', [t 'element{1} is bus']);
t_str_match(dm.elements{2}.name, 'gen', [t 'element{2} is gen']);
t_str_match(dm.elements{3}.name, 'load', [t 'element{3} is load']);
t_str_match(dm.elements{4}.name, 'branch', [t 'element{4} is branch']);
t_str_match(dm.elements{5}.name, 'shunt', [t 'element{5} is shunt']);

t = 'mpc = dmc.export(dm, mpc0) : ';
mpc = dmc.export(dm, mpc0);
t_ok(isequal(mpc, mpc0), [t 'mpc == mpc0']);

t = 'mpc = dmc.export(updated_dm, mpc0) : ';
mpc1 = mpc0;
mpc1.bus([2;3;6;9], VM) = [1.02;1.03;1.06;1.09];
dm.elements.bus.tab.vm([2;3;6;9]) = [1.02;1.03;1.06;1.09];
mpc1.bus([3;5;7], PD) = [30;50;70];
mpc1.bus([3;5;7], QD) = [18;30;42];
load0 = dm.elements.load.tab;
load = [load0; load0(1:2, :)];
k = [4;1;5];
load.uid(k) = [4;1;5];
load.bus(k) = [30;5;6];
load.source_uid(k) = [3;5;7];
load.pd(k) = [30;50;70];
load.qd(k) = [18;30;42];
dm.elements.load.tab = load;
dm.elements.load.rebuild(dm);
mpc = dmc.export(dm, mpc0);
t_ok(~isequal(mpc, mpc0), [t 'mpc ~= mpc0']);
t_ok( isequal(mpc, mpc1), [t 'mpc == updated_mpc']);

t = 'mpc = dmc.export(dm) : ';
mpc1 = struct( ...
    'version', mpc0.version, ...
    'baseMVA', mpc0.baseMVA, ...
    'bus', mpc0.bus, ...
    'gen', mpc0.gen, ...
    'branch', mpc0.branch, ...
    'gencost', mpc0.gencost, ...
    'bus_name', {mpc0.bus_name} );
dmc = mp.dm_converter_mpc2().build();
dm = mp.data_model_opf().build(mpc1, dmc);
mpc = dmc.export(dm);
mpc1.gen(:, MBASE) = 0;
mpc1.branch(7, BR_STATUS) = 0;
t_ok(isequal(mpc, mpc1), [t 'mpc == mpc0']);

t = 'mpc = dmce.export(dme, mpc, ''qcost'') : ';
%% define named indices into data matrices
[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;
dme = dm.elements.gen;
dmce = dmc.elements.gen;
dme.tab.cost_qg = dme.tab.cost_pg;
dme.tab.cost_qg.poly_coef = dme.tab.cost_qg.poly_coef ./ 5;
ng = size(mpc.gen, 1);
epc = mpc.gencost(1:ng, :);
eqc = epc; eqc([1;3], COST) = eqc([1;3], COST) / 5;
mpc = dmce.export(dme, mpc, {'cost_qg'});
t_is(size(mpc.gencost, 1), 2*ng, 12, [t 'size(gencost, 1)']);
t_is(mpc.gencost(1:ng,:), epc, 12, [t 'pcost']);
t_is(mpc.gencost(ng+1:2*ng,:), eqc, 12, [t 'qcost']);

t = 'mpc = dmce.export(dme, mpc, ''qcost'', ridx) : ';
ridx = [2;3];
dme.tab.cost_pg.poly_coef = dme.tab.cost_pg.poly_coef * 2;
dme.tab.cost_pg.pwl_qty = dme.tab.cost_pg.pwl_qty + 10;
dme.tab.cost_pg.pwl_cost = dme.tab.cost_pg.pwl_cost + 10;
dme.tab.cost_qg.poly_coef = dme.tab.cost_qg.poly_coef * 3;
dme.tab.cost_qg.pwl_qty = dme.tab.cost_qg.pwl_qty + 1;
dme.tab.cost_qg.pwl_cost = dme.tab.cost_qg.pwl_cost + 1;
epc(2, COST:end) = epc(2, COST:end) + 10;
epc(3, COST:end) = epc(3, COST:end) * 2;
eqc(2, COST:end) = eqc(2, COST:end) + 1;
eqc(3, COST:end) = eqc(3, COST:end) * 3;
mpc = dmce.export(dme, mpc, {'cost_pg', 'cost_qg'}, ridx);
t_is(mpc.gencost(1:ng,:), epc, 12, [t 'pcost']);
t_is(mpc.gencost(ng+1:2*ng,:), eqc, 12, [t 'qcost']);

t_end;


function varargout = hlp_getresult(idx,f,varargin)
% Returns the Result-Idx's output of the function, given the supplied arguments.
% Results... = hlp_getresult(Result-Idx, Function, Arguments...)
%
% In:
%   Result-Idx : index of the result (output) of the given function application; can also
%                be a vector of indices, then re-emitting those outputs as outputs.
%                note: if this is passed as a cell array, the outputs will be wrapped into a cell
%                      array.
%
%   Function : function to apply to the Arguments
%
%   Arguments... : list of arguments to the function
%
% Out:
%   Results... : one or more outputs, selected according to Result-Idx from the outputs of
%                Function(Arguments...), and optionally wrapped into a cell array.
%
% Examples:
%   % get the second output of the sort() function, when applied to some data
%   hlp_getresult(2,@sort,[1 4 2 5 2 1 0 6])
%
% See also:
%   hlp_wrapresults
%
%				          		 Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-03-28

% Copyright (C) Christian Kothe, SCCN, 2010, christian@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

if isnumeric(idx)
    [tmp{1:max(idx)}] = f(varargin{:});
    varargout = tmp(idx);
elseif iscell(idx)
    [tmp{1:max([idx{:}])}] = f(varargin{:});
    varargout = {tmp([idx{:}])};
else
    error('Unsupported index format (must be either numeric or cell array).');
end


hydro = struct();

hydro = readWAMIT(hydro,'cubes.out',[]);
hydro = radiationIRF(hydro,20,[],[],[],[]);
hydro = radiationIRFSS(hydro,[],[]);
hydro = excitationIRF(hydro,200,[],[],[],[]);
writeBEMIOH5(hydro)
plotBEMIO(hydro)