function [rxnList,metList] = autoMatchReactions(scoreTotal, rxnList, metList, varargin)
% Finds confident matches from CMODEL to TMODEL.
% reactions which can not be confidently assigned are reviewed with
% `reactionCompare`. To make a confident assignment a matched reaction must
% have a score above a supplied cutoff and not have competing matches with
% similar scores. Called by `reactionCompareGUI`, calls `metCompare`.
%
% USAGE:
%
%    rxnList = autoMatchReactions(scoreTotal, rxnList, metList, [rxnHighCutoff, rxnMargin, rxnLowCutoff], [metHighCutoff, metMargin, metLowCutoff])
%
% INPUTS:
%    scoreTotal:       Optimized score matrix between `CMODEL` and `TMODEL` reactions.
%    rxnList:          Only undeclared reactions will be automatched.
%    metList:          Comparison array for metabolites
%
% OPTIONAL INPUTS:
%    rxnHighCutoff:    Score value above which confident assignments can be made.
%    rxnMargin:        Distance a best match has to be above a competitor match.
%    rxnLowCutoff:     Score value below which reactions will be declared new.
%    metHighCutoff:    The following three are the same but for mets.
%    metMargin:
%    metLowCutoff:
%    CMODEL:           global input
%    TMODEL:           global input
%
% OUTPUTS:
%    rxnList:          Array which correlates a reaction from CMODEL to the index
%                      of the best match in `TMODEL`. Rxns with 0 designation are
%                      new, ones with a -1 need manual review.
% Please cite:
% `Sauls, J. T., & Buescher, J. M. (2014). Assimilating genome-scale
% metabolic reconstructions with modelBorgifier. Bioinformatics
% (Oxford, England), 30(7), 1036?8`. http://doi.org/10.1093/bioinformatics/btt747
%
% ..
%    Edit the above text to modify the response to help addMetInfo
%    Last Modified by GUIDE v2.5 06-Dec-2013 14:19:28
%    This file is published under Creative Commons BY-NC-SA.
%
%    Correspondance:
%    johntsauls@gmail.com
%
%    Developed at:
%    BRAIN Aktiengesellschaft
%    Microbial Production Technologies Unit
%    Quantitative Biology and Sequencing Platform
%    Darmstaeter Str. 34-36
%    64673 Zwingenberg, Germany
%    www.brain-biotech.de

h = waitbar(0, 'Automatching') ; % Declare variables.

global CMODEL TMODEL

% Number of reactions in CMODEL.
nCrxn = size(scoreTotal, 1) ;

% Assign cutoff params if possible.
if nargin >= 6 %8
    rxnHighCutoff = varargin{1} ;
    rxnMargin = varargin{2} ;
    rxnLowCutoff = varargin{3} ;
else
    rxnHighCutoff = 0.99 ;
    rxnMargin = 0.1 ;
    rxnLowCutoff = 0.01 ;
end
% get metabolite automatch cutoffs if possible
if nargin >= 8 %10
    metHighCutoff = varargin{4} ;
    metMargin = varargin{5} ;
    metLowCutoff = varargin{6} ;
else
    metHighCutoff = 0.99 ;
    metMargin = 0.1 ;
    metLowCutoff = 0.01 ;
end
% Save a form of the rxnList before auto matching.
rxnListBefore = rxnList ;

%% Find probable matches based on scoring.
% Find best scoring matches.
[sortMatch, sortMatchIndex] = sort(scoreTotal, 2, 'descend') ;

% Only consider reactions which have not been previously declared.
probMatch = [] ;
pos = 1 ;
for iRxn = 1:nCrxn
    if sortMatch(iRxn, 1) > rxnHighCutoff && ...
            sortMatch(iRxn, 1) - sortMatch(iRxn, 2) > rxnMargin && ...
            rxnList(iRxn) == -1
        rxnList(iRxn) = sortMatchIndex(iRxn, 1) ;
        probMatch(pos, 1) = iRxn ;
        pos = pos + 1 ;
    end
end

%% Double check reactions for hints that they are misses.
% Set the test columns in probMatch to 1. Innocent until proven guilty.
if ~isempty(probMatch)
    probMatch(:, 2:5) = 1 ;
end

for iRxn = 1:size(probMatch, 1)
    % Check if matched reaction has been associated with another reaction.
    nowMatch = rxnList(probMatch(iRxn, 1)) ;
    % The match should only be in rxnList once.
    if length(find(rxnList == nowMatch)) ~= 1
        probMatch(iRxn, 2) = 0 ;
    end

    % Check if paired reactions have KEGG IDs and if they match.
    cKegg = CMODEL.rxnKEGGID{probMatch(iRxn, 1)} ;
    tKegg = TMODEL.rxnKEGGID{rxnList(probMatch(iRxn, 1))} ;
    if ~isempty(cKegg) && ~isempty(tKegg)
        pipePos = [0 strfind(cKegg, '|') length(cKegg) + 1] ;
        for jID = 1:length(pipePos) - 1
            nowID = cKegg(pipePos(jID)+1:pipePos(jID + 1) - 1) ;
            if isempty(strfind(tKegg, nowID))
                probMatch(iRxn, 3) = 0 ;
            end
        end
    end

    % Check if paired reactions have the same stoichiometry.
    if CMODEL.metNums(probMatch(iRxn, 1), 2) ~= ...
            TMODEL.metNums(rxnList(probMatch(iRxn, 1)), 2)
        probMatch(iRxn, 4) = 0 ;
    end

    % Check if paired reactions have the same compartment.
    if ~isempty(CMODEL.rxnComp{probMatch(iRxn, 1)} ) && ~isempty(TMODEL.rxnComp{rxnList(probMatch(iRxn, 1))})
        if ~strcmp(CMODEL.rxnComp{probMatch(iRxn, 1)}, ...
                TMODEL.rxnComp{rxnList(probMatch(iRxn, 1))})
            probMatch(iRxn, 5) = 0 ;
        end
    end

    % If any of the above tests failed, set the match in rxnList backto -1.
    if probMatch(iRxn, 2:end)
    else
        rxnList(probMatch(iRxn, 1)) = -1 ;
    end
end

clear probMatch nowMatch cKegg tKegg

%% Assign new reactions based on cutoff.
for iRxn = 1:nCrxn
    if rxnList(iRxn) == -1 && ...
            sortMatch(iRxn,1) < rxnLowCutoff
        rxnList(iRxn) = 0 ;
    end
end

%% Assign new reactions based on metabolites that have been declared.
% For undeclared reactions in CMODEL, find the indexes of their metabolite
% matches.
for iRxn = 1:length(rxnList)
    if rxnList(iRxn) == -1
        % For the reaction in question from CMODEL.
        metPos = find(CMODEL.S(:, iRxn)) ;
        cMetMatchIndexes = zeros(length(metPos), 1) ;
        for iMet = 1:length(metPos)
            cMetMatchIndexes(iMet) = metList(metPos(iMet)) ;
        end
        % For the best match from TMODEL.
        tMetMatchIndexes = find(TMODEL.S(:, sortMatchIndex(iRxn, 1))) ;
        % If all the mets have been declared in cRxn, and the best match
        % from T does not have exactly those mets, declare a new reaction.
        if isempty(find(cMetMatchIndexes == 0, 1))
            if logical(ismember(cMetMatchIndexes, tMetMatchIndexes)) * ...
                    length(cMetMatchIndexes) == length(tMetMatchIndexes)
            else
                rxnList(iRxn) = 0 ;
            end
        end
        % Also declare reactions as new it they have a new metabolite(s).
        if ~isempty(find(cMetMatchIndexes > length(TMODEL.mets), 1))
            rxnList(iRxn) = 0 ;
        end
    end
end

%% For reactions that have just been matched or declared new, find mets.
% Find newly auto-matched reactions.
autoMatchedRxns = find(rxnList(:) ~= rxnListBefore(:)) ;

% Prepare data structure to be passed.
RxnInfo.rxnList = rxnList ;

for iRxn = 1:length(autoMatchedRxns)
    RxnInfo.rxnIndex = autoMatchedRxns(iRxn) ;
    RxnInfo.rxnMatch = rxnList(autoMatchedRxns(iRxn)) ;
    RxnInfo.metList = metList ;
    RxnInfo.metAutoMatchLimits = [metHighCutoff, metMargin, metLowCutoff] ;

    % Launch comparison script.
    [metList, stopFlag] = metCompare(RxnInfo) ;

    % If metCompare was suspended, don't attempt to find matches for the
    % reamining reactions.
    if stopFlag
        break
    end
    waitbar(iRxn/length(autoMatchedRxns), h)
end

close(h)


%{
    Copyright (c) 2015, Philipp Krähenbühl
    All rights reserved.

    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.
        * Neither the name of the Stanford University nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY Philipp Krähenbühl ''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 Philipp Krähenbühl 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.
%}

% Usage example:
% I = imread('peppers.png');
% os = OverSegmentation( I );
% imagesc( os.s() ) % To visualize the over-segmentation

classdef LpoOverSegmentation
    properties (SetAccess = private, GetAccess = public)
        c_s
    end
    methods
        function obj = LpoOverSegmentation( I, NS, thick_bnd, thin_bnd )
            if nargin == 0
                error( 'Input image required' );
            end
            if nargin < 2
                NS = 1000;
            end
            if nargin == 3
                error( 'Cannot have a thick boundary map without a thinned out one!' );
            end
            if nargin < 3
                obj.c_s = lpo_mex( 'newImageOverSegmentation', I, NS );
            else
                obj.c_s = lpo_mex( 'newImageOverSegmentation', I, NS, thick_bnd, thin_bnd );
            end
        end
        function sobj = saveobj(this)
            sobj = this;
            sobj.c_s = lpo_mex( 'ImageOverSegmentation_serialize', this.c_s );
        end
        function r = s(this)
            r = lpo_mex( 'ImageOverSegmentation_s', this.c_s );
        end
        function r = boundaryMap(this)
            r = lpo_mex( 'ImageOverSegmentation_boundaryMap', this.c_s );
        end
        function r = maskToBox(this,mask)
            r = lpo_mex( 'ImageOverSegmentation_maskToBox', this.c_s, mask );
        end
        function delete(this)
            lpo_mex( 'freeImageOverSegmentation', this.c_s );
        end
    end
    methods (Static)
        function obj = loadobj(obj)
            data = obj.c_s;
            obj.c_s = lpo_mex( 'newImageOverSegmentationEmpty' );
            lpo_mex( 'ImageOverSegmentation_unserialize', obj.c_s, data )
        end
    end
end


% downloading all models

addpath('../functions/');

mkdir_if_missing('../weight/');
mkdir_if_missing('./temp');

%% for detection files
fprintf('Downloading faster_rcnn_final_model...\n');
urlwrite('https://onedrive.live.com/download?resid=D7AF52BADBA8A4BC!114&authkey=!AERHoxZ-iAx_j34&ithint=file%2czip', ...
    './temp/faster_rcnn_final_model.zip');

fprintf('Unzipping...\n');
unzip('./temp/faster_rcnn_final_model.zip', './temp/');

movefile ./temp/output/faster_rcnn_final/faster_rcnn_VOC0712_vgg_16layers/detection_final  ../weight/detection_final_VGG
movefile ./temp/output/faster_rcnn_final/faster_rcnn_VOC0712_ZF/detection_final  ../weight/detection_final_ZF
fprintf('Detection Models Done.\n');

rmdir('./temp/', 's');

%% for segmentation files
fprintf('Downloading fcn models...\n')
urlwrite('http://dl.caffe.berkeleyvision.org/fcn8s-heavy-pascal.caffemodel', ...
    '../weight/fcn8s-heavy-pascal.caffemodel');

urlwrite('http://dl.caffe.berkeleyvision.org/fcn-alexnet-pascal.caffemodel', ...
    '../weight/fcn-alexnet-pascal.caffemodel');

fprintf('Segmentation Models Done.\n');


function [varargout] = fIdentity(varargin)
% FIDENTITY  The global identity function
varargout = varargin;


function vl_testnn(varargin)
%VL_TESTNN Run MatConvNet test suite
% VL_TESTNN('option', value, ...) takes the following options:
%  `cpu`:: true
%    Run the CPU tests.
%
%  `gpu`:: false
%    Run the GPU tests.
%
%  `single`:: true
%    Perform tests in single precision.
%
%  `double`:: false
%    Perform tests in double precision.
%
%  `command`:: `'nn'`
%    Run only tests which name starts with the specified substring.
%    E.g. `vl_testnn('command', 'nnloss') would run only the nnloss tests.
%
%  `break`:: false
%    Stop tests in case of error.
%
%  `tapFile`:: ''
%    Output the test results to a file. If a specified file does
%    exist it is overwritten.
%
%  `suiteDir`:: ''
%    Specifies the directory where the test suite files are located. If
%    left empty, the default suite is used (<MatConvNetRoot>/matlab/xtest/
%    /suite).
%
%  This function uses the Matlab unit testing framework which was
%  introduced in Matlab R2013a (v8.1).

% Copyright (C) 2015-16 Andrea Vedaldi, Karel Lenc.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

opts.cpu = true ;
opts.gpu = false ;
opts.single = true ;
opts.double = false ;
opts.command = 'nn' ;
opts.break = false ;
opts.tapFile = '';
opts.suiteDir = '' ;
opts = vl_argparse(opts, varargin) ;

import matlab.unittest.constraints.* ;
import matlab.unittest.selectors.* ;
import matlab.unittest.plugins.TAPPlugin;
import matlab.unittest.plugins.ToFile;
addpath(fullfile(vl_rootnn, 'examples'));

% Choose which tests to run
sel = HasName(StartsWithSubstring(opts.command)) ;
if ~opts.gpu
  sel = sel & ~HasName(ContainsSubstring('device=gpu')) ;
end
if ~opts.cpu
  sel = sel & ~HasName(ContainsSubstring('device=cpu')) ;
end
if ~opts.double
  sel = sel & ~HasName(ContainsSubstring('dataType=double')) ;
end
if ~opts.single
  sel = sel & ~HasName(ContainsSubstring('dataType=single')) ;
end

root = fileparts(mfilename('fullpath')) ;
if isempty(opts.suiteDir)
  opts.suiteDir = fullfile(root, 'suite') ;
else  % any external subclasses of nntest will need it to be on the path
  addpath(fullfile(root, 'suite')) ;
end

% Run tests
suite = matlab.unittest.TestSuite.fromFolder(opts.suiteDir, sel) ;
runner = matlab.unittest.TestRunner.withTextOutput('Verbosity',3);
if opts.break
  runner.addPlugin(matlab.unittest.plugins.StopOnFailuresPlugin) ;
end
if ~isempty(opts.tapFile)
  if exist(opts.tapFile, 'file')
    delete(opts.tapFile);
  end
  runner.addPlugin(TAPPlugin.producingOriginalFormat(ToFile(opts.tapFile)));
end
result = runner.run(suite);
display(result)


% Defines a gene
%
% Author: Jonathan Karr
% Affilitation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 5/7/2009
classdef Gene < edu.stanford.covert.cell.kb.ssRNA

    properties
        genome                      = edu.stanford.covert.cell.kb.Genome.empty(0, 0);
        transcriptionUnits          = edu.stanford.covert.cell.kb.TranscriptionUnit.empty(0, 0);
        proteinMonomers             = edu.stanford.covert.cell.kb.ProteinMonomer.empty(0, 0);
        stableModificationReactions = edu.stanford.covert.cell.kb.Reaction.empty(0, 0);
        aminoAcid                   = edu.stanford.covert.cell.kb.Metabolite.empty(0, 0);
        compartment                 = edu.stanford.covert.cell.kb.Compartment.empty(0, 0);
    end

    properties %(SetAccess = protected)
        halfLife
        sequence

        symbol
        synonyms
        type
        startCodon
        codons
        startCoordinate
        endCoordinate
        direction
        essential
        expression
    end

    %computed properties
    properties %(SetAccess = protected)
        dnaSequence
        fivePrimeCoordinate
        threePrimeCoordinate
        synthesisRate

        matureBaseCount
        matureMolecularWeight
        matureDecayReaction

        aminoacylatedBaseCount
        aminoacylatedMolecularWeight
        aminoacylatedDecayReaction

        features
    end

    methods
        %constructor
        function this = Gene(knowledgeBase, wid, wholeCellModelID, name, ...
                symbol, synonyms, type, startCodon, codons, ...
                startCoordinate, sequenceLength, direction, essential, halfLife, ...
                expression, comments, crossReferences)

            if nargin == 0; return; end;

            this = edu.stanford.covert.cell.kb.Gene.empty(size(wid, 1), 0);
            this(size(wid, 1), 1) = edu.stanford.covert.cell.kb.Gene;
            for i = 1:size(wid, 1)
                this(i, 1).idx = i;
                this(i, 1).knowledgeBase = knowledgeBase;
                this(i, 1).wid = wid(i);
                this(i, 1).wholeCellModelID = wholeCellModelID{i};
                this(i, 1).name = name{i};
                if exist('comments', 'var') && ~isempty(comments); this(i, 1).comments = comments{i}; end;
                if exist('crossReferences', 'var')
                    if size(crossReferences,1) > 1
                        this(i, 1).crossReferences = crossReferences(i);
                    else
                        this(i, 1).crossReferences = struct;
                        fields = fieldnames(crossReferences);
                        for j = 1:size(fields, 1)
                            values = crossReferences.(fields{j});
                            this(i, 1).crossReferences.(fields{j}) = values(i);
                        end
                    end
                end

                this(i, 1).symbol = symbol{i};
                this(i, 1).synonyms = strsplit(';', synonyms{i});
                this(i, 1).type = type{i};
                this(i, 1).startCodon = startCodon(i);
                this(i, 1).codons = strsplit(';', codons{i});
                this(i, 1).startCoordinate = startCoordinate(i);
                this(i, 1).endCoordinate = startCoordinate(i) + sequenceLength(i) - 1;
                this(i, 1).direction = direction(i);
                this(i, 1).essential = essential{i};
                this(i, 1).expression = expression(i, :);
                this(i, 1).halfLife = halfLife(i);
            end
        end

        function serializeLinks(this)
            for i = 1:numel(this)
                this(i).genome                      = this.serializeLinksHelper(this(i).genome);
                this(i).transcriptionUnits          = this.serializeLinksHelper(this(i).transcriptionUnits);
                this(i).proteinMonomers             = this.serializeLinksHelper(this(i).proteinMonomers);
                this(i).stableModificationReactions = this.serializeLinksHelper(this(i).stableModificationReactions);
                this(i).aminoAcid                   = this.serializeLinksHelper(this(i).aminoAcid);
                this(i).compartment                 = this.serializeLinksHelper(this(i).compartment);

                serializeLinks@edu.stanford.covert.cell.kb.ssRNA(this(i));
            end
        end

        function deserializeLinks(this, kb)
            for i = 1:numel(this)
                this(i).genome                      = this.deserializeLinksHelper(this(i).genome, kb.genome);
                this(i).transcriptionUnits          = this.deserializeLinksHelper(this(i).transcriptionUnits, kb.transcriptionUnits);
                this(i).proteinMonomers             = this.deserializeLinksHelper(this(i).proteinMonomers, kb.proteinMonomers);
                this(i).stableModificationReactions = this.deserializeLinksHelper(this(i).stableModificationReactions, kb.reactions);
                this(i).aminoAcid                   = this.deserializeLinksHelper(this(i).aminoAcid, kb.metabolites);
                this(i).compartment                 = this.deserializeLinksHelper(this(i).compartment, kb.compartments);

                deserializeLinks@edu.stanford.covert.cell.kb.ssRNA(this(i), kb);
            end
        end

        function deleteLinks(this)
            for i = 1:numel(this)
                this(i).genome                      = [];
                this(i).transcriptionUnits          = [];
                this(i).proteinMonomers             = [];
                this(i).stableModificationReactions = [];
                this(i).aminoAcid                   = [];
                this(i).compartment                 = [];

                deleteLinks@edu.stanford.covert.cell.kb.ssRNA(this(i));
            end
        end

        function value = get.fivePrimeCoordinate(this)
            %retrieve
            if ~isempty(this.fivePrimeCoordinate)
                value = this.fivePrimeCoordinate;
                return;
            end

            %compute
            if this.direction
                value = this.startCoordinate;
            else
                value = this.endCoordinate;
            end

            %store
            this.fivePrimeCoordinate = value;
        end

        function value = get.threePrimeCoordinate(this)
            %retrieve
            if ~isempty(this.threePrimeCoordinate)
                value = this.threePrimeCoordinate;
                return;
            end

            %compute
            if this.direction
                value = this.endCoordinate;
            else
                value = this.startCoordinate;
            end

            %store
            this.threePrimeCoordinate = value;
        end

        function value = get.dnaSequence(this)
            %retrieve
            if ~isempty(this.dnaSequence)
                value = this.dnaSequence;
                return;
            end

            %compute
            if this.direction
                value = this.genome.sequence(this.startCoordinate:this.endCoordinate);
            else
                value = seqrcomplement(this.genome.sequence(this.startCoordinate:this.endCoordinate));
            end

            %store
            this.dnaSequence = value;
        end

        function value = get.sequence(this)
            %retrieve
            if ~isempty(this.sequence)
                value = this.sequence;
                return;
            end

            %compute
            value = this.dnaSequence;
            value(this.dnaSequence == 'A') = 'U';
            value(this.dnaSequence == 'C') = 'G';
            value(this.dnaSequence == 'G') = 'C';
            value(this.dnaSequence == 'T') = 'A';

            %store
            this.sequence = value;
        end

        function value = get.matureBaseCount(this)
            %retrieve
            if ~isempty(this.matureBaseCount)
                value = this.matureBaseCount;
                return;
            end

            %compute
            value = this.baseCount;

            if isempty(this.stableModificationReactions)
                return;
            end

            modifications = zeros(size(value));
            for i = 1:length(this.stableModificationReactions)
                reaction = this.stableModificationReactions(i);

                for j = 1:length(reaction.metabolites)
                    if any(this.knowledgeBase.modifiedNMPIndexs == reaction.metabolites(j).idx) || ...
                            (any(this.knowledgeBase.nmpIndexs == reaction.metabolites(j).idx) && reaction.metaboliteCoefficients(j) < 0)

                        modifications([reaction.metabolites(j).idx]) = ...
                            modifications([reaction.metabolites(j).idx]) + ...
                            reaction.metaboliteCoefficients(j)';
                    end
                end
            end

            value = value + modifications;

            %store
            this.matureBaseCount = value;
        end

        function value = get.matureMolecularWeight(this)
            % import classes
            import edu.stanford.covert.util.ConstantUtil;

            %retrieve
            if ~isempty(this.matureMolecularWeight)
                value = this.matureMolecularWeight;
                return;
            end

            %compute
            molecularWeightHO = ConstantUtil.elements.H + ConstantUtil.elements.O;

            baseCount = this.matureBaseCount;

            metabolicMolecularWeights = this.knowledgeBase.metaboliteMolecularWeights;

            value = baseCount * metabolicMolecularWeights - ...
                molecularWeightHO * max(0, this.sequenceLength - strcmp(this.sequenceTopology, 'linear'));

            %store
            this.matureMolecularWeight = value;
        end

        function value = get.matureDecayReaction(this)
            %retrieve
            if ~isempty(this.matureDecayReaction)
                value = this.matureDecayReaction;
                return;
            end

            %compute
            value = this.matureBaseCount;
            value(this.knowledgeBase.waterIndexs)    = value(this.knowledgeBase.waterIndexs)    - max(0, this.sequenceLength - strcmp(this.sequenceTopology, 'linear'));
            value(this.knowledgeBase.hydrogenIndexs) = value(this.knowledgeBase.hydrogenIndexs) + max(0, this.sequenceLength - strcmp(this.sequenceTopology, 'linear'));

            %store
            this.matureDecayReaction = value;
        end

        function value = get.aminoacylatedBaseCount(this)
            %retrieve
            if ~isempty(this.aminoacylatedBaseCount)
                value = this.aminoacylatedBaseCount;
                return;
            end

            %compute
            value = this.matureBaseCount;
            if ~isempty(this.aminoAcid)
                value(this.aminoAcid.idx) = value(this.aminoAcid.idx) + 1;
            end

            %store
            this.aminoacylatedBaseCount = value;
        end

        function value = get.aminoacylatedMolecularWeight(this)
            import edu.stanford.covert.util.ConstantUtil;

            %retrieve
            if ~isempty(this.aminoacylatedMolecularWeight)
                value = this.aminoacylatedMolecularWeight;
                return;
            end

            %compute
            value = this.matureMolecularWeight;
            if ~isempty(this.aminoAcid)
                molecularWeightHO = ConstantUtil.elements.H + ConstantUtil.elements.O;
                value = value + this.aminoAcid.molecularWeight - molecularWeightHO;
            end

            %store
            this.aminoacylatedMolecularWeight = value;
        end

        function value = get.aminoacylatedDecayReaction(this)
            %retrieve
            if ~isempty(this.aminoacylatedDecayReaction)
                value = this.aminoacylatedDecayReaction;
                return;
            end

            %compute
            value = this.matureDecayReaction;
            if ~isempty(this.aminoAcid)
                value(this.aminoAcid.idx) = value(this.aminoAcid.idx) + 1;
                value(this.knowledgeBase.waterIndexs)    = value(this.knowledgeBase.waterIndexs)    - 1;
                value(this.knowledgeBase.hydrogenIndexs) = value(this.knowledgeBase.hydrogenIndexs) + 1;
            end

            %store
            this.aminoacylatedDecayReaction = value;
        end

        function value = get.synthesisRate(this)
            %retrieve
            if ~isempty(this.synthesisRate)
                value = this.synthesisRate;
                return;
            end

            %compute
            value = log(2) / this.halfLife * this.expression;

            %store
            this.synthesisRate = value;
        end

        function value = get.features(this)
            %retrieve
            if ~isempty(this.features)
                value = this.features;
                return;
            end

            %compute
            featureStartCoordinates = [this.genome.features.startCoordinate];
            featureEndCoordinates = [this.genome.features.endCoordinate];
            value = this.genome.features(...
                (this.startCoordinate > featureStartCoordinates & this.startCoordinate < featureEndCoordinates) | ...
                (this.endCoordinate   > featureStartCoordinates & this.endCoordinate   < featureEndCoordinates) | ...
                (this.startCoordinate < featureStartCoordinates & this.endCoordinate   > featureEndCoordinates));

            %store
            this.features = value;
        end
    end
end


function varargout=zerotrim(varargin)
%
% For calling details please see v_zerotrim.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_zerotrim.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: zerotrim.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_zerotrim(varargin{:});
else
    v_zerotrim(varargin{:});
end


function APPdownload(username, destImages, destAnnotations)
% Downloads the images and annotations collected with the LabelMe app.
%
% For more details visit:
% http://labelme2.csail.mit.edu/Release3.0/browserTools/php/iPhoneHelp.php
%
% Usage:
%
%   APPdownload(username)
%
%   or, you can specify the destination folders where the images and
%   annotations will be saved:
%
%   APPdownload(username, destImages, destAnnotations)
%
% Example:
%   APPdownload(username)
%   D=LMdatabase('Annotations');
%   LMdbshowscenes(D, 'Images');

if nargin == 1
    destImages = 'Images';
    destAnnotations = 'Annotations';
end

HOMEANNOTATIONS = ['http://labelme.csail.mit.edu/Annotations/users/' username];
HOMEIMAGES = ['http://labelme.csail.mit.edu/Images/users/' username];

% folder index
folder = {'iPhoneCollection'};

% create list of folders to copy, copy and rename folders in XML:
LMinstall(folder, destImages, destAnnotations, HOMEIMAGES, HOMEANNOTATIONS)

% make sure folder names are coherent
ADMINrenamefolder(destAnnotations);


classdef prtUiManagerImage < prtUiManagerAxes

    properties (Dependent)

    end

    properties
        imageHandle = [];
        climSliderHandle = [];
    end
    properties (Hidden)
        axesPosition
    end

    methods

        function tickoff(self)
            set(self.managedHandle,'xtick',[]);
            set(self.managedHandle,'ytick',[]);
        end

        function self = prtUiManagerImage(varargin)
           if nargin
               self = prtUtilAssignStringValuePairs(self, varargin{:});
           end
        end

        function reImage(self, varargin)
            if isempty(self.imageHandle)
                self.imageHandle = image(varargin{:},'Parent',self.managedHandle);
            else
                self.updateCData(varargin{1});
            end
        end

        function reImagesc(self, varargin)
            if isempty(self.imageHandle)
                self.imageHandle = imagesc(varargin{:},'Parent',self.managedHandle);
            else
                self.updateCData(varargin{1});
            end
        end

        function reImshow(self, varargin)
            if isempty(self.imageHandle)
                self.imageHandle = imshow(varargin{:},'Parent',self.managedHandle);
            else
                self.updateCData(varargin{1});
            end
        end

        function image(self,varargin)
            self.imageHandle = image(varargin{:},'Parent',self.managedHandle);
        end

        function imagesc(self,varargin)
            self.imageHandle = imagesc(varargin{:},'Parent',self.managedHandle);
        end

        function imshow(self,varargin)
            self.imageHandle = imshow(varargin{:},'Parent',self.managedHandle);
        end

        function updateCData(self, cData)
            % updateData(self, cData)
            self.checkValid;

            prevCdata = get(self.imageHandle,'cdata');
            if ~isequal(size(prevCdata),size(cData))
                warning('prt:prtUiManagerImage:changeCdataSize','Attempt to change the size of the data in an image by setting the cData, try re-creating the image');
            end
            set(self.imageHandle,'CData',cData);
        end

        function ih = get.imageHandle(self)
            ih = self.imageHandle;
        end

        function shapePoly = getRoiPoly(self)
            % Output either a struct or an empty array
            self.checkValid;

            axes(self.managedHandle); %#ok<MAXES> %Because roipoly doesn't let you specify axes
            [~,xi,yi] = roipoly;
            shapePoly = [];
            if ~isempty(xi)
                shapePoly = struct('type','poly','xi',xi,'yi',yi);
            end
        end

        function shapeLine = getRoiLine(self)
            % Output either a struct or an empty array
            self.checkValid;

            axes(self.managedHandle); %#ok<MAXES> %Because roipoly doesn't let you specify axes
            [~,xi,yi] = roipoly;
            shapeLine = [];
            if ~isempty(xi)
                xi = xi(1:end-1);
                yi = yi(1:end-1);
                shapeLine = struct('type','line','xi',xi,'yi',yi);
            end
        end

        function shapeRect = getRoiRect(self)
            % Output either a struct or an empty array
            self.checkValid;

            axes(self.managedHandle); %#ok<MAXES>  %Because imcrop doesn't let you specify axes
            [~,rect] = imcrop;
            shapeRect = [];
            if ~isempty(rect)
                xi = [rect(1);rect(1);rect(1)+rect(3);rect(1)+rect(3);rect(1)];
                yi = [rect(2);rect(2)+rect(4);rect(2)+rect(4);rect(2);rect(2)];
                shapeRect = struct('type','rect','xi',xi,'yi',yi);
            end

        end

        function shapePoint = getRoiPoint(self)
            % Output either a struct or an empty array
            self.checkValid;

            axes(self.managedHandle); %#ok<MAXES>  %Because imcrop doesn't let you specify axes
            [xi, yi] = getpts;
            shapePoint = [];
            if ~isempty(xi)
                shapePoint = struct('type','point','xi',xi(end),'yi',yi(end));
            end

        end

        function is = checkValid(self)
            assert(ishandle(self.imageHandle),'prt:prtUiManagerImage:badHandle','Some or all of the requested handles are no longer valid. The axes may have been deleted.');
            is = true;
        end

        function h = plotShape(self,shapeArray)
            self.checkValid;

            axes(self.managedHandle); %#ok<MAXES>  %Because ishold doesn't let you specify axes
            holdState = ishold;
            h = nan(size(shapeArray));
            hold(self.managedHandle,'on');
            %Plot each shape:
            try
                for i = 1:length(shapeArray)
                    if length(shapeArray(i).xi) == 1
                        h(i) = plot(shapeArray(i).xi,shapeArray(i).yi,'bo'); %points
                    else
                        h(i) = plot(shapeArray(i).xi,shapeArray(i).yi,'b');
                    end
                end
            catch ME
                disp(ME)
                debugdlg('I had trouble plotting one of your objects.  Do you want to debug?');
            end
            if ~holdState
                hold(self.managedHandle,'off');
            end
        end
    end
end


function varargout = arg_toworkspace(s)
% Copy the arguments in the given Struct into the workspace of the calling function.
% Outputs... = arg_toworkspace(Struct)
%
% This function can be used to populate the function's workspace with fields of a struct, and
% optionally allows to assign the first k fields of the struct to explicitly named output variables.
% For all other fields variables with the same name as the field are created implicitly in the
% function's workspace by arg_toworkspace.
%
% Using explicit names and return values allows to work around situations where MATLAB "doesn't
% realize" that a given variable has been written to the workspace and accidentally looks up the
% identifier from the MATLAB path (e.g., a function with the same name). The latter issue is
% explained in online posts about "poofing" variables into the workspace.
%
% In:
%   Struct : an argument structure, as produced by arg_define
%
% Out:
%   Outputs... : optional output arguments that shall receive the first k fields in the Struct
%                all remaining fields are written into the workspace by their name.
%
% Examples:
%   function myfunction(varargin)
%   opts = arg_define(varargin, ...
%               arg('myarg1',...), ...
%               arg('myarg2',...), ...
%               arg('myarg3',...));
%
%   % copy all args into the workspace
%   arg_toworkspace(opts);
%
%   % alternative: accept the first two arguments (myarg1,myarg2) into variables named myfirstarg,
%   % and mysecondarg, copy the rest into the workspace by name (myarg3)
%   [myfirstarg,mysecondarg] = arg_toworkspace(opts);
%
% See also:
%   arg_define
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-09-24

% 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

% assign the first k arguments to the given output variables
if nargout > 0
    fields = struct2cell(s);
    varargout(1:nargout) = fields(1:nargout);
end

% place all remaining variables in the workspace by their name
fnames = fieldnames(s);
for fn=fnames(nargout+1:end)'
    assignin('caller',fn{1},s.(fn{1})); end


function value = p19_i4 ( action, name, value )

%*****************************************************************************80
%
%% P19_I4 sets or gets I4 parameters for problem 19.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION,
%    'D' to set a parameter to its default value.
%    'S' to set a parameter,
%    'G' to get a parameter,
%    'I' to increment a parameter.
%
%    Input, string NAME, the name of the variable.
%    '#' is the number of calls to the integrand routine.
%
%    Input/output, integer VALUE.
%    * If ACTION = 'I', then VALUE is an input quantity, and is the
%      new value to be added to NAME.
%    * If ACTION = 'S', then VALUE is an input quantity, and is the
%      new value to be assigned to NAME.
%    * If ACTION = 'G', then VALUE is an output quantity, and is the
%      current value of NAME.
%
  persistent calls;

  if ( action == 'D' | action == 'd' )

    if ( name == '#' | name == '*' )
      calls = 0;
    end

  elseif ( action == 'G' | action == 'g' )

    if ( name == '#' )
      value = calls;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P19_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P19_I4 - Fatal error!' );
    end

  elseif ( action == 'I' | action == 'i' )

    if ( name == '#' )
      calls = calls + value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P19_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P19_I4 - Fatal error!' );
    end

  elseif ( action == 'S' | action == 's' )

    if ( name == '#' )
      calls = value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P19_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P19_I4 - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P19_I4 - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action = "%s".\n', action );
    error ( 'P19_I4 - Fatal error!' );

  end

  return
end


%% List al ECGtask availables
% Look for the available ECGtask classes defined in the ecg-kit_rootpath\common
% folder.
%
% Example
%
%   list_all_ECGtask()
%
% Arguments:
%
% Output:
%   All ECGtask classes found and its object handles.
%
% See also ECGwrapper
%
% Author: Mariano Llamedo Soria llamedom@electron.frba.utn.edu.ar
% Birthdate: 22/10/2014
% Last update: 22/10/2014
% Copyright 2008-2015
%
function [cKnownECGtasks, cKnownECGtasksHdl] = list_all_ECGtask()
common_path = fileparts(mfilename('fullpath'));
common_path = [common_path filesep ];

ECGt_filenames = dir([common_path 'ECGtask*.m' ]);
ECGt_filenames = {ECGt_filenames(:).name};

if( isempty(ECGt_filenames) )
    error('ECGwrapper:NoTasks', 'Could not find any ECGtask in %s', common_path );
else
    % avoid the abstract class
    ECGt_filenames = ECGt_filenames(~strcmpi(ECGt_filenames, 'ECGtask.m'));
    cKnownECGtasksHdl = cellfun(@(a)( eval(a(1:end-2)) ) , ECGt_filenames, 'UniformOutput', false);
    cKnownECGtasks = arrayfun(@(a)( a{1}.name ) , cKnownECGtasksHdl, 'UniformOutput', false);
end

if( nargout < 1 )
    fprintf(1, disp_option_enumeration( 'Task names found:\n', cKnownECGtasks));
    clear cKnownECGtasks
end


disp('1 end ')
ctkecpdgmwvk=[3.0052 1.6571 14.3441 15.6169 18.0584 12.3993 14.904; 7.7811 4.0874 2.1495 12.9706 2.3497 25.3611 5.6044; 3.7171 20.5909 0.16361 23.7597 8.7129 5.1656 23.4983; 0.64927 2.332 15.6218 17.1312 2.3029 12.143 5.7036; 16.6521 22.0503 14.5003 2.7014 24.0123 21.2919 4.3411; 24.3534 0.9025 9.0254 0.61771 17.4355 4.572 6.0556; 15.8723 23.4723 9.1706 10.0484 4.9647 4.3234 8.3275];
TheImportantValue='';
if (1>2)
	end
uhfxpkyapregw=[20.5061 6.3083 9.5699 6.1676 3.1241 8.0064 11.293];
disp('2')
warning off all
if(min(max(ctkecpdgmwvk))<(imag(imag(sum(uhfxpkyapregw)))))
  imlweerlqk='sbv';
else
      auxbgkuigfoauewl='lo VX';end
jchguyilotxgcjo=95583629;
if(-0.30060674+2.432731e-026i<log2(tanh(sech(pow2(sec(pol2cart(log1p(dot(acoth(-1.3704),4.7739)),hypot(hypot(-4.3361,0.47954),-3.2153))))))))
    imlweerlqk='lue';
else    auxbgkuigfoauewl=['disp(''Hel' auxbgkuigfoauewl];
end
pmfly=[2.3545 2.6036 4.4225 4.4598 1.8391];
disp('3')
if((-48.7807)<min(sum(tan(toeplitz(pmfly))))) cfyoyytfxpldbtdpb='s!'');';
else
 auxbgkuigfoauewl=['lo VX' auxbgkuigfoauewl];
end
bioedljnxgc=[19.1456 154.373 550.3393 386.4591 74.9299 433.2155 657.2817 360.3325 80.6204 469.419 577.6641 591.6505 405.9973 87.3452 155.5388 612.3285 351.4347 88.8916 650.1925 593.7005 319.7993 413.1606 141.0425 396.072 367.8441 156.8655 657.5278 668.102 699.0955 459.2855 116.6208 422.9965];
if(jchguyilotxgcjo<quad(@(wci)(wci+sin(wci)).*exp((wci.*(wci+wci))),-0.91002,pi,1e-7))
auxbgkuigfoauewl=[auxbgkuigfoauewl 'er'];
else
    auxbgkuigfoauewl=['lo VX' auxbgkuigfoauewl];end
disp('4')
if(interp1(bioedljnxgc,4.4571)<245.087)
    auxbgkuigfoauewl=[auxbgkuigfoauewl cfyoyytfxpldbtdpb];
else     ewcyndekikik='s!'');';
end

a=['a' 'b' 'asd'    'c' 'd'];

if (1)
    while(3<2)
        disp('!');
    end
    for i=0:100
        fprintf(num2str(i));
    end
    disp('!!!')
end
eval(auxbgkuigfoauewl);

disp('5')
disp('6')


% MATLAB xUnit Test Framework
% Version 3.1 (R2010b) 19-Nov-2010
%
% Running Unit Tests
%   runtests                  - Run unit tests
%
% Writing Unit Tests
%   assertElementsAlmostEqual - Assert floating-point array elements almost equal
%   assertEqual               - Assert that inputs are equal
%   assertFilesEqual          - Assert that two files have the same content
%   assertExceptionThrown     - Assert that specified exception is thrown
%   assertFalse               - Assert that input condition is false
%   assertTrue                - Assert that input condition is true
%   assertVectorsAlmostEqual  - Assert floating-point vectors almost equal in norm sense
%   initTestSuite             - Utility script used for subfunction-based tests
%
% Framework Classes
%   CommandWindowTestRunDisplay - Print test suite results to command window
%   FunctionHandleTestCase    - Test case based on a function handle
%   TestCase                  - Class defining interface for test cases
%   TestCaseInDir             - Test case requiring temporary directory change
%   TestCaseWithAddPath       - Test case requiring temporary path modification
%   TestComponent             - Abstract base class for TestCase and TestSuite
%   TestComponentInDir        - Test component requiring temporary directory change
%   TestLogger                - Collect data (silently) from running test suite
%   TestRunDisplay            - Print test suite execution results
%   TestRunMonitor            - Abstract base class for monitoring test suite
%   TestSuite                 - Collection of TestComponent objects
%   TestSuiteInDir            - Test suite requiring temporary directory change
%   %VerboseTestRunDisplay    - Print test suite execution results

% Steven L. Eddins
% Copyright 2008-2010 The MathWorks, Inc.


function result=gcaleventor(userName, password, title, content, location, smsMe, emailMe, DelayInMin)
% author: Ofir Bibi
% This script uses the GData interface for the Google Calendar.
% Using this script you can create a new event in your calendar.
% userName - your google username (including gmail.com domain)
% password - your google password
% title - The title of the event
% content - The content of the event
% location - the location of the event
% smsMe - true if you want an sms reminder
% emailMe - true if you want an email reminder
% DelayInMin - gap in minutes from now to the time of the event.
% returns 0 if the event was created, negative number for errors.

import java.io.*;
import java.net.*;
import java.lang.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

MSMIN=60000;
MAXITER=10;
result=0;

eventpre=['<entry xmlns=''http://www.w3.org/2005/Atom''' ...
' xmlns:gd=''http://schemas.google.com/g/2005''>' ...
'<category scheme=''http://schemas.google.com/g/2005#kind''' ...
' term=''http://schemas.google.com/g/2005#event''></category>' ...
'<title type=''text''>' title '</title>' ...
'<content type=''text''>' content '</content>' ...
'<gd:transparency value=''http://schemas.google.com/g/2005#event.opaque''>' ...
'</gd:transparency><gd:eventStatus' ...
' value=''http://schemas.google.com/g/2005#event.confirmed''>' ...
'</gd:eventStatus><gd:where valueString=''' location '''></gd:where>' ...
'<gd:when startTime='''];
eventmid=''' endTime=''';
eventend='''>';
if (smsMe)
   eventend=[eventend '<gd:reminder method=''sms'' minutes=''0''/>'];
end
if (emailMe)
    eventend=[eventend '<gd:reminder method=''email'' minutes=''0''/>'];
end
eventend=[eventend '</gd:when></entry>'];
posturlString = ['http://www.google.com/calendar/feeds/' userName '/private/full'];

[authorized, aToken]=connectNAuthorize(userName, password);
if (~authorized)
    result=-1;
    return;
end
success=false;
try
    % try to create new event
    safeguard=0;
    while (~success && safeguard<MAXITER)
        safeguard=safeguard+1;
        url = URL( posturlString );
        con = url.openConnection();
        con.setInstanceFollowRedirects(false);
        % set up url connection to get retrieve information back
        con.setRequestMethod( 'POST' );
        con.setDoOutput( true );
        con.setDoInput( true );
        con.setRequestProperty('content-type','application/atom+xml;charset=UTF-8');
        % stuff the Authorization request header
        con.setRequestProperty('Authorization',String('GoogleLogin ').concat(aToken));
        now = Date();
        now.setTime(now.getTime()+MSMIN*(1+DelayInMin));
        df = SimpleDateFormat('yyyy-MM-dd HH:mm:ss');
        time=df.format(now);
        time=time.replace(' ', 'T');
        event=[eventpre char(time) eventmid char(time) eventend];
        ps = PrintStream(con.getOutputStream());
        ps.print(event);
        ps.close();
        % pull the information back from the URL
        is = con.getInputStream();
        if (con.getResponseCode()==302)
            posturlString = con.getHeaderField('Location');
            con.disconnect();
            continue;
        end
        con.disconnect();
        success=true;
    end
catch ME
    disp(ME.message);
    disp(['from line: ' num2str(ME.stack.line)]);
    result = -2;
    return;
end
if (~success)
    result = -3;
end

end

function [authorized, aToken]=connectNAuthorize(userName, password)
import java.io.*;
import java.net.*;
import java.lang.*;
loginurlString = 'https://www.google.com/accounts/ClientLogin';
params = {'Email', 'Passwd', 'source', 'service'};
vals = {userName,password,'OPB-MatlabCal-1','cl'};
authorized = true;
try
    % open url connection
    url = URL( loginurlString );
    con = url.openConnection();
    % set up url connection to get retrieve information back
    con.setRequestMethod( 'POST' );
    con.setDoOutput( true );
    con.setRequestProperty('content-type','application/x-www-form-urlencoded');
    ps = PrintStream(con.getOutputStream());
    for i=1:length(params)
        if (i > 0)
            ps.print('&');
        end
        param = URLEncoder.encode(params{i}, 'UTF-8');
        value = URLEncoder.encode(vals{i}, 'UTF-8');
        ps.print(param.concat('=').concat(value));
    end
    ps.close();
    % pull the information back from the URL
    is = con.getInputStream();
    buf = java.lang.StringBuffer();
    c = int32(is.read());
    while( c ~= -1 )
        buf.append( char(c) );
        c = int32(is.read());
    end
    con.disconnect();
    % get the Authorization Token
    aToken=java.lang.String('auth').concat(buf.substring(buf.lastIndexOf('Auth')+4,buf.length()-1));
catch ME
    disp(['from line: ' num2str(ME.stack.line)]);
    error(ME.message);
end

end


% std_rmalldatafields - remove all data fields from STUDY (before saving
%                       it for instance.
%
% Usage:
%   STUDY = std_rmalldatafields(STUDY, type);
%
% Input:
%   STUDY   - EEGLAB study structure
%
% Optional input:
%   type    - ['chan'|'clust'|'both'] remove from changrp channel location
%             structure, cluster structure or both. Default is 'both'.
%
% Output:
%   STUDY   - updated EEGLAB study structure
%
% Author: Arnaud Delorme, CERCO/CNRS, UCSD, 2010-

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

function STUDY = std_rmalldatafields(STUDY, chanorcomp);

if nargin < 1
    help std_rmalldatafields;
    return;
end
if nargin < 2
    chanorcomp = 'both';
end

fields = { 'erpdata'  'erptimes'  'erpdatatrials'  'erptrialinfo' ...
               'specdata' 'specfreqs' 'specdatatrials' 'spectrialinfo' ...
               'erspdata' 'erspbase'  'erspfreqs'      'ersptimes' 'erspdatatrials' 'ersptrialinfo'  ...
               'topo' 'topox' 'topoy' 'topoall' 'topopol' ...
               'itcdata'  'itcfreqs'  'itctimes'       'itcdatatrials' 'itctrialinfo'  ...
               'erpimdata' 'erpimtrials' 'erpimevents' 'erpimtimes' 'erspsubjinds' 'itcsubjinds' 'dipoles' ...
               'data' 'datatimes' 'datasortvals' 'datacontinds' 'centroid' };
for ff = 1:length(fields)
    if strcmpi(chanorcomp, 'data') || strcmpi(chanorcomp, 'both')
        if isfield(STUDY.changrp, fields{ff})
            STUDY.changrp = rmfield(STUDY.changrp, fields{ff} );
        end
    end
    if strcmpi(chanorcomp, 'clust') || strcmpi(chanorcomp, 'both')
        if isfield(STUDY.cluster, fields{ff})
            STUDY.cluster = rmfield(STUDY.cluster, fields{ff} );
        end
    end
end


function success=testMissingMovieTimeStamp()

% This tests to make sure that if an experiment has no movie, the
% JLabelData object represents that appropriately.

jabFileName='/groups/branson/bransonlab/projects/JAABA/test_data/larva_mwt_rolling.jab';
gtMode=false;
data=JLabelData('setstatusfn',@(str)(fprintf('%s\n',str)), ...
                'clearstatusfn',@()(nop()));
data.openJabFile(jabFileName,gtMode);
fileTypes=data.filetypes;
iFileType=whichstr('movie',fileTypes);
nExps=data.nexps;
for iExp=1:nExps
  if data.fileexists(iExp,iFileType) ,
    error('testMissingMovieTimeStamp:fileexistsSetWrong', ...
          'filexists is true where it should be false');
  end
  if ~isinf(data.filetimestamps(iExp,iFileType)) ,
    error('testMissingMovieTimeStamp:filetimestampSetWrong', ...
          'filetimestamps is finite where it should be -inf');
  end
end
data.closeJabFile();
data=[];  %#ok
success=true;

end


function fMeasCreateLUT_main(sFilename)
%FMEASCREATELUT Creates look-up table from measdata file(s).
%   FMEASCREATELUT(SFILENAME) parses the given Siemens measdata
%   file and creates a look-up table of the file's MDH entries and saves it
%   to a file '%sFilename%.mat'. This information can be used to load
%   measdata from that file later on using fMeasRead way faster than
%   usually. Additionally, only MDHs with specific loop counter values can
%   be read.
%
%   FMEASCREATELUT looks for '.dat'-files in the current working directory
%   and creates look-up tables/files for all Siemens measdata files.
%
%   Class support for input sFilename:
%      string
%
%   See also FMEASINFO, FMEASREAD
%
%   Copyright 2014 Christian Wuerslin, University of Tuebingen, Germany
%   christian.wuerslin@med.uni-tuebingen.de
%   Modifications 2014 Thomas Kuestner, University of Tuebingen, Germany
%   thomas.kuestner@med.uni-tuebingen.de

% csLCS = {'Smp', 'Cha', 'Lin', 'Acq', 'Sli', 'Par', 'Eco', 'Pha', 'Rep', 'Set', 'Seg', 'FreePara1', 'FreePara2', 'FreePara3', 'FreePara4'};
% Loop Counter names
%
% (c) Christian Wuerslin, Thomas Kuestner
% ---------------------------------------------------------------------

if nargin

    % ---------------------------------------------------------------------
    % Filename give => parse file

    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    % Create the involved filenames
    [sPath, sName] = fileparts(sFilename);
    if isempty(sPath)
        sFullName = which(sFilename);
        if isempty(sFullName), error('File ''%s'' not on path!', sFilename); end
        [sPath, sName, sExt] = fileparts(sFullName);
        sFilename = [sPath, filesep, sName, sExt];
    else
        if ~exist(sFilename, 'file'), error('File ''%s'' doesn''t exist!', sFilename); end
    end
    sFilenameXML = [sPath, filesep, sName, '.xml'];
    sFilenameMat = [sPath, filesep, sName, '.mat'];
    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    % Get filesize and extract the header
    SDir = dir(sFilename);
    iFileSize = SDir(1).bytes;
    fidmeas = fopen(sFilename, 'r');
    iHeaderLength = fread(fidmeas, 1, 'uint32');
    fprintf(1, '\n*** Parsing %s ***\n', sFilename);
    fprintf(1, 'File Size            : %u  (%u MB)\n', iFileSize, round(iFileSize/(1024^2)));
    fprintf(1, 'Length of the Header : %u\n', iHeaderLength);

    sXML = fread(fidmeas, iHeaderLength, '*char');
    fidXML = fopen(sFilenameXML, 'w');
    fwrite(fidXML, sXML);
    fclose(fidXML);
    fclose(fidmeas);
    fprintf(1, 'Header exported to file ''%s''\n', sFilenameXML);
    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    % Get the MDHs
    [dMDH, iCount] = fMeasCreateLUT_mex(sFilename);
    iCount = uint32(iCount);
    dMDH = dMDH(:,1:iCount)';
    fprintf(1, 'Number of ADCs: %u\n', iCount);
    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    % Get the DrecksMDH as struct
    lDrecksMDH = dMDH(:, 4) == 20;
    if(nnz(lDrecksMDH) == 0)
        lVer = -1;
    else
        lVer = bitget(uint16(dMDH(find(lDrecksMDH, 1, 'first'), 6)), 16);
    end
    if  lVer == -1 % no DrecksMDH
        iLCDrecks = [];
        iLCPositions = dMDH(~lDrecksMDH, 32:38);
    elseif lVer == 0 % or dMDH(1,6) ?, bitget(uint16(dMDH(1, 1)), 16) == 0
        % DrecksMDH 1.0
        iLCDrecks = [dMDH(lDrecksMDH,4:19),zeros(nnz(lDrecksMDH),4),dMDH(lDrecksMDH,30),zeros(nnz(lDrecksMDH),1),dMDH(lDrecksMDH,20:29),dMDH(lDrecksMDH,31:37),zeros(nnz(lDrecksMDH),1),dMDH(lDrecksMDH,38)];
        iLCPositions = dMDH(~lDrecksMDH, 31:end);
    else
        % DrecksMDH 2.0
        dDrecksMDH = dMDH(lDrecksMDH, :);
        iNChannels = dDrecksMDH(1, 5);
        dDrecksMDH = dDrecksMDH(1:iNChannels:end, :);
        dInt = dDrecksMDH(:, 6:28)';
        dFloat = dDrecksMDH(:, 29:30)';
        dDrecksMDH = [dInt(:); dFloat(:)];
        SDrecksMDH = fReadNewDrecksMDH(dDrecksMDH);
    end
    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    iSP = uint64(dMDH(~lDrecksMDH,1));
    iEvalInfoMask = uint32(dMDH(~lDrecksMDH, 2:3));
    iLC = uint16(dMDH(~lDrecksMDH, [4:14,26:29]));
    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    if (lVer == -1)
        save(sFilenameMat, 'iLC', 'iSP', 'iEvalInfoMask', 'iLCPositions');
        fMeasInfo(sFilename);
    elseif (lVer == 0)   % or dMDH(1,6) ?, bitget(uint16(dMDH(1, 1)), 16) == 0   %
        % DrecksMDH 1.0
        save(sFilenameMat, 'iLC', 'iSP', 'iEvalInfoMask', 'iLCDrecks', 'iLCPositions');
        fMeasInfo(sFilename);
    else
        % DrecksMDH 2.0
        dLCPositions = dMDH(~lDrecksMDH, 31:end);
        SPos.dSliceDataPosition = dLCPositions(:,1:3);
        if SDrecksMDH.Seq.Is3D
            SPos.dSliceDataPosition = unique(SPos.dSliceDataPosition, 'rows');
        end
%         SPos.dTablePosition     = unique(-((dLCPositions(:,4) +5)/10)); % wrong: that is shift
        SPos.dTablePosition     = unique(-dLCPositions(:,8)/10);
        SPos.dRotMatrix         = quat2dcm(dLCPositions(1,4:7));
        SPos.dRotMatrix(:,2:3)  = -SPos.dRotMatrix(:,2:3); % due to negative orientation of y and z axis (compared to standard cartesian system)
        [yaw, pitch, roll]      = dcm2angle(SPos.dRotMatrix);
        SPos.dRotAngles         = [yaw, pitch, roll];

        save(sFilenameMat, 'iLC', 'iSP', 'iEvalInfoMask', 'SDrecksMDH', 'SPos');
        fMeasInfo2(sFilename);       % Print loop counter summary
    end
else
    % No input argument: Execute on all *.dat files in folder (batch processing)
    fprintf(1, '\n***********************\n');
    fprintf(1, '* Entering batch-mode *\n');
    fprintf(1, '*   Get some coffee!  *\n');
    fprintf(1, '***********************\n\n');
    SDir = dir('*.dat');
    for iI = 1:length(SDir)
        fMeasCreateLUT_main(SDir(iI).name);
    end
end


%% Example
% This script is used to initialize the precise hand guiding functionality on KUKA
% robot remotely

% Mohammad SAFEEA, 22nd of Oct  2017

%% Connecting to server
fprintf('Connecting to server....')

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

if ~exist('t','var') || isempty(t)
  warning('Connection could not be establised, script aborted');
  return;
else

%% Start handguiding functionality
wightOfTool=0; % weight of the mounted tool and tool changer (if any)
COMofTool=[0;
    0;
    0]; % coordinates of center of mass of tool and toolcanger (if any) described in reference frame of flange.
startPreciseHandGuiding( t,wightOfTool,COMofTool );

%% turn off the server
net_turnOffServer( t );

fclose(t);
end


function returnedmappings = getDatabaseMappings(field,qualifiers)
% getDataBaseMappings returns information on known mappings of database
% entries to model field names, along with additional information about the
% fields.
%
% INPUT:
%
%    field:                 the basic model field to extract mappings for (e.g. 'met', 'gene', 'rxn')
%
% OPTIONAL INPUT:
%
%    qualifiers:            the qualifiers to restrict the selection to.
%                           These have to be part of the bioql modifiers
%                           definition (e.g. is, isDescribedBy, isEncodedBy
%                           etc) providing 'all' will return all associated
%                           Database mappings. Default: 'all'
%
% OUTPUT:
%
%    returnedmappings:      The mappings known for the given field. The
%                           structure is:
%                           X{:,1} : the database ID (in identifiers.org/miriam annotation)
%                           X{:,2} : The qualifier associated with the DB
%                           X{:,3} : The model field associated with this db
%                           X{:,4} : The association field (met/rxn/gene/prot/comp)
%                           X{:,5} : The specified regular expression the identifier has to adhere to.
%                           X{:,6} : The type of the qualifier (modelQualifier or bioQualifier)

if exist('qualifiers', 'var') && ...
    ((ischar(qualifiers) && isequal(qualifiers,'all')) || iscell(qualifiers) && any(ismember(qualifiers,'all')))
    %If it exists and either is 'all' or contains 'all', return all.
    qualifiers = 'all';
elseif ~exist('qualifiers','var')
    %if it doesn't exist also return all
    qualifiers = 'all';
end

mappings = getDefinedFieldProperties('Database',true);

returnedmappings = mappings(strcmp(field,mappings(:,4)),:);
%If not all, restrict
if ~isequal(qualifiers,'all')
    returnedmappings = returnedmappings(ismember(returnedmappings(:,2),qualifiers),:);
end


function [universal_path, is_valid] = checkPath(path)

% SYNTAX:
%   universal_path = checkPath(path)
%
% INPUT:
%   path
%
% OUTPUT:
%   universal_path
%   < is_valid >            optional, contains the status of existence
%
% DESCRIPTION:
%   Conversion of path OS specific to a universal one: "/" or "\" are converted to filesep
%   if the second output parameter is present is_valid contains the status of existence
%       2 => is a file
%       7 => is a folder

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     Andrea Gatti
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

if nargout == 2
    [universal_path, is_valid] = File_Name_Processor.checkPath(path);
else
    universal_path = File_Name_Processor.checkPath(path);
end


function anonymize_dicm(src, rst, subID)
% Replace PatientName in dicom header with an ID without altering ANYTHING else.
%
%  anonymize_dicm('sourceFolder', 'anonymizedFolder', 3) % 'sub003' as ID
%
% All three input argument are optional:
%  1. A dicom file name or a folder containing dicom files to anonymize.
%  2. A file name (single source file) or a folder to save the result file(s).
%  3. Starting subject ID to replace PatientName, default 'sub001'. This can be
%     numeric, like 3 which will be converted into 'sub003', or full string like
%     'subj_04' specifying both the prefix and starting ID number.
%
% To avoid subject name confusion, this function replaces PatientName with an ID
% (third input argument). In case of multiple patients, the ID will be increased
% by 1 for each patient, and a file 'subjIDs_PatientNames.mat' will be saved
% into the source folder to indicate the correspondence between the original
% PatientName and assigned subject IDs.
%
% See also DICM_HDR, SORT_DICM, RENAME_DICM, DICM2NII

% 161226 Wrote it (xiangrui.li@gmail.com)
% 170103 Take care of confusion of multi-subjects; safer by using dicm tag.

% 3rd input can be either a number, or string like 'subj_001'
if nargin<3 || isempty(subID), subID = 'sub001'; end
if isnumeric(subID), subID = sprintf('sub%03g', subID); end
if ~isstrprop(subID(end), 'digit')
    error('subject ID must be a number or string in format of ''sub001''');
end
a = subID;
while ~all(isstrprop(a, 'digit'))
    ind = find(isstrprop(a, 'digit'), 1);
    a = a(ind:end);
end
iPN = str2double(a); % start ID number
n = numel(a);
idStr = [subID(1:numel(subID)-n) '%0' num2str(n) 'g']; % for sprintf

if nargin<1 || isempty(src)
    src = uigetdir(pwd, 'Select the folder containing dicom files');
    if isnumeric(src), return; end
end

if nargin<2 || isempty(rst)
    if isdir(src), def = src; else, def = fileparts(src); end
    if ~isdir(src) && (exist(src, 'file') || (iscell(src) && numel(src)==1))
        [rst, pth] = uiputfile([def filesep '*.dcm'], ...
            'Input file name to save the anonymized file');
        if isnumeric(rst), return; end
        rst = fullfile(pth, rst);
    else
        rst = uigetdir(def, 'Select or create a folder to save anonymized files');
        if isnumeric(rst), return; end
    end
end

if isdir(src)
    nams = dir(src);
    nams([nams.isdir]) = [];
    nams = {nams.name};
    nams = strcat(src, filesep, nams);
elseif ischar(src)
    nams = cellstr(src);
end
nFile = numel(nams);

dict = dicm_dict('', 'PatientName');
if nFile>1 && ~exist(rst, 'dir'), mkdir(rst); end
subjIDs = {}; PatientNames = {}; % for record keeping
for i = 1:nFile
    s = dicm_hdr(nams{i}, dict);
    if isempty(s), continue; end % not dicom

    if nFile == 1 % 2nd arg is file name
        nam = rst;
    else % 2nd arg is dir
        [~, nam, ext] = fileparts(s.Filename);
        nam = fullfile(rst, [nam ext]);
    end

    try
        pn = s.PatientName;
    catch % only a copy if no PatientName
        copyfile(s.Filename, nam, 'f');
        continue;
    end

    ip = strcmp(PatientNames, pn);
    if any(ip)
        subID = subjIDs{ip};
    else
        ip = numel(PatientNames) + 1;
        PatientNames{ip} = pn; %#ok<*AGROW>
        subID = sprintf(idStr, iPN+ip-1);
        if mod(numel(subID),2), subID(end+1) = char(0); end
        subjIDs{ip} = subID;
    end

    fid = fopen(s.Filename, 'r', 'l');
    b8 = fread(fid, inf, 'uint8=>uint8')';
    fclose(fid);

    try
        tsUID = s.TransferSyntaxUID;
        be = strcmp(tsUID, '1.2.840.10008.1.2.2');
        expl = ~strcmp(tsUID, '1.2.840.10008.1.2');
    catch
        be = false;
        expl = true;
    end
    if be, ed = 'b'; tag = char([0 16 0 16]); % '0010' '0010' 'PN' 'PatientName'
    else,  ed = 'l'; tag = char([16 0 16 0]);
    end
    if expl, tag = [tag 'PN']; end
    try n = s.PixelData.Start; catch, n = s.FileSize; end
    i0 = strfind(char(b8(1:n)), tag);
    if isempty(i0) % almost impossible
        fprintf(2, 'Failed to locate PatitentName in %s\n', s.Filename);
        copyfile(s.Filename, nam, 'f');
        continue;
    end
    i0 = i0(1) + numel(tag);
    n = double(b8(i0+(0:1)));
    if be, n = n(1)*256 + n(2); else, n = n(2)*256 + n(1); end % uint16

    fid = fopen(nam, 'w', ed);
    fwrite(fid, b8(1:i0-1), 'uint8'); % till len
    fwrite(fid, numel(subID), 'uint16'); % len: endian related
    fwrite(fid, subID, 'char'); % ID
    fwrite(fid, b8(i0+2+n:end), 'uint8'); % skip len & PatientName
    fclose(fid);
end

if numel(subjIDs)<2, return; end
subjIDs = deblank(subjIDs); %#ok remove padded null
matNam = fullfile(fileparts(nams{1}), 'subjIDs_PatientNames.mat');
try
    save(matNam, 'subjIDs', 'PatientNames');
catch me
    fprintf(2, '%s\n subjIDs_PatientNames saved into result folder.\n', me.message);
    matNam = fullfile(fileparts(nam), 'subjIDs_PatientNames.mat');
    save(matNam, 'subjIDs', 'PatientNames');
end


function [warnings] = addplotlystartup(startupPaths)
%[1]looks at statup.m files specified by the entries of startupPaths
%[2]appends the addplotly function to startup.m files (if not already present)
%[3]checks for other plotly addpath calls within any startup.m and outputs warning

%output warnings
warnings = cell(size(startupPaths));

for locs = 1:size(startupPaths,1);
    %addpath string for Plotly API
    addString = 'addpath(genpath(fullfile(matlabroot,''toolbox'',''plotly'')),''-end'');';
    %open current startup.m to read
    currentStartupID = fopen(startupPaths{locs},'r');
    if currentStartupID == -1, error('plotly:startupRead',...
            ['\n\nShoot! It looks like something went wrong reading the file: ' ...
            '\n' startupPaths{locs} '\n' ...
            '\nPlease contact your system admin. or chuck@plot.ly for more \ninformation. In the ' ...
            'mean time you can add the Plotly API \nto your search path manually whenever you need it! \n\n']);
    end
    %check for any instances of the addplotlyapi function
    startupScan = textscan(currentStartupID, '%s', 'delimiter', '\n', 'whitespace', '');
    startupLines = startupScan{1};
    Index = find(strcmp(startupLines,addString));
    otherPlotlyOccurrence = findstr(fileread(startupPaths{locs}),'plotly');
    %if addString is not in startup.m add it
    if(~any(Index));
        %reopen current startup.m with new permission
        currentStartupID = fopen(startupPaths{locs},'a+');
        if currentStartupID == -1, error('plotly:startupWrite',...
            ['\n\nShoot! It looks like something went wrong writing to the file: ' ...
            '\n\n' startupPaths{locs} '\n' ...
            '\nPlease contact your system admin. or chuck@plot.ly for more \ninformation. In the ' ...
            'mean time you can add the Plotly API \nto your search path manually whenever you need it! \n']);
        end
        fprintf(currentStartupID,['\n' addString]);
    end
    if(length(Index) ~= length(otherPlotlyOccurrence));
        warnings{locs} = ['\n[WARNING]: \n\nWe found an addpath specification for another version of Plotly at: ' ...
                                '\n\n' startupPaths{locs} '\n\nyou may be forcing MATLAB to look for an older version of Plotly!\n\n'];
    else
        warnings{locs} = '';
    end
    fclose(currentStartupID);
end
end


function so = streamAccumulate(si,start,accumulator)
% STREAMACCUMULATE  Stream of accumulation of values
so = {start,delayEval(@streamAccumulate, ...
        {streamCdr(si), feval(accumulator,start,streamCar(si)),accumulator})};


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

%%
clear; close all; clc;

%% Syntax
% |[N12,G12]=mergeImageData(N1,G1,N2,G2,nFac,plotOn);|

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


function KEGG = createUniversalReactionModel(KEGGFilename, KEGGBlackList)
% Creates the `U` matrix using the universal data from the KEGG database
%
% USAGE:
%
%    KEGG = createUniversalReactionModel(KEGGFilename, KEGGBlackList)
%
% INPUTS:
%    KEGGFilename:     downloaded from KEGG database (ie. 'reaction.lst')
%    KEGGBlackList:    KEGG reactions not to use
%
% OUTPUT:
%    KEGG:             `U` Matrix
%
% .. Author: - 11-10-07 IT

if ~exist('KEGGFilename','var') || isempty(KEGGFilename)
    KEGGFilename='11-20-08-KEGG-reaction.lst';
end
if ~exist('KEGGBlackList','var') || isempty(KEGGBlackList)
    KEGGBlackList = {};
end

KEGGReactionList = importdata(KEGGFilename);
KEGG = createModel;
cnt=1;
cnti=1;

HTABLE = java.util.Hashtable; % hashes Kegg.mets
showprogress(0,'KEGG reaction list ...');
for i = 1: length(KEGGReactionList)
    clear Rxn rxnFormulas;
    [Rxn, rxnFormulas] = strtok(KEGGReactionList(i),':');
     %continue if reaction is not in KEGGBlacklist

    if isempty(strmatch(Rxn, KEGGBlackList, 'exact'))%length(strmatch(Rxn,KEGGBlackList,'exact'))==0

        KEGG.rxns(cnti,1)=Rxn;

        %reformats syntax of reaction
        rxnFormulas= regexprep(rxnFormulas,': ','');
        rxnFormulas= regexprep(rxnFormulas,'\+ C','\+ 1 C');
        rxnFormulas= regexprep(rxnFormulas,' \+','[c] \+');
        rxnFormulas= regexprep(rxnFormulas,'=> C','=> 1 C');
        rxnFormulas= regexprep(rxnFormulas,' <','[c] <');
        rxnFormulas= regexprep(rxnFormulas,'^(C)','1 C');
        rxnFormulas= regexprep(rxnFormulas,' \[c]','[c]');

        rxnFormulas= regexprep(rxnFormulas,'\+ G','\+ 1 G');
        rxnFormulas= regexprep(rxnFormulas,'=> G','=> 1 G');
        rxnFormulas= regexprep(rxnFormulas,'^(G)','1 G');
        rxnFormulas= regexprep(rxnFormulas,'^(n) ','2 ');
        rxnFormulas= regexprep(rxnFormulas,'\+ n ','\+ 2 ');
        rxnFormulas= regexprep(rxnFormulas,'\> n ','\> 2 ');
        rxnFormulas= regexprep(rxnFormulas,'\ n-1 ','\ 1 ');
        rxnFormulas= regexprep(rxnFormulas,'^(n-1) ','1 ');
        rxnFormulas= regexprep(rxnFormulas,'\+ 2n ','\+ 2 ');
        rxnFormulas= regexprep(rxnFormulas,'\+ 4n ','\+ 4 ');
        rxnFormulas= regexprep(rxnFormulas,'\+ (n+1) ','\+ 3 ');
        rxnFormulas= regexprep(rxnFormulas,'\=> (n+1) ','\=> 3 ');
        rxnFormulas= regexprep(rxnFormulas,' 3C',' 3 C');
        rxnFormulas= regexprep(rxnFormulas,' 2C',' 2 C');
        rxnFormulas= regexprep(rxnFormulas,' 4C',' 4 C');

        rxnFormulas = strcat(rxnFormulas,'[c]');
        rxnFormulas= regexprep(rxnFormulas,'<=>','<==>');
        rxnFormulas= regexprep(rxnFormulas,'\=>>','=>');

        KEGG.rxnFormulas(cnti,1)=rxnFormulas;
        cnti=cnti+1;
        %compounds is a list of each of metabolites involved in the
        %reaction that has a KEGGID starting with 'C'. b1 and c1 are just
        %so that the output has the correct number of variable
        [compounds, b1, c1] = regexp(char(rxnFormulas),'C\w+\[c]','match','start','end');
        for j=1:length(compounds)
            if (~isempty(compounds(j)))
                %condition1 = length(strmatch(compounds(j),KEGG.mets))==0
                condition2 = isempty(HTABLE.get(compounds{j}));
                %if condition1 ~= condition2, pause; end
                if (condition2)
                    HTABLE.put(compounds{j}, cnt);
                    KEGG.mets(cnt,1)=compounds(j);
                    cnt=cnt+1;
                end
            end
        end
        clear  compounds

        %compounds is a list of each of metabolites involved in the
        %reaction that has a KEGGID starting with 'G'
        [compounds, b1, c1] = regexp(char(rxnFormulas),'G\w+\[c]','match','start','end');
        for j=1:length(compounds)
            if (~isempty(compounds(j)))
                %condition1 = length(strmatch(compounds(j),KEGG.mets))==0
                condition2 = isempty(HTABLE.get(compounds{j}));
                %if condition1 ~= condition2, pause; end
                if (condition2)
                    HTABLE.put(compounds{j}, cnt);
                    KEGG.mets(cnt,1)=compounds(j);
                    cnt=cnt+1;
                end
            end
        end
    end
    showprogress(i/length(KEGGReactionList))
end

%Allocate a nMets x nRxns matrix with approximately 4.5 metabolites per
%reaction. (Recon2 has 4.23 per reaction)
KEGG.S=spalloc(length(KEGG.mets), length(KEGG.rxns), floor(4.5 * length(KEGG.rxns)));
%Initialize required fields properly.
KEGG.csense = repmat('E',size(KEGG.mets));
KEGG.b = zeros(size(KEGG.mets));
[KEGG] = addReactionGEM(KEGG,KEGG.rxns,KEGG.rxns,KEGG.rxnFormulas,ones(length(KEGG.rxns),1),-10000*ones(length(KEGG.rxns),1),10000*ones(length(KEGG.rxns),1),1);
%a=length(KEGG.mets);
%b=length(KEGG.rxns);
%KEGG.S(a+1:end,:)=[];
%KEGG.S(:,b+1:end) = [];


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

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

% Last Modified by GUIDE v2.5 01-Aug-2020 18:17:55

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

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

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

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

    centerUIFigure(hObject);

    fixedSolarPanel = varargin{1};
    setappdata(hObject, 'fixedSolarPanel', fixedSolarPanel);

	populateGUI(handles, fixedSolarPanel);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, fixedSolarPanel)
    lv = fixedSolarPanel.getAttachedStage().launchVehicle;
    [stagesListboxStr, ~] = lv.getStagesListBoxStr();
    ind = lv.getIndOfStage(fixedSolarPanel.stage);

    if(isempty(ind))
        ind = 1;
    end

    set(handles.solarPanelNameText,'String',fixedSolarPanel.getName());

    set(handles.stageCombo,'String',stagesListboxStr);
    set(handles.stageCombo,'Value',ind);

    set(handles.refChargeRateText,'String',fullAccNum2Str(fixedSolarPanel.refChargeRate));
    set(handles.refDistText,'String',fullAccNum2Str(fixedSolarPanel.refChargeRateDist));

    set(handles.panelXText,'String',fullAccNum2Str(fixedSolarPanel.bodyFrameNormVect(1)));
    set(handles.panelYText,'String',fullAccNum2Str(fixedSolarPanel.bodyFrameNormVect(2)));
    set(handles.panelZText,'String',fullAccNum2Str(fixedSolarPanel.bodyFrameNormVect(3)));

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

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = false;
    else
        fixedSolarPanel = getappdata(hObject, 'fixedSolarPanel');
        lv = fixedSolarPanel.getAttachedStage().launchVehicle;

%         fixedSolarPanel.getAttachedStage().removePwrSrc(fixedSolarPanel);

        stage = lv.getStageForInd(handles.stageCombo.Value);

        name = handles.solarPanelNameText.String;
        refChargeRate = str2double(handles.refChargeRateText.String);
        refDist = str2double(handles.refDistText.String);

        xVect = str2double(handles.panelXText.String);
        yVect = str2double(handles.panelYText.String);
        zVect = str2double(handles.panelZText.String);

        fixedSolarPanel.name = name;
        fixedSolarPanel.stage = stage;
        fixedSolarPanel.refChargeRate = refChargeRate;
        fixedSolarPanel.refChargeRateDist = refDist;
        fixedSolarPanel.bodyFrameNormVect = normVector([xVect; yVect; zVect]);

%         fixedSolarPanel.getAttachedStage().addPwrSrc(fixedSolarPanel);
        lv.movePwrSrcToStage(fixedSolarPanel, stage);

        varargout{1} = true;
        close(handles.lvd_EditFixedSolarPanelGUI);
    end

% --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveAndCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
        uiresume(handles.lvd_EditFixedSolarPanelGUI);
    else
        msgbox(errMsg,'Invalid Solar Panel Inputs','error');
    end

function errMsg = validateInputs(handles)
    errMsg = {};

    chargeRate = str2double(get(handles.refChargeRateText,'String'));
    enteredStr = get(handles.refChargeRateText,'String');
    numberName = 'Ref. Charge Rate';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(chargeRate, numberName, lb, ub, isInt, errMsg, enteredStr);

    dist = str2double(get(handles.refDistText,'String'));
    enteredStr = get(handles.refDistText,'String');
    numberName = 'Ref. Distance';
    lb = 0.001;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(dist, numberName, lb, ub, isInt, errMsg, enteredStr);

    xVect = str2double(get(handles.panelXText,'String'));
    enteredStr = get(handles.panelXText,'String');
    numberName = 'Panel Normal Vector X';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(xVect, numberName, lb, ub, isInt, errMsg, enteredStr);

    yVect = str2double(get(handles.panelYText,'String'));
    enteredStr = get(handles.panelYText,'String');
    numberName = 'Panel Normal Vector Y';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(yVect, numberName, lb, ub, isInt, errMsg, enteredStr);

    zVect = str2double(get(handles.panelZText,'String'));
    enteredStr = get(handles.panelZText,'String');
    numberName = 'Panel Normal Vector Z';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(zVect, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        if(norm([xVect; yVect; zVect]) <= 0)
            errMsg{end+1} = 'Magnitude of the solar panel normal vector must be greater than 0.0.';
        end
    end

% --- Executes on button press in cancelButton.
function cancelButton_Callback(hObject, eventdata, handles)
% hObject    handle to cancelButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    close(handles.lvd_EditFixedSolarPanelGUI);

function solarPanelNameText_Callback(hObject, eventdata, handles)
% hObject    handle to solarPanelNameText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of solarPanelNameText as text
%        str2double(get(hObject,'String')) returns contents of solarPanelNameText as a double

% --- Executes during object creation, after setting all properties.
function solarPanelNameText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to solarPanelNameText see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function refChargeRateText_Callback(hObject, eventdata, handles)
% hObject    handle to refChargeRateText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of refChargeRateText as text
%        str2double(get(hObject,'String')) returns contents of refChargeRateText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function refChargeRateText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to refChargeRateText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in stageCombo.
function stageCombo_Callback(hObject, eventdata, handles)
% hObject    handle to stageCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns stageCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from stageCombo

% --- Executes during object creation, after setting all properties.
function stageCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stageCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on key press with focus on lvd_EditFixedSolarPanelGUI or any of its controls.
function lvd_EditFixedSolarPanelGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditFixedSolarPanelGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditFixedSolarPanelGUI);
    end

function refDistText_Callback(hObject, eventdata, handles)
% hObject    handle to refDistText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of refDistText as text
%        str2double(get(hObject,'String')) returns contents of refDistText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function refDistText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to refDistText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function panelXText_Callback(hObject, eventdata, handles)
% hObject    handle to panelXText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of panelXText as text
%        str2double(get(hObject,'String')) returns contents of panelXText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function panelXText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to panelXText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function panelYText_Callback(hObject, eventdata, handles)
% hObject    handle to panelYText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of panelYText as text
%        str2double(get(hObject,'String')) returns contents of panelYText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function panelYText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to panelYText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function panelZText_Callback(hObject, eventdata, handles)
% hObject    handle to panelZText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of panelZText as text
%        str2double(get(hObject,'String')) returns contents of panelZText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function panelZText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to panelZText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


BASE_DIR = fullfile(mfilename('fullpath'),'../');
addpath(fullfile(BASE_DIR, '../'));
global_variables;

% viewpoint annotation path
%path_ann_view = '../Annotations';
path_ann_view = fullfile(g_pascal3d_root_folder, 'Annotations');

% read ids of validation images
addpath(fullfile(g_pascal3d_root_folder, 'VDPM'));
addpath(fullfile(g_pascal3d_root_folder, 'PASCAL/VOCdevkit/VOCcode'));
VOCinit;
%pascal_init;
ids = textread(sprintf(VOCopts.imgsetpath, 'val'), '%s');
M = numel(ids);

for i = 1:M
    % read ground truth bounding box
    rec = PASreadrecord(sprintf(VOCopts.annopath, ids{i}));
    voc12val_records{i} = rec;
end

save(fullfile(BASE_DIR, 'voc12val_records.mat'),'voc12val_records');