function val = readStringFromFID(FID, string)

% READSTRINGFROMFID Read an boolean from an FID.
% FORMAT
% DESC reads a string from a stream.
% ARG FID : stream to read from.
% ARG name : name of string.
% RETURN val : value of variable in file.
%
% SEEALSO : writeStringToFID, readIntFromFID, readBoolFromFID, readDoubleFromFID
%
% COPYRIGHT : Neil D. Lawrence, 2008

% NDLUTIL

lineStr = getline(FID);
tokens = tokenise(lineStr, '=');
if(length(tokens)~=2 | ~strcmp(tokens{1}, string))
  error('Incorrect file format.')
end
val = tokens{2};


 function ir_colorbar_text(str)
%function ir_colorbar_text(str)
%|
%| Add a colorbar and label it with string str.
%|
%| Needed as of octave 3.8.2 and matlab R2014b because they have incompatible
%| graphics support for colorbars.

if nargin < 1, ir_usage, end
if nargin == 1 && streq(str, 'test'), ir_colorbar_text_test, return, end

if ~im, return, end

h = colorbar;
if ir_is_octave
	subplot(h); ylabel(str)
else
	h.Label.String = str;
end

function ir_colorbar_text_test
im clf
im(eye(8))
ir_colorbar_text('test1')


function [OutputError] = PIVlab_capture_basler_save(basler_vid,nr_of_images,ImagePath,frame_nr_display)

hgui=getappdata(0,'hgui');

OutputError=0;

basler_frames_to_capture = nr_of_images*2;

if getappdata(hgui,'cancel_capture') ~=1 %capture was not cancelled --> save images from RAM to disk
	basler_data = getdata(basler_vid,basler_frames_to_capture); %ruft alle Frames in RAM ab. Frame 1,2,3 sind müll
	cntr=0;
	for image_save_number=1:2:size(basler_data,4)
		imgA_path=fullfile(ImagePath,['PIVlab_' sprintf('%4.4d',cntr) '_A.tif']);
		imgB_path=fullfile(ImagePath,['PIVlab_' sprintf('%4.4d',cntr) '_B.tif']);
		imwrite(basler_data(:,:,:,image_save_number),imgA_path,'compression','none'); %tif file saving seems to be the fastest method for saving data...
		imwrite(basler_data(:,:,:,image_save_number+1),imgB_path,'compression','none');
		cntr=cntr+1;
		set(frame_nr_display,'String',['Saving images to disk: Image pair ' num2str(cntr) ' of ' num2str(size(basler_data,4)/2)]);
		drawnow limitrate;
	end
end


classdef prtUiListDlg < prtUiManagerPanel

    % clear classes
    % close all
    % strs = {'asdf', 'qwer','poiu','lkhj'};
    % obj = prtUiListDlg(strs);
    %
    % if isempty(obj.enteredSelection)
    %     disp('Nothin');
    % else
    %     disp(strs{obj.enteredSelection});
    % end

    properties
        inputStruct
        tableFieldNames = {};
        dataCell = {};

        enteredSelection = [];

        windowSize = [500 300];
        textFontSize = 25;
        tableFontSize = 20;

        titleStr = '';
        messageStr = '
Make A Choice
';

        cancelStr = 'Cancel';
        okStr = 'OK';

        enableMultiSelect = false;

        handleStruct
    end

    properties (SetAccess = 'protected')
        madeThisWindow = false;
    end

    methods
        function self = prtUiListDlg(varargin)

            if nargin == 1
                self.inputStruct = varargin{1};
            elseif ~mod(nargin,2)
                self = prtUtilAssignStringValuePairs(self,varargin{:});
            else
                self.inputStruct = varargin{1};
                self = prtUtilAssignStringValuePairs(self,varargin{2:end});
            end

            if nargin~=0 && ~self.hgIsValid
               self.create()
            end

            init(self);

            waitfor(self.handleStruct.table);

        end
        function create(self)
            ss = get(0,'ScreenSize');
            screenCenter = ss(3:4)/2;

            self.handleStruct.figureHandle = figure('units','pixels',...
                'position',[screenCenter(1)-self.windowSize(1)/2 screenCenter(2)-self.windowSize(2)/2 self.windowSize],...
                'menubar','none',...
                'toolbar','none',...
                'numberTitle','off',...
                'Name',self.titleStr,...
                'Interruptible','off',...
                'BusyAction','cancel',...
                'DockControls','off');

            self.managedHandle = uipanel(self.handleStruct.figureHandle, ...
                'units','normalized',...
                'BorderType','none',...
                'Position',[0 0 1 1]);

            self.madeThisWindow = true;

        end

        function init(self)

            self.handleStruct.table = uitable('parent',self.managedHandle,...
                'units','pixels','position',[1 1 50 50]); % Dummy position
            if ~isfield(self.handleStruct,'figureHandle') || ~ishandle(self.handleStruct.figureHandle)
                self.handleStruct.figureHandle = gcf; %Is this ok? It depens how we use this.
            end
            drawnow;

            self.handleStruct.jScrollPane = findjobj(self.handleStruct.table);
            self.handleStruct.jTable = self.handleStruct.jScrollPane.getViewport.getView;

            % Set the actual data in the cell
            structArrayToCell(self);
            set(self.handleStruct.table,'data',self.dataCell,...
                'columnName',self.tableFieldNames,...
                'RearrangeableColumns','on',...
                'RowName',{},...
                'TooltipString','Available Options',...
                'ColumnEditable',false(1,length(self.tableFieldNames)),...
                'KeyPressFcn',@self.tableKeyPressFcn,...
                'CellSelectionCallback',@self.cellCelectionFcn);

            % Force selection of full rows only
            self.handleStruct.jTable.setNonContiguousCellSelection(false)

            % Force selection of a single row only
            if ~self.enableMultiSelect
                self.handleStruct.jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
            end

            % Set the column widths to take up the whole area
            self.handleStruct.jTable.setAutoResizeMode(self.handleStruct.jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

            [self.handleStruct.textHandle, self.handleStruct.textHandleContainer]  = javacomponent('javax.swing.JLabel',[1 1 1 1], self.managedHandle);
            backgroundColor = get(self.managedHandle,'BackgroundColor');
            set(self.handleStruct.textHandle,'Text',self.messageStr,'Background',java.awt.Color(backgroundColor(1),backgroundColor(2),backgroundColor(3)),...
                'Font',java.awt.Font('sansserif',java.awt.Font.PLAIN,self.textFontSize));
            self.handleStruct.textHandle.setVerticalAlignment(javax.swing.JLabel.TOP);

            self.handleStruct.cancelButton = uicontrol('style','pushbutton',...
                'parent',self.managedHandle,...
                'units','pixels',...
                'position',[1 1 10 10],...
                'callback',@self.cancelCallback,...
                'string',self.cancelStr);

            self.handleStruct.okButton = uicontrol('style','pushbutton',...
                'parent',self.managedHandle,...
                'units','pixels',...
                'position',[1 1 10 10],...
                'callback',@self.okCallback,...
                'string',self.okStr);

            % Set and call the resize function to set the element positions
            set(self.managedHandle,'ResizeFcn',@self.resizeFunction);
            resizeFunction(self);

            drawnow;
            set(self.handleStruct.jTable,'Font',java.awt.Font('sansserif',java.awt.Font.PLAIN,self.tableFontSize));
        end

        function close(self)
            if self.madeThisWindow
                try %#ok<TRYNC>
                    close(self.handleStruct.figureHandle);
                end
            else
                try
                    delete(self.handleStruct.table);
                end
            end

        end

        function okCallback(self, varargin)
            self.enteredSelection = getSelection(self);
            close(self)
        end

        function cancelCallback(self, varargin)
            close(self);
        end

        function structArrayToCell(self)
            self.tableFieldNames = fieldnames(self.inputStruct)';
            self.dataCell = struct2cell(self.inputStruct)';
        end

        function resizeFunction(self, varargin)
            panelPosition = getpixelposition(self.managedHandle);

            border = 8;
            textHeight = 50;
            buttonHeight = 20;
            buttonWidth = 50;

            left = border+1;
            width = panelPosition(3);
            bottom = border+1;
            height= panelPosition(4);

            textBottom = max(height-textHeight-border,1);

            okButtonLeft = width/2-border/2-buttonWidth;
            cancelButtonLeft = width/2+border/2;

            tableBottom = bottom+border+buttonHeight;
            tableHeight = max(height-buttonHeight-border*4-textHeight,1);

            okButtonPos = [okButtonLeft bottom buttonWidth, buttonHeight];
            cancelButtonPos = [cancelButtonLeft bottom buttonWidth, buttonHeight];

            tablePos = [left tableBottom width-border*2-2 tableHeight];
            textPos = [left textBottom width-border*2-2 textHeight];

            set(self.handleStruct.okButton,'units','pixels');
            set(self.handleStruct.okButton,'position',okButtonPos);
            set(self.handleStruct.okButton,'units','normalized');

            set(self.handleStruct.cancelButton,'units','pixels');
            set(self.handleStruct.cancelButton,'position',cancelButtonPos);
            set(self.handleStruct.cancelButton,'units','normalized');

            set(self.handleStruct.table,'units','pixels');
            set(self.handleStruct.table,'position',tablePos);
            set(self.handleStruct.table,'units','normalized');

            set(self.handleStruct.textHandleContainer,'units','pixels')
            set(self.handleStruct.textHandleContainer,'position',textPos)
            set(self.handleStruct.textHandleContainer,'units','normalized')

            %drawnow;
        end

        function tableKeyPressFcn(self, varargin)
            event = varargin{2};

            if strcmpi(event.Key,'Return')

                % They hit return, so select this entry and exit
                % When you hit return MATLAB (I think), moves the selection
                % to the "next" cell. If you have the last one selected it
                % goes back around to zero.
                reportedSelection = getSelection(self);
                reportedSelection = reportedSelection - 1; % undo the wrap arround
                if reportedSelection==0 % We actually selected the end and they wrapped us around to 1
                    reportedSelection = length(self.inputStruct);
                end

                self.enteredSelection = reportedSelection;

                drawnow;
                self.handleStruct.jTable.setRowSelectionInterval(reportedSelection-1,reportedSelection-1);
                drawnow;

                close(self);

            elseif strcmpi(event.Key,'Escape')
                % Leave with an empty selection
                close(self)
            else
                % Nada, probably an arrow
            end
        end
        function reportedSelection = getSelection(self)
            if ~self.enableMultiSelect
                reportedSelection = self.handleStruct.jTable.getSelectedRow()+1;% Java is 0 referenced
            else
                reportedSelection = self.handleStruct.jTable.getSelectedRows()+1;% Java is 0 referenced
            end
        end
        function set.inputStruct(self, val)
            assert(isstruct(val) || iscellstr(val),'inputStruct must be a structure array or a cellstr');

            if iscellstr(val)
                cellOfStrs = val; cellOfStrs = cellOfStrs(:);
                self.inputStruct = struct('Choices',cellOfStrs);
            else
                self.inputStruct = val(:);
            end
        end
    end
end


function [ ret ] = setPin2On( t_Kuka )
%% About:
% This function is used to set on the Pin 2 of the KUKA iiwa 7 R 800.

%% Syntax:
% [ ret ] = setPin2On( t_Kuka )

%% Arreguments:
% t_Kuka: is the TCP/IP connection

%% Return value:
% ret: a boolean variable
% true: if the message is treated successfully
% false: if an error has happened

% Copy right, Mohammad SAFEEA, 3rd of May 2017

theCommand='pin2on';
fprintf(t_Kuka, theCommand);
message=fgets(t_Kuka);
ret=checkAcknowledgment(message);
end


function [ compSymbolList, compNameList  ] = getDefaultCompartments( )
%GETDEFAULTCOMPARTMENTS returns the default compartment Symbols and default Compartments
%
%   USAGE:  [ compSymbolList, compNameList  ] = getDefaultCompartments( )
%
% OUTPUT:
%    compSymbolList:       Default symbols of compartments
%    compNameList:         Names of the default compartments.
%
% .. Authors: Thomas Pfau May 2017
    compSymbolList = {'c','m','v','x','e','t','g','r','n','p','l','u'};
    compNameList = {'Cytoplasm','Mitochondrion','Vacuole','Peroxisome','Extracellular','Pool','Golgi','Endoplasmic_reticulum','Nucleus','Periplasm','Lysosome','Unknown'};

end


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

Version  = '6.0';
date =  '07-Mar-2021';


function labeled_output = PTKWatershedMeyerFromStartingPoints( ~, ~ )
    % PTKWatershedMeyerFromStartingPoints Implementation of Meyer flooding algorithm
    %
    %     This is a Matlab mex file and must be compiled before use.
    %
    %     To compile, type
    %
    %         mex PTKWatershedMeyerFromStartingPoints
    %
    %     in the Matlab command window.

    error('PTKWatershedMeyerFromStartingPoints has not been compiled. You must compile using mex PTKWatershedMeyerFromStartingPoints. Alternatively, use the slower Matlab equivalent function mex PTKWatershedMeyerFromStartingPointsMatlab().');
end


function params = init_default_params(params)

% Initialize default parameters
default_params.use_gpu = false;
default_params.gpu_id = [];
default_params.clamp_position = false;

def_param_names = fieldnames(default_params);
for k = 1:numel(def_param_names)
    param_name = def_param_names{k};
    if ~isfield(params, param_name)
        params.(param_name) = default_params.(param_name);
    end
end

params.visualization = params.visualization;


% This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix

try
	Type = ver;
	% This part is for OCTAVE
	if(strcmp(Type(1).Name, 'Octave') == 1)
		mex libsvmread.c
		mex libsvmwrite.c
		mex svmtrain.c ../svm.cpp svm_model_matlab.c
		mex svmpredict.c ../svm.cpp svm_model_matlab.c
	% This part is for MATLAB
	% Add -largeArrayDims on 64-bit machines of MATLAB
	else
		mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmread.c
		mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmwrite.c
		mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims svmtrain.c ../svm.cpp svm_model_matlab.c
		mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims svmpredict.c ../svm.cpp svm_model_matlab.c
	end
catch
	fprintf('If make.m failes, please check README about detailed instructions.\n');
end


classdef Display_Plot < Display_Abstract

    methods (Access = protected)

        function setChartType(obj)
            obj.handle = plot(0,0);
        end

    end

end


classdef MimMarkerPoint
    %MimMarkerPoint Used in exporting of marker points to disk
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %
    properties
        X
        Y
        Z
        Label
    end

    methods
        function obj = MimMarkerPoint(x, y, z, label)
            if nargin > 0
                obj.X = x;
                obj.Y = y;
                obj.Z = z;
                obj.Label = label;
            end
        end
    end
end


function obj = updateContourProjection(obj,contourIndex)

%-FIGURE DATA STRUCTURE-%
figure_data = get(obj.State.Figure.Handle);

%-AXIS INDEX-%
axIndex = obj.getAxisIndex(obj.State.Plot(contourIndex).AssociatedAxis);

%-AXIS DATA STRUCTURE-%
axis_data = get(obj.State.Plot(contourIndex).AssociatedAxis);

%-PLOT DATA STRUCTURE- %
contour_data = get(obj.State.Plot(contourIndex).Handle);

%-CHECK FOR MULTIPLE AXES-%
[xsource, ysource] = findSourceAxis(obj,axIndex);

%-AXIS DATA-%
eval(['xaxis = obj.layout.xaxis' num2str(xsource) ';']);
eval(['yaxis = obj.layout.yaxis' num2str(ysource) ';']);

%-------------------------------------------------------------------------%

%-contour xaxis-%
obj.data{contourIndex}.xaxis = ['x' num2str(xsource)];

%-------------------------------------------------------------------------%

%-contour yaxis-%
obj.data{contourIndex}.yaxis = ['y' num2str(ysource)];

%-------------------------------------------------------------------------%

%-contour name-%
obj.data{contourIndex}.name = contour_data.DisplayName;

%-------------------------------------------------------------------------%

%-setting the plot-%
xdata = contour_data.XData;
ydata = contour_data.YData;
zdata = contour_data.ZData;

%-contour type-%
obj.data{contourIndex}.type = 'surface';

%-contour x and y data
obj.data{contourIndex}.x = xdata;
obj.data{contourIndex}.y = ydata;

%-contour z data-%
obj.data{contourIndex}.z = zdata;%-2*ones(size(zdata));

%-setting for contour lines z-direction-%
obj.data{contourIndex}.contours.z.start = contour_data.LevelList(1);
obj.data{contourIndex}.contours.z.end = contour_data.LevelList(end);
obj.data{contourIndex}.contours.z.size = contour_data.LevelStep;
obj.data{contourIndex}.contours.z.show = true;
obj.data{contourIndex}.contours.z.usecolormap = true;
obj.data{contourIndex}.hidesurface = true;
obj.data{contourIndex}.surfacecolor = zdata;

obj.data{contourIndex}.contours.z.project.x = true;
obj.data{contourIndex}.contours.z.project.y = true;
obj.data{contourIndex}.contours.z.project.z = true;

%-------------------------------------------------------------------------%

%-contour visible-%

obj.data{contourIndex}.visible = strcmp(contour_data.Visible,'on');

%-------------------------------------------------------------------------%

%-contour showscale-%
obj.data{contourIndex}.showscale = false;

%-------------------------------------------------------------------------%

%-colorscale (ASSUMES PATCH CDATAMAP IS 'SCALED')-%
colormap = figure_data.Colormap;

for c = 1:size((colormap),1)
    col =  255*(colormap(c,:));
    obj.data{contourIndex}.colorscale{c} = {(c-1)/(size(colormap,1)-1), ['rgb(' num2str(col(1)) ',' num2str(col(2)) ',' num2str(col(3)) ')']};
end

%-------------------------------------------------------------------------%

%-contour reverse scale-%
obj.data{contourIndex}.reversescale = false;

%---------------------------------------------------------------------%

%-aspect ratio-%
ar = obj.PlotOptions.AspectRatio;

if ~isempty(ar)
    if ischar(ar)
        obj.layout.scene.aspectmode = ar;
    elseif isvector(ar) && length(ar) == 3
        xar = ar(1);
        yar = ar(2);
        zar = ar(3);
    end
else

    %-define as default-%
    xar = max(xdata(:));
    yar = max(ydata(:));
    xyar = max([xar, yar]);
    zar = 0.6*xyar;
end

obj.layout.scene.aspectratio.x = xyar;
obj.layout.scene.aspectratio.y = xyar;
obj.layout.scene.aspectratio.z = zar;

%---------------------------------------------------------------------%

%-camera eye-%
ey = obj.PlotOptions.CameraEye;

if ~isempty(ey)
    if isvector(ey) && length(ey) == 3
        obj.layout.scene.camera.eye.x = ey(1);
        obj.layout.scene.camera.eye.y = ey(2);
        obj.layout.scene.camera.eye.z = ey(3);
    end
else

    %-define as default-%
    xey = - xyar; if xey>0 xfac = -0.2; else xfac = 0.2; end
    yey = - xyar; if yey>0 yfac = -0.2; else yfac = 0.2; end
    if zar>0 zfac = 0.2; else zfac = -0.2; end

    obj.layout.scene.camera.eye.x = xey + xfac*xey;
    obj.layout.scene.camera.eye.y = yey + yfac*yey;
    obj.layout.scene.camera.eye.z = zar + zfac*zar;
end

%-------------------------------------------------------------------------%

%-contour showlegend-%

leg = get(contour_data.Annotation);
legInfo = get(leg.LegendInformation);

switch legInfo.IconDisplayStyle
    case 'on'
        showleg = true;
    case 'off'
        showleg = false;
end

obj.data{contourIndex}.showlegend = showleg;

%-------------------------------------------------------------------------%

end


% Add Manopt to the path and make all manopt components available.

% This file is part of Manopt: www.manopt.org.
% Original author: Nicolas Boumal, Jan. 3, 2013.
% Contributors:
% Change log:
%   Aug.  7, 2013 (NB): Changed to work without the import command
%                      (new structure of the toolbox).
%   Aug.  8, 2013 (NB): Changed to use addpath_recursive, home brewed.
%   Aug. 22, 2013 (NB): Using genpath instead of homecooked
%                       addpath_recursive.

addpath(pwd);

% Recursively add Manopt directories to the Matlab path.
cd manopt;
addpath(genpath(pwd));
cd ..;


function dicomHeaders = MRSI_read_dicom_headers(folderName)
    arguments
        folderName (1, :) char {mustBeFolder}
    end
    dicomFolder = dir(folderName);
    % remove . and .. files from dicomFolder
    dicomFolder = dicomFolder(~ismember({dicomFolder.name}, {'.', '..'}));

    dicomPath = arrayfun(@(listing) fullfile(listing.folder, listing.name), dicomFolder, 'UniformOutput', false);

    dicomHeaders = spm_dicom_headers(dicomPath);
end


function [featureLexiconNameList, ...
          featureLexiconFileNameList, ...
          featureLexiconAnimalTypeList] = ...
  getFeatureLexiconListsFromXML(jaabarootdir)

% Figure out the name of the XML file holding the list of the possible
% feature lexicons
if isdeployed,
  filename = deployedRelative2Global('params/featureConfigList.xml');
else
  filename = 'featureConfigList.xml';
  if nargin >= 1,
    filename = fullfile(jaabarootdir,'perframe','params',filename);
  end

end
% Read in the XML file
featureLexiconListThing = ReadXMLParams(filename);
% break out that information into three cell arrays, each of length equal
% to the number of feature lexicons
%   featureLexiconNameList{i} holds the name of the ith lexicon, e.g.
%   'flies', 'larvae', 'vivek_mice'.
%   featureLexiconFileNameList{i} holds the file name of the XML file
%     describing the ith lexicon
%   featureLexiconAnimalTypeList{i} holds the name of the animal that the
%     ith lexicon is designed to be used with.  E.g. 'fly', or 'mouse', or
%     'larva'.  This should be singular, not plural.
featureLexiconNameList=fieldnames(featureLexiconListThing);
nFeatureLexicons=length(featureLexiconNameList);
featureLexiconFileNameList=cell(nFeatureLexicons,1);
featureLexiconAnimalTypeList=cell(nFeatureLexicons,1);
for i=1:nFeatureLexicons
  featureLexiconName=featureLexiconNameList{i};
  featureLexiconFileNameList{i}=featureLexiconListThing.(featureLexiconName).file;
  if nargin >= 1,
    featureLexiconFileNameList{i} = fullfile(jaabarootdir,'perframe',featureLexiconFileNameList{i});
  end
  featureLexiconAnimalTypeList{i}=featureLexiconListThing.(featureLexiconName).animal;
end

end


function GSS = getWoLFScores(inputFile, kingdom)
% getWoLFScores
%   Call WoLF PSort to predict the sub-cellular localization of proteins.
%   The output can be used as input to predictLocalization. This function
%   is currently only available for Linux and requires Perl to be
%   installed. If one wants to use another predictor, see parseScores. The
%   function normalizes the scores so that the best score for each gene is
%   1.0.
%
%   Input:
%   inputFile	a FASTA file with protein sequences
%   kingdom     the kingdom of the organism, 'animal', 'fungi' or 'plant'
%
%   Output:
%   GSS         a gene scoring structure to be used in predictLocalization
%
%   Usage: GSS = getWoLFScores(inputFile, kingdom)

if ~isfile(inputFile)
    error('FASTA file %s cannot be found',string(inputFile));
end

kingdom=char(kingdom);
if ~any(strcmp(kingdom,{'animal','fungi','plant'}))
    EM='Allowed kingdoms are "animal", "fungi", and "plant"';
    dispEM(EM);
end

if ispc || ismac
    EM='This function currently runs only on Linux. Use parseScores if you want to use another predictor';
    dispEM(EM);
end

%Get the directory for RAVEN Toolbox
ravenPath=findRAVENroot();

%Temporary output name
outFile=tempname;
fid=fopen(outFile,'w');

%Do the prediction
[~, output]=unix(['perl "' ravenPath '/software/WoLFPSORT/bin/runWolfPsortSummary" ' kingdom ' < ' inputFile]);

%Save output and call the general parser
fprintf(fid,output);
fclose(fid);
GSS=parseScores(outFile,'wolf');

%Clean up
delete(outFile);
end


function planC = CERRImportDICOM(study_directory, planC_save_name, defaultSelection)
%"CERRImportDICOM"
%   Calls DICOM routines to import a DICOM directory to CERR file.
%
%   By default use no parameters, which passes the user to a GUI.  To use
%   in batch mode, pass a directory path and save file name.  The directory
%   path must contain ONLY ONE DICOM study, and will have only the first
%   scan,dose,etc extracted.
%
%Last Modified:  28 Aug 03, by ES.
%                added control for proper exit when user cancelled DICOM import
%
%                7 Feb 05, JRA Added batch mode control.
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Start diary and timer for import log.
startTime = now;
tmpFileName = tempname;
diary(tmpFileName);
Ver = version;
tic;

if exist('study_directory')
    [ap,ap_xmesh,ap_ymesh,ap_zmesh,ap_ct,ap_ct_xmesh,ap_ct_ymesh,ap_ct_zmesh,ap_voi,MRCell,PETCell,SPECTCell]=dicomrt_DICOMimport(study_directory, 'r', defaultSelection);
else
    [ap,ap_xmesh,ap_ymesh,ap_zmesh,ap_ct,ap_ct_xmesh,ap_ct_ymesh,ap_ct_zmesh,ap_voi,MRCell,PETCell,SPECTCell]=dicomrt_DICOMimport;
end

if isempty(ap)==1 & ...
        isempty(ap_xmesh)==1 & ...
        isempty(ap_ymesh)==1 & ...
        isempty(ap_zmesh)==1 & ...
        isempty(ap_ct)==1 & ...
        isempty(ap_ct_xmesh)==1 & ...
        isempty(ap_ct_ymesh)==1 & ...
        isempty(ap_ct_zmesh)==1 & ...
        isempty(ap_voi)==1 & ...
        isempty(MRCell) & ...
        isempty(PETCell) & ...
        isempty(SPECTCell) , ...
        return;
else
    [planC] = dicomrt_dicomrt2cerr(ap,ap_xmesh,ap_ymesh,ap_zmesh,ap_ct,...
        ap_ct_xmesh,ap_ct_ymesh,ap_ct_zmesh,ap_voi,'CERROptions.m',MRCell,PETCell,SPECTCell);
end

%Stop diary and write it to planC.
diary off;
endTime = now;
logC = file2cell(tmpFileName);
delete(tmpFileName);
indexS = planC{end};
planC{indexS.importLog}(1).importLog = logC;
planC{indexS.importLog}(1).startTime = datestr(startTime);
planC{indexS.importLog}(1).endTime = datestr(endTime);

toc;
% Save plan  -- this line moved out from dicomrt_dicomrt2cerr.  If a passed
% save name was used, save there, else prompt.
if exist('planC_save_name')
    save_planC(planC,planC{indexS.CERROptions}, 'passed', planC_save_name);
else
    save_planC(planC,planC{indexS.CERROptions});
end


classdef Create < handle
    properties
        serPort
        delay
        cur_mode           % current mode: passive, safe, full
    end

    methods
        function robot = Create(varargin)
        %[serPort] = RoombaInit(my_COM)
        % initializes serial port for use with Roomba
        % COMMport is the number of the comm port
        % ex. RoombaInit(1) sets port = 'COM1'
        % note that it sets baudrate to a default of 57600
        % can be changed (see SCI).
        % An optional time delay can be added after all commands
        % if your code crashes frequently.  15 ms is recommended by irobot
        % By; Joel Esposito, US Naval Academy, 2011

        % This code puts the robot in CONTROL(132) mode, which means does NOT stop
        % when cliff sensors or wheel drops are true; can also run while plugged into charger

            Contrl = 132;

            % Esposito 9/2008

            warning off

            opt.port = '';
            opt.delay = 0.015;

            opt = tb_optparse(opt, varargin);

            robot.delay = opt.delay;

            % clean up any previous instances of the port, can happen...
            for tty = instrfind('port', opt.port)
                if ~isempty(tty)
                    disp(['serPort ' tty.serPort.port 'is in use.   Closing it.'])
                    fclose(tty);
                    delete(tty);
                end
            end

            if opt.verbose
                disp('Establishing connection to Roomba...');
            end

            % defaults at 57600, can change
            robot.serPort = serial(opt.port,'BaudRate', 57600);
            set(robot.serPort,'Terminator','LF')
            set(robot.serPort,'InputBufferSize',100)
            set(robot.serPort, 'Timeout', 1)
            set(robot.serPort, 'ByteOrder','bigEndian');
            set(robot.serPort, 'Tag', 'Roomba')

            robot.serPort

            if opt.verbose
                disp('Opening connection to Roomba...');
            end

            pause(0.5);
            try
            fopen(robot.serPort);
            catch me
                disp('open failed');
                me.message
                return
            end

            %% Confirm two way connumication
            disp('Setting Roomba to Control Mode...');

            % Start! and see if its alive
            robot.mode('passive');

            robot.mode('full');

            % light LEDS
            robot.write([139 25 0 128]);

            % set song 1, default beep
            robot.write([140 1 1 48 20], 0.05);

            % sing it
            robot.write([141 1])

            disp('I am alive if my two outboard lights came on')

            confirmation = robot.read(4, 0.1);
        end

        function msg = read(robot, nbytes, delay)
            msg = fread(robot.serPort, nbytes);
            if nargin > 2
                pause(delay);
            end
        end

        function v = fread(robot, n, type, delay)
            v = fread(robot.serPort, n, type);

            if nargin > 3
                pause(delay);
            else
                pause(robot.delay)
            end
        end

        function write(robot, msg, delay)
            fwrite(robot.serPort, msg);
            fprintf('write: '); disp(msg);

            if nargin > 2
                pause(delay);
            else
                pause(robot.delay)
            end
        end

        function fwrite(robot, val, type, delay)
            fwrite(robot.serPort, val, type);
            disp(['fwrite:' val '(' type ')']);

            if nargin > 3
                pause(delay);
            else
                pause(robot.delay)
            end
        end

        function flush(robot)
            %Flush Buffer
            N = robot.serPort.BytesAvailable();
            while(N ~= 0)
                fread(robot.serPort,N);
                N = robot.serPort.BytesAvailable();
            end
        end

        function delete(robot)
            tty = instrfind('port', robot.serPort.port);
            fclose(tty);
            pause(1)
            delete(tty);
            pause(1)
        end

        function s = char(robot)
            s = sprintf('iCreate robot on port %s', robot.serPort.port);
        end
    end % methods
end % classdef


function export_protocol(iProtocol, iSubject, OutputFile)
% EXPORT_PROTOCOL: Export a protocol into a zip file.
%
% USAGE:  export_protocol(iProtocol, iSubject, OutputFile)
%         export_protocol(iProtocol, iSubject)        : Ask for the output filename
%         export_protocol(iProtocol)                  : Export all the subjects of protocol, ask for the output filename
%         export_protocol()                           : Export current protocol, ask for the output filename

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

global GlobalData;

%% ===== PARSE INPUTS =====
if (nargin < 3)
    OutputFile = [];
end
if (nargin < 2)
    iSubject = [];
end
if (nargin < 1) || isempty(iProtocol)
    iProtocol = bst_get('iProtocol');
else
    gui_brainstorm('SetCurrentProtocol', iProtocol);
end
% Check protocol indice
if isempty(iProtocol) || (iProtocol == 0)
    bst_error('Invalid protocol indice.', 'Export protocol', 0);
    return
end
% Get protocol description
ProtocolInfo = bst_get('ProtocolInfo');
% Get output filename
if isempty(OutputFile)
    % Get default directories
    LastUsedDirs = bst_get('LastUsedDirs');
	% Default output filename
    if isempty(iSubject)
        OutputFile = bst_fullfile(LastUsedDirs.ExportProtocol, file_standardize([ProtocolInfo.Comment, '.zip']));
    else
        sSubject = bst_get('Subject', iSubject);
        OutputFile = bst_fullfile(LastUsedDirs.ExportProtocol, file_standardize([ProtocolInfo.Comment, '_', sSubject.Name, '.zip']));
    end
    % File selection
    OutputFile = java_getfile('save', 'Export protocol', OutputFile, 'single', 'files', ...
                              {{'.zip'}, 'Zip files (*.zip)', 'ZIP'}, 1);
    if isempty(OutputFile)
        return
    end
    % Save new default export path
    LastUsedDirs.ExportProtocol = bst_fileparts(OutputFile);
    bst_set('LastUsedDirs', LastUsedDirs);
end
% Force saving database
db_save(1);

%% ===== ZIP FILES =====
% Progress bar
bst_progress('start', 'Export protocol', 'Creating zip file...');
% Cd to protocol folder
prevFolder = pwd;
cd(bst_fileparts(ProtocolInfo.SUBJECTS, 1));
% Prefixes to add to the folders
[tmp__, anatFolder] = bst_fileparts(ProtocolInfo.SUBJECTS, 1);
[tmp__, dataFolder] = bst_fileparts(ProtocolInfo.STUDIES, 1);
% Build list of files to zip
if isempty(iSubject)
    % Add the entire subject folder
    ListZip = {anatFolder};
    % List files in studies: add all files
    allFiles = dir(ProtocolInfo.STUDIES);
    for i = 1:length(allFiles)
        if (allFiles(i).name(1) ~= '.')
            ListZip{end+1} = bst_fullfile(dataFolder, allFiles(i).name);
        end
    end
else
    % Get default study for this subject
    sSubject = bst_get('Subject', iSubject, 1);
    sStudy   = bst_get('AnalysisIntraStudy', iSubject);
    % Create a temporary protocol.mat for future database update information
    ProtocolMat = struct();
    ProtocolMat.ProtocolInfo      = GlobalData.DataBase.ProtocolInfo(iProtocol);
    ProtocolMat.ProtocolSubjects  = GlobalData.DataBase.ProtocolSubjects(iProtocol);
    ProtocolMat.ProtocolStudies   = GlobalData.DataBase.ProtocolStudies(iProtocol);
    ProtocolMat.DbVersion         = GlobalData.DataBase.DbVersion;
    ProtocolMat.LastAccessDate    = datestr(now);
    ProtocolMat.LastAccessUserDir = bst_get('UserDir');
    % Remove useless fields
    StudyDir = ProtocolMat.ProtocolInfo.STUDIES;
    ProtocolMat.ProtocolInfo = rmfield(ProtocolMat.ProtocolInfo, 'STUDIES');
    ProtocolMat.ProtocolInfo = rmfield(ProtocolMat.ProtocolInfo, 'SUBJECTS');
    ProtocolMat.ProtocolSubjects.Subject = ProtocolMat.ProtocolSubjects.Subject(iSubject);
    [sStudies, iStudies] = bst_get('StudyWithSubject', ProtocolMat.ProtocolSubjects.Subject.FileName, 'default_study', 'intra_subject');
    ProtocolMat.ProtocolStudies.Study = ProtocolMat.ProtocolStudies.Study(iStudies);
    ProtocolFile = bst_fullfile(dataFolder, 'protocol.mat');
    bst_save(ProtocolFile, ProtocolMat, 'v7');
    % List all files that might be useful for this subject
    ListZip = {bst_fullfile(anatFolder, bst_fileparts(sSubject.FileName)), ...
               bst_fullfile(anatFolder, bst_get('DirDefaultSubject')), ...
               bst_fullfile(dataFolder, bst_fileparts(bst_fileparts(sStudy.FileName))), ...
               bst_fullfile(dataFolder, bst_get('DirDefaultStudy')), ...
               bst_fullfile(dataFolder, bst_get('DirAnalysisInter')), ...
               ProtocolFile};
end
% Zip
zip(OutputFile, ListZip);
% Restore protocol file
if ~isempty(iSubject)
    % Remove temporary protocol file
    file_delete(bst_fullfile(StudyDir, 'protocol.mat'), 1);
    % Save again the original one
    GlobalData.DataBase.isProtocolModified(iProtocol) = 1;
    db_save(1);
end
% Restore initial folder
cd(prevFolder);
% Close progress bar
bst_progress('stop');


function neuron = fix_mat_files(root)

    %% Get path of all .mat files in root directory
    % get filenames to process
    files = dir([root, '/**/*-*_*_*_*.mat']);
    not = dir([root, '/**/*-*-*_*_*_*.mat']);
    [~,ia] = setdiff({files.name}, {not.name});
    files = files(ia);

    %% Open up each .mat file and save as a cleaned file (and format v6)
    for ff = 1:length(files)
        if ~exist([files(ff).folder, '/out.mat'], 'file')
            load([files(ff).folder, '/', files(ff).name]);
            neuron = struct(neuron);
            save([files(ff).folder, '/out.mat'],'-v6','-struct','neuron');
            clear neuron;
        end
    end

end


function studyPath = studySave(studies);
% Save a set of studies in the local studies.mat file.
%
% studyPath = studySave(studies);
%
% Returns the path to the updated studies file. This should reside
% in the same directory as the study-related MATLAB functions. mrVista 2
% is intended to have a unique set of studies for each copy of the code,
% in order to be unambiguous and minimize the selection of files. (If it's
% decide to change this, these functions will needed to be significantly
% expanded.)
%
% ras, 07/06
if nargin<1, error('Not enough input args.'); end

parentDir = fileparts(which(mfilename)); % parent directory of this M-file.
studyPath = fullfile(parentDir, 'studies.mat');

save(studyPath, 'studies');

return


function varargout = sr_gui(varargin)
% SR_GUI M-file for sr_gui.fig
%      SR_GUI, by itself, creates a new SR_GUI or raises the existing
%      singleton*.
%
%      H = SR_GUI returns the handle to a new SR_GUI or the handle to
%      the existing singleton*.
%
%      SR_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SR_GUI.M with the given input arguments.
%
%      SR_GUI('Property','Value',...) creates a new SR_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before sr_gui_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to sr_gui_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 sr_gui

% Last Modified by GUIDE v2.5 19-Feb-2011 00:22:12

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @sr_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @sr_gui_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 sr_gui is made visible.
function sr_gui_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 sr_gui (see VARARGIN)

% Choose default command line output for sr_gui
handles.mouse_pressed=0;
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% This sets up the initial plot - only do when we are invisible
% so window can get raised using sr_gui.
if strcmp(get(hObject,'Visible'),'off')
    plot(rand(5));
end

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

% --- Outputs from this function are returned to the command line.
function varargout = sr_gui_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
varargout{1} = handles.output;

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

h=waitbar(0,'Registering images...');
for id=2:length(handles.images)
    clear timage;
    for color=1:3
        timage(:,:,color)=register_image(double(handles.images{1}(:,:,color)),double(handles.images{id}(:,:,color)));

    end
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);
guidata(hObject,handles);
frame_slider_Callback(hObject, [], handles)

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

% --------------------------------------------------------------------
function LoadMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to LoadMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
folder = uigetdir;
files=dir(sprintf('%s/*.jpg',folder));
tmp=dir(sprintf('%s/*.JPG',folder));
files(length(files)+1:length(files)+length(tmp))=tmp;

handles.images=[];
h=waitbar(0,'Loading images...');
for id=1:length(files)
    handles.images{id}=double(imread(sprintf('%s/%s',folder,files(id).name)))/255;
%     for color=1:3
%         timage(:,:,color)=double(flipud(handles.images{id}(:,:,color)'));
%     end
    if length(size(handles.images{id}))==2 % expand grey scale image to color image format
        t=handles.images{id};
        t=zeros([size(handles.images{id}) 3]);
        t(:,:,1)=handles.images{id};
        t(:,:,2)=handles.images{id};
        t(:,:,3)=handles.images{id};
        handles.images{id}=t;
    end
    waitbar(id/length(files),h);
%     handles.images{id}=timage;
end
delete(h);

% for color=1:3
%     timage(:,:,color)=double(flipud(handles.images{1}(:,:,color)'));
% end
% images{1}=timage;

% handle.ImageAxes
axes(handles.ImageAxes);
hold off;
imshow(handles.images{1});
hold on;
set(handles.FrameSlider,'min',1);
set(handles.FrameSlider,'max',length(handles.images));
set(handles.FrameSlider,'value',1);
set(handles.frame_title,'string','Frame 1');
title('Frame 1');
guidata(hObject,handles);

% if ~isequal(folder, 0)
%     open(file);
% end

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

% --------------------------------------------------------------------
function CloseMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to CloseMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...
                     ['Close ' get(handles.figure1,'Name') '...'],...
                     'Yes','No','Yes');
if strcmp(selection,'No')
    return;
end

delete(handles.figure1)

% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (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

set(hObject, 'String', {'plot(rand(5))', 'plot(sin(1:0.01:25))', 'bar(1:.5:10)', 'plot(membrane)', 'surf(peaks)'});

% --- Executes on slider movement.
function FrameSlider_Callback(hObject, eventdata, handles)
% hObject    handle to FrameSlider (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
axes(handles.ImageAxes);
hold off;
imshow(handles.images{round(get(hObject,'value'))});
hold on;
%set(handles.frame_title,'string',sprintf('Frame %d',round(get(hObject,'value'))));
title(sprintf('Frame %d',round(get(hObject,'value'))));

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on mouse motion over figure - except title and menu.
function figure1_WindowButtonMotionFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pos=get(handles.ImageAxes,'currentpoint');
pos=pos(1,1:2);
if inrange(pos,handles.ImageAxes)
    if isfield(handles,'mouse_pressed')
        if handles.mouse_pressed
           if isfield(handles,'last_box')
                if ishandle(handles.last_box)
                    delete(handles.last_box);
                end
           end
           axes(handles.ImageAxes);
           handles.last_box=drawbox(handles.start_pos,pos);
           guidata(hObject,handles);
        end
    end

end

function h=drawbox(p1,p2)
x=[p1(1) p2(1) p2(1) p1(1) p1(1)];
y=[p1(2) p1(2) p2(2) p2(2) p1(2)];
h=plot(x,y);

% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

pos=get(handles.ImageAxes,'currentpoint');
pos=pos(1,1:2);
if inrange(pos,handles.ImageAxes)
    handles.start_pos=pos;
    handles.mouse_pressed=1;
end
guidata(hObject,handles);

%     handles.tmp_box=drawbox(
% if (pos(1) >=0 & pos(1) <=

function flag=inrange(pos,h)
s=size(get(findobj(h,'type','image'),'cdata'));

if (pos(1)>=1) && (pos(2) >=1) && (pos(2) <= s(1)) && (pos(1) <= s(2))
    flag=1;
else
    flag=0;
end

% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonUpFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pos=get(handles.ImageAxes,'currentpoint');
pos=pos(1,1:2);

if inrange(pos,handles.ImageAxes)
    handles.mouse_pressed=0;
    handles.end_pos=pos;
    guidata(hObject,handles);
end

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

% Hints: contents = get(hObject,'String') returns BilinearProjectionPopup contents as cell array
%        contents{get(hObject,'Value')} returns selected item from BilinearProjectionPopup
p1(1)=min([handles.start_pos(1),handles.end_pos(1)]);
p1(2)=min([handles.start_pos(2),handles.end_pos(2)]);
p2(1)=max([handles.start_pos(1),handles.end_pos(1)]);
p2(2)=max([handles.start_pos(2),handles.end_pos(2)]);
p1=round(p1); p2=round(p2);
imobj=findobj(handles.ImageAxes,'type','image');
cdata=get(imobj,'cdata');
fid=round(get(handles.FrameSlider,'value'));
cdata=handles.images{fid};
imclip=cdata(p1(2):p2(2),p1(1):p2(1),:);

contents=get(hObject,'String');
figure;
switch contents{get(hObject,'value')}
    case 'zoom 1x'
        imshow(imclip);
        title('zoom 1x');
    case 'zoom 2x'
        imclip=bilinear_interp(double(imclip));
        imshow(imclip);
        title('zoom 2x');
    case 'zoom 4x'
        imclip=bilinear_interp(double(imclip));
        imclip=bilinear_interp(imclip);
        imshow(imclip);
        title('zoom 4x');
end

% --- Executes during object creation, after setting all properties.
function BilinearProjectionPopup_CreateFcn(hObject, eventdata, handles)
% hObject    handle to BilinearProjectionPopup (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

function [p1,p2]=get_clip_range(handles)
p1(1)=min([handles.start_pos(1),handles.end_pos(1)]);
p1(2)=min([handles.start_pos(2),handles.end_pos(2)]);
p2(1)=max([handles.start_pos(1),handles.end_pos(1)]);
p2(2)=max([handles.start_pos(2),handles.end_pos(2)]);
p1=round(p1); p2=round(p2);

% --- Executes on button press in SRBWButton.
function SRBWButton_Callback(hObject, eventdata, handles)
% hObject    handle to SRBWButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[p1,p2]=get_clip_range(handles);
for id=1:length(handles.images)
    t2{id}=handles.images{id}(p1(2):p2(2),p1(1):p2(1),1)*255;
end
h=waitbar(0,'Running super-resolution for red component...');
image=sr_bw(t2,h,0,1)/255;
delete(h);
figure; imshow(image); title('super resolution image');

% --- Executes on button press in SRColorButton.
function SRColorButton_Callback(hObject, eventdata, handles)
% hObject    handle to SRColorButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[p1,p2]=get_clip_range(handles);
h=waitbar(0,'Running super-resolution for all three components...');
for color=1:3
    for id=1:length(handles.images)
        t2{id}=handles.images{id}(p1(2):p2(2),p1(1):p2(1),color)*255;
    end
    image{color}=sr_bw(t2,h,(color-1)/3,1/3)/255;
end
delete(h);
tmpimg=zeros([size(image{color}) 3]);
for color=1:3
    tmpimg(:,:,color)=image{color};
end
figure; imshow(tmpimg); title('super resolution image');

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

h=waitbar(0,'Registering images...');
for id=2:length(handles.images)
    clear timage;
    timage=register_color_image(double(handles.images{1}), double(handles.images{id}));
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);
guidata(hObject,handles);
FrameSlider_Callback(hObject, [], handles)

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

% Hint: get(hObject,'Value') returns toggle state of CaptureFramesButton

if get(hObject,'value') % starting capturing
   fprintf('starting capturing...');
   handles.images=[];
   vid=videoinput('winvideo',1,'YUY2_320x240');
   vid.ReturnedColorSpace='rgb';
   fid=1;
   axes(handles.ImageAxes);
   hold off;
   while (get(hObject,'value'))
       handles.images{fid}=double(getsnapshot(vid))/255;
       imshow(handles.images{fid});
       title(sprintf('Frame %d',fid));
       fid=fid+1;
   end
   hold on;
   set(handles.FrameSlider,'min',1);
   set(handles.FrameSlider,'max',length(handles.images));
   set(handles.FrameSlider,'value',length(handles.images));
   guidata(hObject, handles);
else
   fprintf('stoping capturing...');
end

% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over CaptureFramesButton.
function CaptureFramesButton_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to CaptureFramesButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

folder = uigetdir;
h=waitbar(0,'Saving images...');
for id=1:length(handles.images)
    imwrite(handles.images{id},sprintf('%s/%d.JPG',folder,id),'quality',100);
    waitbar(id/length(handles.images),h);
end
delete(h);

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

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

h=waitbar(0,'Rotating images...');
for id=1:length(handles.images)
    clear timage;
    for color=1:3
        timage(:,:,color)=double(flipud(handles.images{id}(:,:,color)'));
    end
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);

% handle.ImageAxes
axes(handles.ImageAxes);
hold off;
imshow(handles.images{1});
hold on;
% set(handles.FrameSlider,'min',1);
% set(handles.FrameSlider,'max',length(handles.images));
set(handles.FrameSlider,'value',1);
set(handles.frame_title,'string','Frame 1');
title('Frame 1');
guidata(hObject,handles);

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

h=waitbar(0,'Rotating images...');
for id=1:length(handles.images)
    clear timage;
    for color=1:3
        timage(:,:,color)=double(flipud(handles.images{id}(:,:,color))');
    end
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);

axes(handles.ImageAxes);
hold off;
imshow(handles.images{1});
hold on;
set(handles.FrameSlider,'value',1);
set(handles.frame_title,'string','Frame 1');
title('Frame 1');
guidata(hObject,handles);

% --------------------------------------------------------------------
function DeleteMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to DeleteMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
fid=round(get(handles.FrameSlider,'value'));
handles.images(fid)=[];
if fid > length(handles.images)
    fid=length(handles.images);
end
set(handles.FrameSlider,'value',fid);
set(handles.FrameSlider,'max',length(handles.images));
axes(handles.ImageAxes);
hold off;
imshow(handles.images{fid});
hold on;
title(sprintf('Frame %d',fid));
guidata(hObject,handles);

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

popupmessage('help.txt');

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


%% Template Matlab script to create an BIDS compatible dataset_description.json file
% This example lists all required and optional fields.
% When adding additional metadata please use CamelCase
%
% DHermes, 2017

% Writing json files relies on the JSONio library
% https://github.com/bids-standard/bids-matlab
%
% Make sure it is in the matab/octave path
try
    bids.bids_matlab_version;
catch
    warning('%s\n%s\n%s\n%s', ...
            'Writing the JSON file seems to have failed.', ...
            'Make sure that the following library is in the matlab/octave path:', ...
            'https://github.com/bids-standard/bids-matlab');
end

%%
clear;

this_dir = fileparts(mfilename('fullpath'));
root_dir = fullfile(this_dir, '..', filesep, '..');

project_label = 'templates';

json_label = 'dataset_description';

json_name = fullfile(root_dir, project_label, 'dataset_description.json');

%% General fields, shared with MRI BIDS and MEG BIDS:

%% Required fields:

% name of the dataset
json.Name = '';

% The version of the BIDS standard that was used
json.BIDSVersion = '1.7.0';

% The interpretation of the dataset. MUST be one of "raw" or "derivative".
% For backwards compatibility, the default value is "raw".
json.DatasetType = 'raw';

%% Recommended fields:

% what license is this dataset distributed under? The
% use of license name abbreviations is suggested for specifying a license.
% A list of common licenses with suggested abbreviations can be found in appendix III.
json.License = '';

% List of individuals who contributed to the
% creation/curation of the dataset
json.Authors = {'', '', ''};

json.Acknowledgements = ''; % who should be acknowledge in helping to collect the data

% Instructions how researchers using this
% dataset should acknowledge the original authors. This field can also be used
% to define a publication that should be cited in publications that use the
% dataset.
json.HowToAcknowledge = '';

% sources of funding (grant numbers)
json.Funding = {'', '', ''};

% List of ethics committee approvals of the research protocols and/or protocol identifiers.
json.EthicsApprovals = {''};

% a list of references to
% publication that contain information on the dataset, or links.
json.ReferencesAndLinks = {'', '', ''};

% the Document Object Identifier of the dataset
% (not the corresponding paper).
json.DatasetDOI = 'doi:';

%% Write JSON
% Make sure the directory exists
bids.util.mkdir(fileparts(json_name));
bids.util.jsonencode(json_name, json);


function [k] = getObjCutMovie(inputMovie,inputImages,varargin)
	% Creates a movie cell array cut to a region around input cell images.
	% Biafra Ahanonu
	% started: 2014.01.03 [19:13:01]
	% inputs
		% inputMovie - [x y frames]
		% inputImages - [x y nSignals] - NOTE the dimensions, permute(inputImages,[3 1 2]) if you use [x y nSignals] convention
	% outputs
		%

	[k] = ciapkg.video.getObjCutMovie(inputMovie,inputImages,'passArgs', varargin);
end


classdef AscendingNodeTermCondition < LatitudeTermCondition
    %AscendingNodeTermCondition Summary of this class goes here
    %   Detailed explanation goes here

    properties

    end

    methods
        function obj = AscendingNodeTermCondition()
            obj = obj@LatitudeTermCondition(0.0);
            obj.direction = 1.0;
        end

        function name = getName(obj)
            name = sprintf('Ascending Node');
        end

        function params = getTermCondUiStruct(obj)
            params = getTermCondUiStruct@LatitudeTermCondition(obj);

            params.paramName = 'Ascending Node';
            params.paramUnit = '';
            params.useParam = 'off';
            params.useStages = 'off';
            params.useTanks = 'off';
            params.useEngines = 'off';
            params.useStopwatches = 'off';

            params.value = [];
            params.refStage = LaunchVehicleStage.empty(1,0);
            params.refTank = LaunchVehicleEngine.empty(1,0);
            params.refEngine = LaunchVehicleEngine.empty(1,0);
            params.refStopwatch = LaunchVehicleStopwatch.empty(1,0);
        end

        function tf = usesStage(obj, stage)
            tf = false;
        end

        function tf = usesEngine(obj, engine)
            tf = false;
        end

        function tf = usesTank(obj, tank)
            tf = false;
        end

        function tf = usesEngineToTankConn(obj, engineToTank)
            tf = false;
        end

        function tf = usesStopwatch(obj, stopwatch)
            tf = false;
        end

        function optVar = getNewOptVar(obj)
            optVar = AbstractOptimizationVariable.empty(0,1);
        end

        function optVar = getExistingOptVar(obj)
            optVar = AbstractOptimizationVariable.empty(0,1);
        end
    end

    methods(Static)
        function termCond = getTermCondForParams(paramValue, stage, tank, engine, stopwatch)
            termCond = AscendingNodeTermCondition();
        end
    end
end


%kkasc2mask 'Import ASCII Data File to Mask Segment'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kasc2mask.pane file
%
% Parameters:
% InputFile: i1 'ASCII Input File', required: 'ASCII input data file containing new data segment'
% InputFile: i2 'Data Object Input', optional: 'data object input to insert the new segment into'
% Integer: so 'Start Offset ', default: 0: 'starting point in ASCII file to start importing at'
% Integer: sf 'Skip Factor ', default: 0: 'number of points in ASCII file to skip between reads'
% Integer: wsize ' ', default: 1: 'width size must be > 0'
% Integer: hsize ' ', default: 1: 'height size must be > 0'
% Integer: dsize ' ', default: 1: 'depth size must be > 0'
% Integer: tsize ' ', default: 1: 'time size must be > 0'
% Integer: esize ' ', default: 1: 'elements size must be > 0'
% OutputFile: o 'Output Object', required: 'output data object'
%
% Example: o = kkasc2mask({i1, i2}, {'i1','';'i2','';'so',0;'sf',0;'wsize',1;'hsize',1;'dsize',1;'tsize',1;'esize',1;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kasc2mask - Import ASCII Data File to Mask Segment
%
%  DESCRIPTION
% This routine will import an ASCII data file and insert it into a data
% object if it is specified.  If there is no source object to insert the
% new segment into, the data object specified as the output file will be
% created.  The new segment will be inserted into this data object in the
% mask segment.  If a source object was specified, then all of its
% data segments and the global object attributes will be copied to the
% destination.
% The index order is specified by setting the -windex, -hindex, -dindex,
% -tindex and -eindex flags.  They can not be set to the same value.
% The start offset is the point to start importing in the
% ASCII data.  All points before this one are ignored.
% The skip factor is the number of points to skip in the ASCII
% data between reads.  If the size of the new segment's lowest
% index is 40 and the skip factor is 5, then this routine will
% read in 40 points skip 5 and read in 40 more, etc. until the
% entire ASCII file read in.
% Complex values in ASCII are represented by number pairs, surrounded
% by parenthesis and separated by a comma.  For example, (8, 3) represents
% the complex number 8+3i.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% kasc2val, kasc2loc, kasc2time, kasc2map, kimportasc
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

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

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


function newdata=jdatadecode(data,varargin)
%
% newdata=jdatadecode(data,opt,...)
%
% Convert all JData object (in the form of a struct array) into an array
% (accepts JData objects loaded from either loadjson/loadubjson or
% jsondecode for MATLAB R2016b or later)
%
% This function implements the JData Specification Draft 3 (Jun. 2020)
% see http://github.com/NeuroJSON/jdata for details
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
%
% input:
%      data: a struct array. If data contains JData keywords in the first
%            level children, these fields are parsed and regrouped into a
%            data object (arrays, trees, graphs etc) based on JData
%            specification. The JData keywords are
%               "_ArrayType_", "_ArraySize_", "_ArrayData_"
%               "_ArrayIsSparse_", "_ArrayIsComplex_",
%               "_ArrayZipType_", "_ArrayZipSize", "_ArrayZipData_"
%      opt: (optional) a list of 'Param',value pairs for additional options
%           The supported options include
%               Recursive: [1|0] if set to 1, will apply the conversion to
%                            every child; 0 to disable
%               Base64: [0|1] if set to 1, _ArrayZipData_ is assumed to
%                         be encoded with base64 format and need to be
%                         decoded first. This is needed for JSON but not
%                         UBJSON data
%               Prefix: ['x0x5F'|'x'] for JData files loaded via loadjson/loadubjson, the
%                         default JData keyword prefix is 'x0x5F'; if the
%                         json file is loaded using matlab2018's
%                         jsondecode(), the prefix is 'x'; this function
%                         attempts to automatically determine the prefix;
%                         for octave, the default value is an empty string ''.
%               FullArrayShape: [0|1] if set to 1, converting _ArrayShape_
%                         objects to full matrices, otherwise, stay sparse
%               MaxLinkLevel: [0|int] When expanding _DataLink_ pointers,
%                         this sets the maximum level of recursion
%               FormatVersion: [2|float]: set the JSONLab output version;
%                         since v2.0, JSONLab uses JData specification Draft 1
%                         for output format, it is incompatible with all
%                         previous releases; if old output is desired,
%                         please set FormatVersion to 1
%
% output:
%      newdata: the covnerted data if the input data does contain a JData
%               structure; otherwise, the same as the input.
%
% examples:
%      obj={[],{'test'},true,struct('sparse',sparse(2,3),'magic',uint8(magic(5)))}
%      jdata=jdatadecode(jdataencode(obj))
%      isequaln(obj,jdata)
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

    newdata=data;
    opt=struct;
    if(nargin==2)
        opt=varargin{1};
    elseif(nargin>2)
        opt=varargin2struct(varargin{:});
    end
    opt.fullarrayshape=jsonopt('FullArrayShape',0,opt);
    opt.maxlinklevel=jsonopt('MaxLinkLevel',0,opt);

    %% process non-structure inputs
    if(~isstruct(data))
        if(iscell(data))
            newdata=cellfun(@(x) jdatadecode(x,opt),data,'UniformOutput',false);
        elseif(isa(data,'containers.Map'))
            newdata=containers.Map('KeyType',data.KeyType,'ValueType','any');
            names=data.keys;
            for i=1:length(names)
                newdata(names{i})=jdatadecode(data(names{i}),opt);
            end
        end
        return;
    end

    %% assume the input is a struct below
    fn=fieldnames(data);
    len=length(data);
    needbase64=jsonopt('Base64',0,opt);
    format=jsonopt('FormatVersion',2,opt);
    if(isoctavemesh)
        prefix=jsonopt('Prefix','',opt);
    else
        prefix=jsonopt('Prefix','x0x5F',opt);
    end
    if(~isfield(data,N_('_ArrayType_')) && isfield(data,'x_ArrayType_'))
        prefix='x';
        opt.prefix='x';
    end

    %% recursively process subfields
    if(jsonopt('Recursive',1,opt)==1)
      for i=1:length(fn) % depth-first
        for j=1:len
            if(isstruct(data(j).(fn{i})) || isa(data(j).(fn{i}),'containers.Map'))
                newdata(j).(fn{i})=jdatadecode(data(j).(fn{i}),opt);
            elseif(iscell(data(j).(fn{i})))
                newdata(j).(fn{i})=cellfun(@(x) jdatadecode(x,opt),newdata(j).(fn{i}),'UniformOutput',false);
            end
        end
      end
    end

    %% handle array data
    if(isfield(data,N_('_ArrayType_')) && (isfield(data,N_('_ArrayData_')) || isfield(data,N_('_ArrayZipData_'))))
      newdata=cell(len,1);
      for j=1:len
        if(isfield(data,N_('_ArrayZipSize_')) && isfield(data,N_('_ArrayZipData_')))
            zipmethod='zip';
            if(isstruct(data(j).(N_('_ArrayZipSize_'))))
                data(j).(N_('_ArrayZipSize_'))=jdatadecode(data(j).(N_('_ArrayZipSize_')),opt);
            end
	    dims=data(j).(N_('_ArrayZipSize_'))(:)';
            if(length(dims)==1)
                 dims=[1 dims];
            end
            if(isfield(data,N_('_ArrayZipType_')))
                zipmethod=data(j).(N_('_ArrayZipType_'));
            end
            if(ismember(zipmethod,{'zlib','gzip','lzma','lzip','lz4','lz4hc','base64'}))
                decompfun=str2func([zipmethod 'decode']);
                arraytype=data(j).(N_('_ArrayType_'));
                chartype=0;
                if(strcmp(arraytype,'char') || strcmp(arraytype,'logical'))
                    chartype=1;
                    arraytype='uint8';
                end
                if(needbase64 && strcmp(zipmethod,'base64')==0)
                    ndata=reshape(typecast(decompfun(base64decode(data(j).(N_('_ArrayZipData_')))),arraytype),dims);
                else
                    ndata=reshape(typecast(decompfun(data(j).(N_('_ArrayZipData_'))),arraytype),dims);
                end
                if(chartype)
                    ndata=char(ndata);
                end
            else
                error('compression method is not supported');
            end
        else
            if(isstruct(data(j).(N_('_ArrayData_'))))
                data(j).(N_('_ArrayData_'))=jdatadecode(data(j).(N_('_ArrayData_')),opt);
            end
            if(isstruct(data(j).(N_('_ArrayData_'))) && isfield(data(j).(N_('_ArrayData_')),N_('_ArrayType_')))
                data(j).(N_('_ArrayData_'))=jdatadecode(data(j).(N_('_ArrayData_')),varargin{:});
            end
            if(iscell(data(j).(N_('_ArrayData_'))))
                data(j).(N_('_ArrayData_'))=cell2mat(cellfun(@(x) double(x(:)),data(j).(N_('_ArrayData_')),'uniformoutput',0)).';
            end
            ndata=cast(data(j).(N_('_ArrayData_')),char(data(j).(N_('_ArrayType_'))));
        end
        if(isfield(data,N_('_ArrayZipSize_')))
            if(isstruct(data(j).(N_('_ArrayZipSize_'))))
                data(j).(N_('_ArrayZipSize_'))=jdatadecode(data(j).(N_('_ArrayZipSize_')),opt);
            end
	    dims=data(j).(N_('_ArrayZipSize_'))(:)';
            if(iscell(dims))
                dims=cell2mat(dims);
            end
            if(length(dims)==1)
                 dims=[1 dims];
            end
            ndata=reshape(ndata(:),fliplr(dims));
            ndata=permute(ndata,ndims(ndata):-1:1);
        end
        iscpx=0;
        if(isfield(data,N_('_ArrayIsComplex_')) && isstruct(data(j).(N_('_ArrayIsComplex_'))) )
                data(j).(N_('_ArrayIsComplex_'))=jdatadecode(data(j).(N_('_ArrayIsComplex_')),opt);
        end
        if(isfield(data,N_('_ArrayIsComplex_')) && data(j).(N_('_ArrayIsComplex_')) )
                iscpx=1;
        end
        iscol=0;
        if(isfield(data,N_('_ArrayOrder_')))
            arrayorder=data(j).(N_('_ArrayOrder_'));
            if(~isempty(arrayorder) && (arrayorder(1)=='c' || arrayorder(1)=='C'))
                iscol=1;
            end
        end
        if(isfield(data,N_('_ArrayIsSparse_')) && isstruct(data(j).(N_('_ArrayIsSparse_'))) )
                data(j).(N_('_ArrayIsSparse_'))=jdatadecode(data(j).(N_('_ArrayIsSparse_')),opt);
        end
        if(isfield(data,N_('_ArrayIsSparse_')) && data(j).(N_('_ArrayIsSparse_')))
                if(isfield(data,N_('_ArraySize_')))
                    if(isstruct(data(j).(N_('_ArraySize_'))))
                        data(j).(N_('_ArraySize_'))=jdatadecode(data(j).(N_('_ArraySize_')),opt);
                    end
                    dim=data(j).(N_('_ArraySize_'))(:)';
                    if(iscell(dim))
                        dim=cell2mat(dim);
                    end
                    dim=double(dim);
		    if(length(dim)==1)
			dim=[1 dim];
		    end
                    if(iscpx)
                        ndata(end-1,:)=complex(ndata(end-1,:),ndata(end,:));
                    end
                    if isempty(ndata)
                        % All-zeros sparse
                        ndata=sparse(dim(1),prod(dim(2:end)));
                    elseif dim(1)==1
                        % Sparse row vector
                        ndata=sparse(1,ndata(1,:),ndata(2,:),dim(1),prod(dim(2:end)));
                    elseif dim(2)==1
                        % Sparse column vector
                        ndata=sparse(ndata(1,:),1,ndata(2,:),dim(1),prod(dim(2:end)));
                    else
                        % Generic sparse array.
                        ndata=sparse(ndata(1,:),ndata(2,:),ndata(3,:),dim(1),prod(dim(2:end)));
                    end
                else
                    if(iscpx && size(ndata,2)==4)
                        ndata(3,:)=complex(ndata(3,:),ndata(4,:));
                    end
                    ndata=sparse(ndata(1,:),ndata(2,:),ndata(3,:));
                end
        elseif(isfield(data,N_('_ArrayShape_')))
                if(isstruct(data(j).(N_('_ArrayShape_'))))
                    data(j).(N_('_ArrayShape_'))=jdatadecode(data(j).(N_('_ArrayShape_')),opt);
                end
                if(iscpx)
                    if(size(ndata,1)==2)
                        dim=size(ndata);
                        dim(end+1)=1;
                        arraydata=reshape(complex(ndata(1,:),ndata(2,:)),dim(2:end));
                    else
                        error('The first dimension must be 2 for complex-valued arrays');
                    end
                else
                    arraydata=data.(N_('_ArrayData_'));
                end
                shapeid=data.(N_('_ArrayShape_'));
                if(isfield(data,N_('_ArrayZipSize_')))
                        datasize=data.(N_('_ArrayZipSize_'));
                        if(iscell(datasize))
                            datasize=cell2mat(datasize);
                        end
                        datasize=double(datasize);
                        if(iscpx)
                            datasize=datasize(2:end);
                        end
                else
                        datasize=size(arraydata);
                end
                if(isstruct(data(j).(N_('_ArraySize_'))))
                    data(j).(N_('_ArraySize_'))=jdatadecode(data(j).(N_('_ArraySize_')),opt);
                end
                arraysize=data.(N_('_ArraySize_'));

                if(iscell(arraysize))
                    arraysize=cell2mat(arraysize);
                end
                arraysize=double(arraysize);
                if(ischar(shapeid))
                        shapeid={shapeid};
                end
                arraydata=double(arraydata).';
                if(strcmpi(shapeid{1},'diag'))
                        ndata=spdiags(arraydata(:),0,arraysize(1),arraysize(2));
                elseif(strcmpi(shapeid{1},'upper') || strcmpi(shapeid{1},'uppersymm'))
                        ndata=zeros(arraysize);
                        ndata(triu(true(size(ndata)))')=arraydata(:);
                        if(strcmpi(shapeid{1},'uppersymm'))
                            ndata(triu(true(size(ndata))))=arraydata(:);
                        end
                        ndata=ndata.';
                elseif(strcmpi(shapeid{1},'lower') || strcmpi(shapeid{1},'lowersymm'))
                        ndata=zeros(arraysize);
                        ndata(tril(true(size(ndata)))')=arraydata(:);
                        if(strcmpi(shapeid{1},'lowersymm'))
                            ndata(tril(true(size(ndata))))=arraydata(:);
                        end
                        ndata=ndata.';
                elseif(strcmpi(shapeid{1},'upperband') || strcmpi(shapeid{1},'uppersymmband'))
                        if(length(shapeid)>1 && isvector(arraydata))
                            datasize=double([shapeid{2}+1, prod(datasize)/(shapeid{2}+1)]);
                        end
                        ndata=spdiags(reshape(arraydata,min(arraysize),datasize(1)),-datasize(1)+1:0,arraysize(2),arraysize(1)).';
                        if(strcmpi(shapeid{1},'uppersymmband'))
                            diagonal=diag(ndata);
                            ndata=ndata+ndata.';
                            ndata(1:arraysize(1)+1:end)=diagonal;
                        end
                elseif(strcmpi(shapeid{1},'lowerband') || strcmpi(shapeid{1},'lowersymmband'))
                        if(length(shapeid)>1 && isvector(arraydata))
                            datasize=double([shapeid{2}+1, prod(datasize)/(shapeid{2}+1)]);
                        end
                        ndata=spdiags(reshape(arraydata,min(arraysize),datasize(1)),0:datasize(1)-1,arraysize(2),arraysize(1)).';
                        if(strcmpi(shapeid{1},'lowersymmband'))
                            diagonal=diag(ndata);
                            ndata=ndata+ndata.';
                            ndata(1:arraysize(1)+1:end)=diagonal;
                        end
                elseif(strcmpi(shapeid{1},'band'))
                        if(length(shapeid)>1 && isvector(arraydata))
                            datasize=double([shapeid{2}+shapeid{3}+1, prod(datasize)/(shapeid{2}+shapeid{3}+1)]);
                        end
                        ndata=spdiags(reshape(arraydata,min(arraysize),datasize(1)),double(shapeid{2}):-1:-double(shapeid{3}),arraysize(1),arraysize(2));
                elseif(strcmpi(shapeid{1},'toeplitz'))
                        arraydata=reshape(arraydata,flipud(datasize(:))');
                        ndata=toeplitz(arraydata(1:arraysize(1),2),arraydata(1:arraysize(2),1));
                end
                if(opt.fullarrayshape && issparse(ndata))
                        ndata=cast(full(ndata),data(j).(N_('_ArrayType_')));
                end
        elseif(isfield(data,N_('_ArraySize_')))
            if(isstruct(data(j).(N_('_ArraySize_'))))
                data(j).(N_('_ArraySize_'))=jdatadecode(data(j).(N_('_ArraySize_')),opt);
            end
            if(iscpx)
                ndata=complex(ndata(1,:),ndata(2,:));
            end
            if(format>1.9 && iscol==0)
                data(j).(N_('_ArraySize_'))=data(j).(N_('_ArraySize_'))(end:-1:1);
            end
            dims=data(j).(N_('_ArraySize_'))(:)';
            if(iscell(dims))
                dims=cell2mat(dims);
            end
	    if(length(dims)==1)
		dims=[1 dims];
	    end
            ndata=reshape(ndata(:),dims(:)');
            if(format>1.9 && iscol==0)
                ndata=permute(ndata,ndims(ndata):-1:1);
            end
        end
        newdata{j}=ndata;
      end
      if(len==1)
          newdata=newdata{1};
      end
    end

    %% handle table data
    if(isfield(data,N_('_TableRecords_')))
        newdata=cell(len,1);
        for j=1:len
            ndata=data(j).(N_('_TableRecords_'));
            if(iscell(ndata))
                if(iscell(ndata{1}))
                    rownum=length(ndata);
                    colnum=length(ndata{1});
                    nd=cell(rownum, colnum);
                    for i1=1:rownum
                        for i2=1:colnum
                            nd{i1,i2}=ndata{i1}{i2};
                        end
                    end
                    newdata{j}=cell2table(nd);
                else
                    newdata{j}=cell2table(ndata);
                end
            else
                newdata{j}=array2table(ndata);
            end
            if(isfield(data(j),N_('_TableRows_'))&& ~isempty(data(j).(N_('_TableRows_'))))
                newdata{j}.Properties.RowNames=data(j).(N_('_TableRows_'))(:);
            end
            if(isfield(data(j),N_('_TableCols_')) && ~isempty(data(j).(N_('_TableCols_'))))
                newdata{j}.Properties.VariableNames=data(j).(N_('_TableCols_'));
            end
        end
        if(len==1)
            newdata=newdata{1};
        end
    end

    %% handle map data
    if(isfield(data,N_('_MapData_')))
        newdata=cell(len,1);
        for j=1:len
            key=cell(1,length(data(j).(N_('_MapData_'))));
            val=cell(size(key));
            for k=1:length(data(j).(N_('_MapData_')))
                key{k}=data(j).(N_('_MapData_')){k}{1};
                val{k}=jdatadecode(data(j).(N_('_MapData_')){k}{2},opt);
            end
            ndata=containers.Map(key,val);
            newdata{j}=ndata;
        end
        if(len==1)
            newdata=newdata{1};
        end
    end

    %% handle graph data
    if(isfield(data,N_('_GraphNodes_')) && exist('graph','file') && exist('digraph','file'))
        newdata=cell(len,1);
        isdirected=1;
        for j=1:len
            nodedata=data(j).(N_('_GraphNodes_'));
            if(isstruct(nodedata))
                nodetable=struct2table(nodedata);
            elseif(isa(nodedata,'containers.Map'))
                nodetable=[keys(nodedata);values(nodedata)];
                if(strcmp(nodedata.KeyType,'char'))
                    nodetable=table(nodetable(1,:)',nodetable(2,:)','VariableNames',{'Name','Data'});
                else
                    nodetable=table(nodetable(2,:)','VariableNames',{'Data'});
                end
            else
                nodetable=table;
            end

            if(isfield(data,N_('_GraphEdges_')))
                edgedata=data(j).(N_('_GraphEdges_'));
            elseif(isfield(data,N_('_GraphEdges0_')))
                edgedata=data(j).(N_('_GraphEdges0_'));
                isdirected=0;
            elseif(isfield(data,N_('_GraphMatrix_')))
                edgedata=jdatadecode(data(j).(N_('_GraphMatrix_')),varargin{:});
            end

            if(exist('edgedata','var'))
                if(iscell(edgedata))
                    endnodes=edgedata(:,1:2);
                    endnodes=reshape([endnodes{:}],size(edgedata,1),2);
                    weight=cell2mat(edgedata(:,3:end));
                    edgetable=table(endnodes,[weight.Weight]','VariableNames',{'EndNodes','Weight'});

                    if(isdirected)
                        newdata{j}=digraph(edgetable,nodetable);
                    else
                        newdata{j}=graph(edgetable,nodetable);
                    end
                elseif(ndims(edgedata)==2 && isstruct(nodetable))
                    newdata{j}=digraph(edgedata,fieldnames(nodetable));
                end
            end
        end
        if(len==1)
            newdata=newdata{1};
        end
    end

    %% handle bytestream and arbitrary matlab objects
    if(isfield(data,N_('_ByteStream_')) && isfield(data,N_('_DataInfo_')))
        newdata=cell(len,1);
        for j=1:len
            if(isfield(data(j).(N_('_DataInfo_')),'MATLABObjectClass'))
                if(needbase64)
                    newdata{j}=getArrayFromByteStream(base64decode(data(j).(N_('_ByteStream_'))));
                else
                    newdata{j}=getArrayFromByteStream(data(j).(N_('_ByteStream_')));
                end
            end
        end
        if(len==1)
            newdata=newdata{1};
        end
    end

    %% handle data link
    if(opt.maxlinklevel>0 && isfield(data,N_('_DataLink_')))
        if(ischar(data.(N_('_DataLink_'))))
            datalink=data.(N_('_DataLink_'));
            if(regexp(datalink,'\:\$'))
                ref=regexp(datalink, '^(?<proto>[a-zA-Z]+://)*(?<path>.+)(?<delim>\:)()*(?<jsonpath>(?<=:)\$\d*\.*.*)*', 'names');
            else
                ref=regexp(datalink, '^(?<proto>[a-zA-Z]+://)*(?<path>.+)(?<delim>\:)*(?<jsonpath>(?<=:)\$\d*\..*)*', 'names');
            end
            if(~isempty(ref.path))
                uripath=[ref.proto ref.path];
                [fpath, fname, fext]=fileparts(uripath);
                opt.maxlinklevel=opt.maxlinklevel-1;
                switch(lower(fext))
                    case {'.json','.jnii','.jdt','.jdat','.jmsh','.jnirs'}
                        newdata=loadjson(uripath, opt);
                    case {'.bjd' ,'.bnii','.jdb','.jbat','.bmsh','.bnirs', '.jamm'}
                        newdata=loadbj(uripath, opt);
                    case {'.ubj'}
                        newdata=loadubjson(uripath, opt);
                    case {'.msgpack'}
                        newdata=loadmsgpack(uripath, opt);
                    case {'.h5','.hdf5','.snirf'}  % this requires EasyH5 toolbox
                        newdata=loadh5(uripath, opt);
                    otherwise
                        % _DataLink_ url does not specify type, assuming JSON format
                        if(regexpi(datalink,'^\s*(http|https|ftp|file)://'))
                            newdata=loadjson(uripath, opt);
                        else
                            warning('_DataLink_ url is not supported')
                        end
                end
                if(~isempty(ref.jsonpath))
                    newdata=getfromjsonpath(newdata,ref.jsonpath);
                end
            end
        end
    end

    %% subfunctions
    function escaped=N_(str)
      escaped=[prefix str];
    end
end