function varargout = process_channel_addloc( varargin )
% PROCESS_CHANNEL_ADDLOC: Import a raw file in the database.

% @=============================================================================
% 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, 2015-2023

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % ===== EEG DEFAULTS =====
    strList = {''};
    % Get registered Brainstorm EEG defaults
    bstDefaults = bst_get('EegDefaults');
    % Build a list of strings representing all the defaults
    for iGroup = 1:length(bstDefaults)
        for iDef = 1:length(bstDefaults(iGroup).contents)
            strList{end+1} = [bstDefaults(iGroup).name ': ' bstDefaults(iGroup).contents(iDef).name];
        end
    end

    % ===== PROCESS =====
    % Description the process
    sProcess.Comment     = 'Add EEG positions';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = {'Import', 'Channel file'};
    sProcess.Index       = 36;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Epilepsy?highlight=%28Add+EEG+positions%29#Access_the_recordings';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data', 'raw'};
    sProcess.OutputTypes = {'data', 'raw'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;
    % Option: File to import
    sProcess.options.channelfile.Comment = 'File to import:';
    sProcess.options.channelfile.Type    = 'filename';
    sProcess.options.channelfile.Value   = {...
        '', ...                                % Filename
        '', ...                                % FileFormat
        'open', ...                            % Dialog type: {open,save}
        'Import channel file', ...             % Window title
        'ImportChannel', ...                   % LastUsedDir: {ImportData,ImportChannel,ImportAnat,ExportChannel,ExportData,ExportAnat,ExportProtocol,ExportImage,ExportScript}
        'single', ...                          % Selection mode: {single,multiple}
        'files_and_dirs', ...                  % Selection mode: {files,dirs,files_and_dirs}
        bst_get('FileFilters', 'channel'), ... % Get all the available file formats
        'ChannelIn'};                          % DefaultFormats
    % Option: Default channel files
    sProcess.options.usedefault.Comment = 'Or use default:';
    sProcess.options.usedefault.Type    = 'combobox_label';
    sProcess.options.usedefault.Value   = {'', cat(1, strList, strList)};
    % Fix units
    sProcess.options.fixunits.Comment = 'Fix distance units automatically';
    sProcess.options.fixunits.Type    = 'checkbox';
    sProcess.options.fixunits.Value   = 1;
    % Apply vox2ras transformation
    sProcess.options.vox2ras.Comment    = 'Apply voxel=>subject transformation from the MRI';
    sProcess.options.vox2ras.Type       = 'checkbox';
    sProcess.options.vox2ras.Value      = 1;           % If value is set to 2 programatically, then it also removes the MRI coregistration (see process_import_bids)
    sProcess.options.vox2ras.Controller = 'Vox2ras';
    % File selection options
    SelectOptions = {...
        '', ...                            % Filename
        '', ...                            % FileFormat
        'open', ...                        % Dialog type: {open,save}
        'Reference MRI...', ...            % Window title
        'ImportAnat', ...                  % LastUsedDir: {ImportData,ImportChannel,ImportAnat,ExportChannel,ExportData,ExportAnat,ExportProtocol,ExportImage,ExportScript}
        'single', ...                      % Selection mode: {single,multiple}
        'files', ...                       % Selection mode: {files,dirs,files_and_dirs}
        {{'_subjectimage'}, 'Volume from Brainstorm database (*subjectimage*.mat)', 'BST'}, ... % Accept only files from the database
        'MriIn'};                          % DefaultFormats: {ChannelIn,DataIn,DipolesIn,EventsIn,MriIn,NoiseCovIn,ResultsIn,SspIn,SurfaceIn,TimefreqIn
    % Option: MRI file
    sProcess.options.mrifile.Comment = 'Reference MRI:';
    sProcess.options.mrifile.Type    = 'filename';
    sProcess.options.mrifile.Value   = SelectOptions;
    sProcess.options.mrifile.Class   = 'Vox2ras';
    % Option: Fiducials
    sProcess.options.fiducials.Comment = 'Anatomical fiducials';
    sProcess.options.fiducials.Type    = 'label';
    sProcess.options.fiducials.Value   = [];
    sProcess.options.fiducials.Hidden  = 1;
end

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

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputs) %#ok<DEFNU>
    OutputFiles = {};
    ChannelMat = [];

    % ===== LOAD SELECTED FILE =====
    % Get filename to import
    ChannelFile = sProcess.options.channelfile.Value{1};
    FileFormat  = sProcess.options.channelfile.Value{2};

    % HANDLING ISSUE #591: https://github.com/brainstorm-tools/brainstorm3/issues/591
    % The list of default caps is changing between versions of Brainstorm, therefore the index of a "combobox" option can't be considered a reliable information.
    % On 6-Jan-2022: The option "usedefault" was changed from type "combobox" to "combobox_label" and the use of previous syntax is now an error.
    % Users with existing scripts will get an error and will be requested to update their scripts.
    if isempty(ChannelFile) && ~ischar(sProcess.options.usedefault.Value{1})
        bst_report('Error', sProcess, [], [...
            'On 6-Jan-2023, the option "usedefault" of process_channel_add loc was changed from type "combobox" to "combobox_label".' 10 ...
            'This parameter was previously an integer, indicating an index in a list that unfortunately changes across versions of Brainstorm.' 10 ...
            'The value now must be a string, which points at a specific default EEG cap with no amibiguity.' 10 10 ...
            'Scripts generated before 30-Jun-2022 and executed with a version of Brainstorm posterior to 30-Jun-2022' 10 ...
            'might have been selecting the wrong EEG cap, and should be fixed and executed again.' 10 10 ...
            'If you get this error, you must edit your processing script (or saved pipeline):' 10 ...
            'Use the pipeline editor to generate a new script to call the process "Add EEG position".' 10 10 ...
            'More information in GitHub issue #591: ' 10 ...
            'https://github.com/brainstorm-tools/brainstorm3/issues/591']);
        return
    end

    % Get other options
    if isfield(sProcess.options, 'fixunits') && isfield(sProcess.options.fixunits, 'Value')
        isFixUnits = sProcess.options.fixunits.Value;
    else
        isFixUnits = 1;
    end
    if isfield(sProcess.options, 'vox2ras') && isfield(sProcess.options.vox2ras, 'Value')
        isApplyVox2ras = sProcess.options.vox2ras.Value;
    else
        isApplyVox2ras = 1;
    end
    % Get reference MRI
    if isfield(sProcess.options, 'mrifile') && isfield(sProcess.options.mrifile, 'Value')
        MriFile = sProcess.options.mrifile.Value{1};
    else
        MriFile = [];
    end
    % Get fiducials
    if isfield(sProcess.options, 'fiducials') && isfield(sProcess.options.fiducials, 'Value') && ~isempty(sProcess.options.fiducials.Value)
        sFid = sProcess.options.fiducials.Value;
        isApplyVox2ras = 0;
    else
        sFid = [];
    end

    % Get channel studies
    [tmp, iChanStudies] = bst_get('ChannelForStudy', [sInputs.iStudy]);
    iChanStudies = unique(iChanStudies);
    % Load file
    if ~isempty(ChannelFile)
        ChannelMat = import_channel(iChanStudies, ChannelFile, FileFormat, [], [], 0, isFixUnits, isApplyVox2ras, MriFile);
        % Apply fiducials
        if ~isempty(sFid) && isfield(sFid, 'NAS') && (length(sFid.NAS)==3) && isfield(sFid, 'LPA') && (length(sFid.LPA)==3) && isfield(sFid, 'RPA') && (length(sFid.RPA)==3) && ~(isequal(sFid.NAS(:), [0;0;0]) && isequal(sFid.LPA(:), [0;0;0]) && isequal(sFid.RPA(:), [0;0;0]))
            ChannelMat.SCS.NAS = sFid.NAS;
            ChannelMat.SCS.LPA = sFid.LPA;
            ChannelMat.SCS.RPA = sFid.RPA;
            ChannelMat = channel_detect_type(ChannelMat, 1);
        end
    end

    % ===== USE DEFAULT =====
    if isempty(ChannelFile)
        % Get registered Brainstorm EEG defaults
        bstDefaults = bst_get('EegDefaults');
        % Get default channel file
        strDef = sProcess.options.usedefault.Value{1};
        % If there is something selected
        if ~isempty(strDef)
            % Format: "group: name"
            cDef   = strtrim(str_split(strDef, ':'));
            % Find the selected group in the list
            iGroup = find(strcmpi(cDef{1}, {bstDefaults.name}));
            % If group is found
            if ~isempty(iGroup)
                % Find the selected default in the list
                iDef = find(strcmpi(cDef{2}, {bstDefaults(iGroup).contents.name}));
                % If default was found
                if ~isempty(iDef)
                    ChannelFile = bstDefaults(iGroup).contents(iDef).fullpath;
                    isMni = strcmpi(bstDefaults(iGroup).name, 'ICBM152');
                end
            end
        end
        % If nothing was selected (file or default)
        if isempty(ChannelFile)
            bst_report('Error', sProcess, [], 'No channel file selected.');
            return
        end
        % Load channel file
        ChannelMat = in_bst_channel(ChannelFile);
    else
        isMni = 0;
    end

    % ===== ADD POSITIONS =====
    % Add channel positions
    if ~isempty(ChannelMat)
        channel_add_loc(iChanStudies, ChannelMat, 0, isMni);
    else
        bst_report('Warning', sProcess, [], 'No channel positions added.');
    end

    % Return input files
    OutputFiles = {sInputs.FileName};
end


classdef NomadDirectionTypeEnum < matlab.mixin.SetGet
    %NomadDirectionTypeEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        Ortho1('ortho 1', 'Ortho 1')
        Ortho2('ortho 2', 'Ortho 2')
        OrthoN1('ortho n+1', 'Ortho N+1')
        OrthoN1Quad('ortho n+1 quad', 'Ortho N+1 Quad')
        OrthoN1Neg('ortho n+1 neg', 'Ortho N+1 Neg')
        Ortho('ortho', 'Ortho')
        Ortho2N('ortho 2n', 'Ortho 2N')

        LT1('lt 1', 'LT 1')
        LT2('lt 2', 'LT 2')
        LT2N('lt 2n', 'LT 2N')
        LTN1('lt n+1', 'LT N+1')

        GPSBin('gps binary', 'GPS Binary')
        GPS2NStatic('gps 2n static', 'GPS 2N Static')
        GPS2NRand('gps 2n rand', 'GPS 2N Random')
        GPSN1StaticUniform('gps n+1 static uniform', 'GPS N+1 Static Uniform')
        GPSN1Static('gps n+1 static', 'GPS N+1 Static')
        GPSN1RandUniform('gps n+1 rand uniform', 'GPS N+1 Random Uniform')
        GPSN1Rand('gps n+1 rand', 'GPS N+1 Random')
        GPS1Static('gps 1 static', 'GPS 1 Static')
    end

    properties
        optionStr char = ''
        name char = '';
    end

    methods
        function obj = NomadDirectionTypeEnum(optionStr, name)
            obj.optionStr = optionStr;
            obj.name = name;
        end
    end

    methods(Static)
        function listBoxStr = getListBoxStr()
            m = enumeration('NomadDirectionTypeEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('NomadDirectionTypeEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('NomadDirectionTypeEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


function this = init_processing_step(this, module, varargin)
% initializes next processing step by creating folders for version tracking,
% shuffling data, and updating processing parameters
%
%   MrSeries = init_processing_step(MrSeries, module)
%
% This is a method of class MrSeries.
%
% IN
%   module      'realign', 'smooth', ...
%
% OUT
%
%   side effects:
%   new folder (with current data):
%       dirObject/<nProcessingSteps+1>_moduleName
%   parameters.processingLog
%   nProcessingSteps
%
% EXAMPLE
%   init_processing_step
%
%   See also MrSeries

% Author:   Saskia Klein & Lars Kasper
% Created:  2014-07-01
% Copyright (C) 2014 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public Licence (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

% NOTE: for each new processing step added here, it has to be decided which
% (input, raw, unprocessed) files are saved additionally

itemsSave = this.parameters.save.items;
doSave = ~strcmpi(itemsSave, 'none');
doSaveRaw = ismember(itemsSave, {'all'});
doSaveNifti = ismember(itemsSave, {'nii', 'all', 'processed'});
doSaveObject = ismember(itemsSave, {'object', 'all', 'processed'});

% set file-saving behavior of MrImage to keep disk files
this.data.parameters.save.keepCreatedFiles = ...
    1 ; % keeps files here, cleanup will happen in finish_processing_step

pathSaveRoot = this.parameters.save.path;

% save initial, unprocessed data
isFirstProcessingStep = ~this.nProcessingSteps;
if isFirstProcessingStep && doSave
    dirProcessing = sprintf('%03d_%s', this.nProcessingSteps, 'unprocessed');
    pathProcessing = fullfile(pathSaveRoot, dirProcessing);
    mkdir(pathProcessing);
    this.data.parameters.save.path = pathProcessing;
    this.data.parameters.save.fileName = 'data.nii';

    % save data (MrImage file)
    if doSaveNifti
        this.data.save();
    end

    % strip and save object as well
    if doSaveObject
        fileObject = fullfile(pathProcessing, 'MrObject.mat');
        MrObject = this.copyobj('exclude', 'data'); % copies object without data
        save(fileObject, 'MrObject');
    end
end

% specify new directory to save data here
this.nProcessingSteps   = this.nProcessingSteps + 1;
dirProcessing           = sprintf('%03d_%s', this.nProcessingSteps, module);
pathProcessing          = fullfile(pathSaveRoot, dirProcessing);

this.processingLog{end+1,1} = dirProcessing;

% module-specific adaptations, e.g. data copying

% for all matlabbatches where additional spm output files are saved
hasMatlabbatch = ismember(module, this.get_all_matlabbatch_methods());

% for all matlabbatches, where data is needed as raw.nii before job start
doesNeedDataNifti = ismember(module, {'realign', 'smooth', ...
    'specify_and_estimate_1st_level'});

if doSave || hasMatlabbatch
    mkdir(pathProcessing);
end

if doesNeedDataNifti % data has to be written to disk before running spm_jobman, prepare file-names!
    this.data.parameters.save.path = pathProcessing;
end

switch module
    case 'specify_and_estimate_1st_level'
        % save raw data
        this.data.save;

    case 'analyze_rois'
        % dummy image for path transfer
        inputDummyImage = varargin{1};
        inputDummyImage.parameters.save.path = pathProcessing;

    case 'compute_masks'
        inputImages = varargin{1};
        nImages = numel(inputImages);

        % set paths, save raw input files and prefix file names with "mask"... for all input files
        for iImage = 1:nImages
            inputImages{iImage}.parameters.save.path = pathProcessing;
            inputImages{iImage}.parameters.save.fileName = ...
                tapas_uniqc_prefix_files(inputImages{iImage}.parameters.save.fileName, ...
                'mask', 0, 1);
            inputImages{iImage}.save;
        end

    case 'compute_stat_images'

        % determine output file names, e.g. mean.nii and path of processing
        % directory
        [handleImageArray, nameImageArray] = this.get_all_image_objects('stats');
        for iImage = 1:numel(handleImageArray)
            handleImageArray{iImage}.parameters.save.path = pathProcessing;
            handleImageArray{iImage}.parameters.save.fileName = ...
                [nameImageArray{iImage} '.nii'];
        end

    case 'compute_tissue_probability_maps'

        % adjust path of input image to make it save-able
        inputImage = varargin{1};
        inputImage.parameters.save.path = pathProcessing;
        inputImage.parameters.save.keepCreatedFiles = 'all';

    case 'coregister'
        transformedImage = varargin{1};
        equallyTransformedImages = varargin{2};
        inputImages = [{transformedImage};...
            equallyTransformedImages];

        % set save path
        nImages = numel(inputImages);
        for iImage = 1:nImages
            inputImages{iImage}.parameters.save.path = ...
                pathProcessing;
            inputImages{iImage}.parameters.save.keepCreatedFiles = 'all';
        end

    case 'realign'

    case 'smooth'

        % set file names and save path for statistical images
    case 't_filter'
        this.data.parameters.save.path = pathProcessing;
        this.data.parameters.save.keepCreatedFiles = 'all';
end

end


function whelp(classpath)
% Display help about the available options to the console.
%
% classpath - the full path to the class omiting 'weka'.
%
% Example: whelp classifiers.bayes.BayesNet

    eval(['weka.',classpath,'.main(''-h'')']);
end


function [seriesNameArray] = dispFileSeries(inputFilePath,varargin)
	% [bfSeriesNo] = getSeriesNoFromName(inputFilePath,bfSeriesName,varargin)
	%
	% Returns series number for Bio-Formats series with name given by user.
	%
	% Biafra Ahanonu
	% started: 2022.07.15 [08:10:16]
	%
	% Inputs
	% 	inputFilePath - Str: path to Bio-Formats compatible file.
	%
	% Outputs
	% 	bfSeriesNo - Int: series number (1-based indexing) matching the input series name. NaN is output if no series is found.
	%
	% Options (input as Name-Value with Name = options.(Name))
	% 	% File ID connection from calling bfGetReader(inputFilePath), this is to save time on larger files by avoiding opening the connection again.
	% 	options.fileIdOpen = '';

	% Changelog
		%
	% TODO
		%

	% ========================
	% File ID connection from calling bfGetReader(inputFilePath), this is to save time on larger files by avoiding opening the connection again.
	options.fileIdOpen = [];
	% get options
	options = ciapkg.io.getOptions(options,varargin);
	% disp(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	% ========================

	try
		% By default output NaN if no series found.
		seriesNameArray = {};

		if isempty(options.fileIdOpen)
			disp(['Opening connection to Bio-Formats file:' inputFilePath])
			startReadTime = tic;
			fileIdOpen = bfGetReader(inputFilePath);
			toc(startReadTime)
		else
			fileIdOpen = options.fileIdOpen;
		end
		omeMeta = fileIdOpen.getMetadataStore();

		nSeries = fileIdOpen.getSeriesCount();
		seriesNameArray = cell([1 nSeries]);
		disp('===')
		disp(['Series in file: ' inputFilePath])
		for seriesNo = 1:nSeries
			% Convert 1-based to 0-based indexing.
			thisStr = char(omeMeta.getImageName(seriesNo-1));
			seriesNameArray{seriesNo} = thisStr;
			disp([num2str(seriesNo) ': "' thisStr '"'])
		end
		disp('===')
	catch err
		disp(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		disp(repmat('@',1,7))
	end

	function [outputs] = nestedfxn_exampleFxn(arg)
		% Always start nested functions with "nestedfxn_" prefix.
		% outputs = ;
	end
end
function [outputs] = localfxn_exampleFxn(arg)
	% Always start local functions with "localfxn_" prefix.
	% outputs = ;
end


function lines = strflushright(lines, offset)
%STRFLUSHRIGHT Flush right each line of text.
%
%   STRFLUSHRIGHT(LINES, OFFSET) where LINES is a cell array of lines and
%   OFFSET is a non-negative integer, does a right flush of the text in each
%   line so the last character in each line is at the specified offset.  If
%   OFFSET is omitted, 72 is used.

%   Author:      Peter J. Acklam
%   Time-stamp:  2003-10-13 11:13:53 +0200
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   error(nargchk(1, 2, nargin));
   if nargin < 2
      offset = 72;
   end

   spc = ' ';
   tab = sprintf('\t');
   fmt = sprintf('%%%ds', offset);
   lines = lines(:);

   for i = 1:length(lines)
      k = find(lines{i} ~= spc & lines{i} ~= tab);
      if isempty(k)
         lines{i} = '';
      else
         lines{i} = sprintf(fmt, lines{i}(k(1):k(end)));
      end
   end


function updateSSHypothesis( aid )
%UPDATESSHYPOTHESIS Summary of this function goes here
%   Detailed explanation goes here
%matlabpool(2);
[~,b] = system('hostname');
fprintf('Running on %s\n',b);

% diaryfilename = sprintf('../diary/diary%03d.txt', aid);
% diary(diaryfilename);
% diary on;

addpath(genpath('/n/fs/sun360/panoParser/SceneParsing'));
cd '/n/fs/sun360/panoParser/SceneParsing';
folderName = './annotation/dataset/bedroom/';
% folderName = './annotation/dataset/living_room/';

load([folderName '/IMGLIST.mat']);
load([folderName '/ANNO_ALL.mat']);
fprintf('Data loaded\n');
testfile2 = [folderName IMGLIST(aid).name '/bottomupcuboid_P1.mat'];
if exist(testfile2, 'file')
	fprintf('Job: %d: Previously done^_^\n', aid);
	return;
end

anno_valid = false( 1, length(ANNO_ALL));
for i = 1:length(anno_valid)
    anno_valid(i) = ~isempty(ANNO_ALL(i).ANNO3D) && ANNO_ALL(i).ANNO3D.b_singleroom;
end

if ~anno_valid(aid)
    return;
end

rotImg = imread([IMGLIST(aid).small_imgname(1:end-9) 'rotate.png']);
fprintf('Image loaded\n');

SS = getSelectiveSearch(rotImg);

if exist(testfile2, 'file')
	fprintf('Job: %d: Previously done^_^\n', aid);
	return;
end

AllCuboid = regionBasedHypothesisFromSS(SS, 1024, 2048);

if exist(testfile2, 'file')
	fprintf('Job: %d: Previously done^_^\n', aid);
	return;
end

rectangle = rectDetectionFlexFromSS(SS, 1024, 2048);

if exist(testfile2, 'file')
	fprintf('Job: %d: Previously done^_^\n', aid);
	return;
end

AllCuboid_NEW = pruneCuboid(rotImg, AllCuboid);
rectangle_NEW = pruneRectangle(rotImg, rectangle);

load([folderName IMGLIST(aid).name '/bottomupcuboid.mat']);
fprintf('Old data loaded\n');

regionCuboid.views = [regionCuboid.views; AllCuboid_NEW.views];
regionCuboid.xyzBox = [regionCuboid.xyzBox; AllCuboid_NEW.xyzBox];
regionCuboid.score = [regionCuboid.score; AllCuboid_NEW.score];
regionCuboid.count = regionCuboid.count + AllCuboid_NEW.count;

for i = 1:6
    rectangle(i).highPixelBox = [rectangle(i).highPixelBox; rectangle_NEW(i).highPixelBox];
%     rectangle(i).count = rectangle(i).count + rectangle_NEW(i).count;
    rectangle(i).xyzBox = [rectangle(i).xyzBox; rectangle_NEW(i).xyzBox];
    rectangle(i).score = [rectangle(i).score; rectangle_NEW(i).score];
end

save([folderName IMGLIST(aid).name '/bottomupcuboid_P1.mat'], ...
            'rectangle', 'rectCuboid2', 'rectCuboid3', 'regionCuboid');
fprintf('save data for bottomcuboid_P1.mat\n');

%% move updatePruneRectDetBySegmentation
testfile2 = [folderName IMGLIST(aid).name '/rectangleSegScore_P1.mat'];
[ rect_score ] = getSegScrOfRect( rotImg, rectangle );
save(testfile2, 'rect_score');
fprintf('save data for rectangleSegScore_P1.mat\n');

end