% Script comes from Convolutional Pose Machine
function genJSON(dataset)

    addpath('util/jsonlab/');

    if(strcmp(dataset, 'MPI'))
        mat = load('../dataset/MPI/mpii_human_pose_v1_u12_1/mpii_human_pose_v1_u12_1.mat');
        RELEASE = mat.RELEASE;
        trainIdx = find(RELEASE.img_train);

        % in MPI: (0 - r ankle, 1 - r knee, 2 - r hip, 3 - l hip, 4 - l knee,
        %          5 - l ankle, 6 - pelvis, 7 - thorax, 8 - upper neck, 9 - head top,
        %          10 - r wrist, 11 - r elbow, 12 - r shoulder, 13 - l shoulder, 14 - l elbow, 15 - l wrist)"

        tompson = load('../dataset/MPI/Tompson_valid/detections');
        tompson_i_p = [tompson.RELEASE_img_index; tompson.RELEASE_person_index];

        count = 1;
        makeFigure = 0;
        validationCount = 0;

        for i = trainIdx
            numPeople = length(RELEASE.annolist(i).annorect);
            fprintf('image: %d (numPeople: %d) last: %d\n', i, numPeople, trainIdx(end));

            for p = 1:numPeople
                loc = find(sum(~bsxfun(@minus, tompson_i_p, [i;p]))==2, 1);
                if(~isempty(loc))
                    validationCount = validationCount + 1;
                    %fprintf('Tomspon''s validation! %d\n', validationCount);
                    isValidation = 1;
                else
                    isValidation = 0;
                end
                joint_all(count).dataset = 'MPI';
                joint_all(count).isValidation = isValidation;

                try % sometimes no annotation at all....
                    anno = RELEASE.annolist(i).annorect(p).annopoints.point;
                catch
                    continue;
                end

                % set image path
                %joint_all(count).img_paths = sprintf('dataset/MPI/images/%s', RELEASE.annolist(i).image.name);
                joint_all(count).img_paths = RELEASE.annolist(i).image.name;

                img = imread(['../dataset/MPI/images/', joint_all(count).img_paths]);
                [h,w,~] = size(img);
                %[h,w,~] = size(imread(['../dataset/MPI/images/', joint_all(count).img_paths]));

                joint_all(count).img_width = w;
                joint_all(count).img_height = h;
                joint_all(count).objpos = [RELEASE.annolist(i).annorect(p).objpos.x, RELEASE.annolist(i).annorect(p).objpos.y];
                % set part label: joint_all is (np-3-nTrain)

                % for this very center person
                for part = 1:length(anno)
                    joint_all(count).joint_self(anno(part).id+1, 1) = anno(part).x;
                    joint_all(count).joint_self(anno(part).id+1, 2) = anno(part).y;
                    try % sometimes no is_visible...
                        if(anno(part).is_visible == 0 || anno(part).is_visible == '0')
                            joint_all(count).joint_self(anno(part).id+1, 3) = 0;
                        else
                            joint_all(count).joint_self(anno(part).id+1, 3) = 1;
                        end
                    catch
                        joint_all(count).joint_self(anno(part).id+1, 3) = 1;
                    end
                end
                % pad it into 16x3
                dim_1 = size(joint_all(count).joint_self, 1);
                dim_3 = size(joint_all(count).joint_self, 3);
                pad_dim = 16 - dim_1;
                joint_all(count).joint_self = [joint_all(count).joint_self; zeros(pad_dim, 3, dim_3)];
                % set scale
                joint_all(count).scale_provided = RELEASE.annolist(i).annorect(p).scale;

                % for other person on the same image
                count_other = 1;
                joint_others = cell(0,0);
                for op = 1:numPeople
                    if(op == p), continue; end
                    try % sometimes no annotation at all....
                        anno = RELEASE.annolist(i).annorect(op).annopoints.point;
                    catch
                        continue;
                    end
                    joint_others{count_other} = zeros(16,3);
                    for part = 1:length(anno)
                        joint_all(count).joint_others{count_other}(anno(part).id+1, 1) = anno(part).x;
                        joint_all(count).joint_others{count_other}(anno(part).id+1, 2) = anno(part).y;
                        try % sometimes no is_visible...
                            if(anno(part).is_visible == 0 || anno(part).is_visible == '0')
                                joint_all(count).joint_others{count_other}(anno(part).id+1, 3) = 0;
                            else
                                joint_all(count).joint_others{count_other}(anno(part).id+1, 3) = 1;
                            end
                        catch
                            joint_all(count).joint_others{count_other}(anno(part).id+1, 3) = 1;
                        end
                    end
                    joint_all(count).scale_provided_other(count_other) = RELEASE.annolist(i).annorect(op).scale;
                    joint_all(count).objpos_other{count_other} = [RELEASE.annolist(i).annorect(op).objpos.x RELEASE.annolist(i).annorect(op).objpos.y];

                    count_other = count_other + 1;
                end

                if(makeFigure) % visualizing to debug
                    %imshow(joint_all(count).img_paths);
                    imshow(img);
                    hold on;
                    visiblePart = joint_all(count).joint_self(:,3) == 1;
                    invisiblePart = joint_all(count).joint_self(:,3) == 0;
                    plot(joint_all(count).joint_self(visiblePart, 1), joint_all(count).joint_self(visiblePart,2), 'gx');
                    plot(joint_all(count).joint_self(invisiblePart,1), joint_all(count).joint_self(invisiblePart,2), 'rx');
                    plot(joint_all(count).objpos(1), joint_all(count).objpos(2), 'cs');
                    if(~isempty(joint_all(count).joint_others))
                        for op = 1:size(joint_all(count).joint_others, 3)
                            visiblePart = joint_all(count).joint_others(:,3,op) == 1;
                            invisiblePart = joint_all(count).joint_others(:,3,op) == 0;
                            plot(joint_all(count).joint_others(visiblePart,1,op), joint_all(count).joint_others(visiblePart,2,op), 'mx');
                            plot(joint_all(count).joint_others(invisiblePart,1,op), joint_all(count).joint_others(invisiblePart,2,op), 'cx');
                        end
                    end
                    close all;
                end
                joint_all(count).annolist_index = i;
                joint_all(count).people_index = p;
                joint_all(count).numOtherPeople = length(joint_all(count).joint_others);
                count = count + 1;

                %if(count==10), break; endscale_provided
            end
            %if(count==10), break; end
        end
        opt.FileName = 'json/MPI_annotations.json';
        opt.FloatFormat = '%.3f';
        savejson('root', joint_all, opt);

    elseif(strcmp(dataset, 'LEEDS'))
        % in cpp: real scale = param_.target_dist()/meta.scale_self = (41/35)/scale_input
        targetDist = 41/35; % in caffe cpp file 41/35
        oriTrTe = load('../dataset/LEEDS/lsp_dataset/joints.mat');
        extTrain = load('../dataset/LEEDS/lspet_dataset/joints.mat');

        flag_showJoints = 0;
        flag_showScaledImg = 0;

        % in LEEDS:
        % 1  Right ankle
        % 2  Right knee
        % 3  Right hip
        % 4  Left hip
        % 5  Left knee
        % 6  Left ankle
        % 7  Right wrist
        % 8  Right elbow
        % 9  Right shoulder
        % 10 Left shoulder
        % 11 Left elbow
        % 12 Left wrist
        % 13 Neck
        % 14 Head top
        % 15,16 DUMMY
        % We want to comply to MPII: (1 - r ankle, 2 - r knee, 3 - r hip, 4 - l hip, 5 - l knee, 6 - l ankle, ..
        %                             7 - pelvis, 8 - thorax, 9 - upper neck, 10 - head top,
        %                             11 - r wrist, 12 - r elbow, 13 - r shoulder, 14 - l shoulder, 15 - l elbow, 16 - l wrist)
        ordering = [1 2 3, 4 5 6, 15 16, 13 14, 7 8 9, 10 11 12]; % should follow MPI 16 parts..?
        oriTrTe.joints(:,[15 16],:) = 0;
        oriTrTe.joints = oriTrTe.joints(:,ordering,:);
        oriTrTe.joints(3,:,:) = 1 - oriTrTe.joints(3,:,:);
        oriTrTe.joints = permute(oriTrTe.joints, [2 1 3]);

        extTrain.joints([15 16],:,:) = 0;
        extTrain.joints = extTrain.joints(ordering,:,:);

        count = 1;

        %path = {'lspet_dataset/images/im%05d.jpg', 'lsp_dataset/images/im%04d.jpg'};
        path = {'lspet_dataset/images/im%05d.png', 'lsp_dataset/images/im%04d.jpg'};
        %local_path = {'../dataset/LEEDS/lspet_dataset/images/im%05d.jpg', '../dataset/LEEDS/lsp_dataset/images/im%04d.jpg'};
        local_path = {'../dataset/LEEDS/lspet_dataset/images/im%05d.png', '../dataset/LEEDS/lsp_dataset/images/im%04d.jpg'};

        num_image = [10000, 1000];

        for dataset = 1:2
            for im = 1:num_image(dataset)
                path_this = sprintf(local_path{dataset}, im);
                if exist(path_this, 'file') == 0
                    continue
                end
                disp(im);
                disp(count);

                % trivial stuff for LEEDS
                joint_all(count).dataset = 'LEEDS';
                joint_all(count).isValidation = 0;
                joint_all(count).img_paths = sprintf(path{dataset}, im);
                joint_all(count).numOtherPeople = 0;
                joint_all(count).annolist_index = count;
                joint_all(count).people_index = 1;
                % joints and w, h
                if(dataset == 1)
                    %joint_this = extTrain.joints(:,:,im);
                    joint_this = extTrain.joints(:,:,count);
                else
                    joint_this = oriTrTe.joints(:,:,im);
                end

                [h,w,~] = size(imread(path_this));

                joint_all(count).img_width = w;
                joint_all(count).img_height = h;
                joint_all(count).joint_self = joint_this;
                % infer objpos
                invisible = (joint_all(count).joint_self(:,3) == 0);
                if(dataset == 1) %lspet is not tightly cropped
                    joint_all(count).objpos(1) = (min(joint_all(count).joint_self(~invisible, 1)) + max(joint_all(count).joint_self(~invisible, 1))) / 2;
                    joint_all(count).objpos(2) = (min(joint_all(count).joint_self(~invisible, 2)) + max(joint_all(count).joint_self(~invisible, 2))) / 2;
                else
                    joint_all(count).objpos(1) = w/2;
                    joint_all(count).objpos(2) = h/2;
                end
                % visualize
                if (flag_showJoints == 1)
                 figure(1); clf; imshow(path_this);
                 hold on;
                 plot(joint_all(count).joint_self([1 2 3], 1), joint_all(count).joint_self([1 2 3], 2), 'wx', 'Linewidth', 3);
                 plot(joint_all(count).joint_self([4 5 6], 1), joint_all(count).joint_self([4 5 6], 2), 'bx', 'Linewidth', 3);
                 plot(joint_all(count).joint_self([9 10], 1), joint_all(count).joint_self([9 10], 2), 'gx', 'Linewidth', 3);
                 plot(joint_all(count).joint_self([11 12 13], 1), joint_all(count).joint_self([11 12 13], 2), 'mx', 'Linewidth', 3);
                 plot(joint_all(count).joint_self([14 15 16], 1), joint_all(count).joint_self([14 15 16], 2), 'yx', 'Linewidth', 3);
                 plot(joint_all(count).joint_self(invisible, 1), joint_all(count).joint_self(invisible, 2), 'rx');
                 plot(joint_all(count).objpos(1), joint_all(count).objpos(2), 'cs');
                 pause;
                end
                % increase counter and display info
                count = count + 1;
                fprintf('processing %s\n', path_this);
            end
        end

        joint_all = insertMPILikeScale(joint_all, targetDist);

        if (flag_showScaledImg == 1)
         for i = 1:length(joint_all)
             path = ['../dataset/LEEDS/', joint_all(i).img_paths];
             figure(1); clf;
             img = imread(path);
             scale_in_cpp = targetDist/joint_all(i).scale_provided;
             img = imresize(img, scale_in_cpp);
             img = [zeros(400,size(img,2),3); img];
             img = [zeros(size(img,1),400,3), img];
             img = [img; zeros(400,size(img,2),3)];
             img = [img, zeros(size(img,1),400,3)];
             imshow(img);
             hold on;
             fprintf('scale: %f\n', scale_in_cpp);
             objpos = joint_all(i).objpos * scale_in_cpp + 400;
             plot(objpos(1), objpos(2), 'cs');
             line([objpos(1)-368/2, objpos(1)-368/2], [objpos(2)+368/2, objpos(2)-368/2], 'lineWidth', 3);
             line([objpos(1)+368/2, objpos(1)-368/2], [objpos(2)+368/2, objpos(2)+368/2], 'lineWidth', 3);
             line([objpos(1)+368/2, objpos(1)+368/2], [objpos(2)-368/2, objpos(2)+368/2], 'lineWidth', 3);
             line([objpos(1)-368/2, objpos(1)+368/2], [objpos(2)-368/2, objpos(2)-368/2], 'lineWidth', 3);
             pause;
         end
        end

        opt.FileName = 'json/LEEDS_annotations.json';
        opt.FloatFormat = '%.3f';
        savejson('root', joint_all, opt);

    elseif(strcmp(dataset, 'FLIC'))
        % note FLIC is OC
        targetDist = 41/35;
        constant = 0.0110;
        annotation = load('../dataset/FLIC/examples.mat');
        count_flip = 0;
        anno = {annotation.examples.filepath};
        [~,~,IC] = unique(anno);

        count = 1;
        for i = 1:length(annotation.examples)
            if(annotation.examples(i).istest)
                continue;
            end
            fprintf('FLIC images %d, conut = %d\n', i, count);
            joint_all(count).dataset = 'FLIC';
            joint_all(count).isValidation = 0;

            img_path = sprintf('images/%s', annotation.examples(i).filepath);
            joint_all(count).img_paths = img_path;

            current_IC = IC(i);
            fellow_idx = find(IC == current_IC);
            fellow_idx = setdiff(fellow_idx, i);

            joint_all(count).numOtherPeople = length(fellow_idx);
            joint_all(count).annolist_index = i;
            joint_all(count).people_index = 1;

            coords = annotation.examples(i).coords;
            coords(isnan(coords)) = [];
            coords = reshape(coords, [2 11]);
            coords(:,[9 10]) = [];
            coords = coords';
            coords = [coords, ones(9,1)];

            if(coords(4,1) > coords(1,1))
                coords([1 2 3 4 5 6 7 8],:) = coords([4 5 6 1 2 3 8 7],:);
                count_flip = count_flip + 1;
            end

            joint_all(count).joint_self = coords;

            img = imread(sprintf('../dataset/FLIC/%s', img_path));

            for k = 1:length(fellow_idx)
                coords_fellow = annotation.examples(fellow_idx(k)).coords;
                coords_fellow(isnan(coords_fellow)) = [];
                coords_fellow = reshape(coords_fellow, [2 11]);
                coords_fellow(:,[9 10]) = [];
                coords_fellow = coords_fellow';
                coords_fellow = [coords_fellow, ones(9,1)];
                if(coords_fellow(4,1) > coords_fellow(1,1))
                    coords_fellow([1 2 3 4 5 6 7 8],:) = coords_fellow([4 5 6 1 2 3 8 7],:);
                end
                box = annotation.examples(fellow_idx(k)).torsobox;
                torso_height = box(4) - box(2);
                scale = constant*torso_height;

                joint_all(count).joint_others{k} = coords_fellow;
                joint_all(count).scale_provided_other(k) = scale;
                joint_all(count).objpos_other{k} = [(box(1)+box(3))/2, (box(2)*0.7 + box(4)*0.3)];
            end

            joint_all(count).img_width = size(img, 2);
            joint_all(count).img_height = size(img, 1);

%             imshow(img); hold on;
%             plot(coords(:,1), coords(:,2), 'bx');
%             plot(coords(1:3,1), coords(1:3,2), 'rx');
%             plot(coords(end,1), coords(end,2), 'yx');
            box = annotation.examples(i).torsobox;
%             plot([box(1) box(1) box(3) box(3) box(1)], [box(2) box(4) box(4) box(2) box(2)]);
            torso_height = box(4) - box(2);

            joint_all(count).objpos = [(box(1)+box(3))/2, (box(2)*0.7 + box(4)*0.3)];

            % in cpp: real scale = param_.target_dist()/meta.scale_self = (41/35)/scale_input

            scale = constant * torso_height;
%             real_scale = targetDist/scale;
%             img = imresize(img, real_scale);
%
%             x = joint_all(i).objpos(1)*real_scale;
%             y = joint_all(i).objpos(2)*real_scale;
%             if(length(fellow_idx)~=0)
%                 clf; imshow(img); hold on;
%                 plot(joint_all(i).objpos(1)*real_scale, joint_all(i).objpos(2)*real_scale, 'cs');
%                 plot([x+184, x+184, x-184, x-184, x+184], [y+184 y-184 y-184 y+184 y+184], 'b-', 'LineWidth', 3);
%                 plot(coords(:,1)*real_scale, coords(:,2)*real_scale, 'rx');
%                 for k = 1:length(fellow_idx)
%                     plot(joint_all(i).objpos_other(k,1)*real_scale, joint_all(i).objpos_other(k,2)*real_scale, 'cs');
%                     coords = joint_all(i).joint_others(:,:,k);
%                     plot(coords(:,1)*real_scale, coords(:,2)*real_scale, 'yx');
%                 end
%             end

%             lm(i) = min(coords(:,1)*real_scale) - (x-184);
%             rm(i) = (x+184) - max(coords(:,1)*real_scale);
%             tm(i) = min(coords(:,2)*real_scale) - (y-184);
%             bm(i) = (y+184) - max(coords(:,2)*real_scale);

            joint_all(count).scale_provided = scale;
            count = count + 1;
        end
        fprintf('Flipped %d samples\n', count_flip);
        opt.FileName = 'json/FLIC_annotations.json';
        opt.FloatFormat = '%.3f';
        savejson('root', joint_all, opt);
    end

function out = parseFile(in)
    % out is like /media/posenas1//141215/141215_Pose1/Kinect//KINECTNODE1-December-15-2014-13-22-33/color/color-2561794.394.png
    % in should be /media/posenas1/Captures/poseMachineKinect/141215/141215_Pose1/Kinect//KINECTNODE1-December-15-2014-13-22-33/color/color-2561794.394.png
    out = strrep(in, '/media/posenas1/', '/media/posenas1/Captures/poseMachineKinect');

function joint_all = insertMPILikeScale(joint_all, targetDist)
    % calculate scales for each image first
    joints = cat(3, joint_all.joint_self);
    joints([7 8],:,:) = [];
    pa = [2 3 7, 5 4 7, 8 0, 10 11 7, 13 12 7];
    x = permute(joints(:,1,:), [3 1 2]);
    y = permute(joints(:,2,:), [3 1 2]);
    vis = permute(joints(:,3,:), [3 1 2]);
    validLimb = 1:14-1;

    x_diff = x(:, [1:7,9:14]) - x(:, pa([1:7,9:14]));
    y_diff = y(:, [1:7,9:14]) - y(:, pa([1:7,9:14]));
    limb_vis = vis(:, [1:7,9:14]) .* vis(:, pa([1:7,9:14]));
    l = sqrt(x_diff.^2 + y_diff.^2);

    for p = 1:14-1 % for each limb. reference: 7th limb, which is 7 to pa(7) (neck to head)
        valid_compare = limb_vis(:,7) .* limb_vis(:,p);
        ratio = l(valid_compare==1, p) ./ l(valid_compare==1, 7);
        r(p) = median(ratio(~isnan(ratio), 1));
    end

    numFiles = size(x_diff, 1);
    all_scales = zeros(numFiles, 1);

    boxSize = 368;
    psize = 64;
    nSqueezed = 0;

    for file = 1:numFiles %numFiles
        l_update = l(file, validLimb) ./ r(validLimb);
        l_update = l_update(limb_vis(file,:)==1);
        distToObserve = quantile(l_update, 0.75);
        scale_in_lmdb = distToObserve/35; % can't get too small. 35 is a magic number to balance to MPI
        scale_in_cpp = targetDist/scale_in_lmdb; % can't get too large to be cropped

        visibleParts = joints(:, 3, file);
        visibleParts = joints(visibleParts==1, 1:2, file);
        x_range = max(visibleParts(:,1)) - min(visibleParts(:,1));
        y_range = max(visibleParts(:,2)) - min(visibleParts(:,2));
        scale_x_ub = (boxSize - psize)/x_range;
        scale_y_ub = (boxSize - psize)/y_range;

        scale_shrink = min(min(scale_x_ub, scale_y_ub), scale_in_cpp);

        if scale_shrink ~= scale_in_cpp
            nSqueezed = nSqueezed + 1;
            fprintf('img %d: scale = %f %f %f shrink %d\n', file, scale_in_cpp, scale_shrink, min(scale_x_ub, scale_y_ub), nSqueezed);
        else
            fprintf('img %d: scale = %f %f %f\n', file, scale_in_cpp, scale_shrink, min(scale_x_ub, scale_y_ub));
        end

        joint_all(file).scale_provided = targetDist/scale_shrink; % back to lmdb unit
    end

    fprintf('total %d squeezed!\n', nSqueezed);


function c = set(c, prop_name, val)

   %SET Set properties for correlation object
   %   c = SET(c,prop_name,val)
   %
   %   see help correlation/get.m for valid property names

   % Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
   % $Date$
   % $Revision$

   switch upper(prop_name)
      case {'WAVEFORMS' 'WAVEFORM' 'WAVES'}
         c.W = reshape(val,length(val),1); % make 1 column
      case {'TRIG'}
         c.trig = reshape(val,length(val),1);
      case {'CORR'}
         c.corrmatrix = val;
      case {'LAG'}
         c.lags = val;
      case {'STAT'}
         c.stat = val;
      case {'LINK'}
         c.link = val;
      case {'CLUST'}
         c.clust = val;
      otherwise
         warning('can''t understand property name');
         help correlation/set
   end;
end


function tests = test_savestack(varargin)
%TEST_SAVESTACK  Test case for the file savestack
%
%   Test case for the file savestack

%   Example
%   test_savestack
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-09-27,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

tests = functiontests(localfunctions);

function test_SaveGrayStack(testCase)
% Test call of function without argument

D = load ('mri');
D = squeeze(D.D);

fName = 'testSaveGrayStack.tif';
if exist(fName, 'file')
    delete(fName);
end

savestack(D, fName);

info = imfinfo(fName);
assertEqual(testCase, 27, length(info));

delete(fName);

function test_SaveGraySlices(testCase)

D = load ('mri');
D = squeeze(D.D);

genericName = 'testSaveGraySlices*.tif';
patternName = 'testSaveGraySlices###.tif';

list = dir(genericName);
for i = 1:length(list)
    delete(list(i).name);
end

savestack(D, patternName);

list = dir(genericName);
assertEqual(testCase, 27, length(list));

list = dir(genericName);
for i = 1:length(list)
    delete(list(i).name);
end

function test_SaveRGBStack(testCase)
% Test call of function without argument

% create a 3D color image
mri = load ('mri');
mri = squeeze(mri.D);
bin = imclose(mri>0, ones(3, 3));
bnd = imdilate(imBoundary(bin), ones(3, 3));
ovr = imOverlay(mri*3, bnd);

fName = 'testSaveRGBStack.tif';
if exist(fName, 'file')
    delete(fName);
end

savestack(ovr, fName);

info = imfinfo(fName);
assertEqual(testCase, 27, length(info));

delete(fName);

function test_SaveRGBSlices(testCase)
% Test call of function without argument

% create a 3D color image
mri = load ('mri');
mri = squeeze(mri.D);
bin = imclose(mri > 0, ones(3, 3));
bnd = imdilate(imBoundary(bin), ones(3, 3));
ovr = imOverlay(mri*3, bnd);

genericName = 'testSaveRGBSlices*.tif';
patternName = 'testSaveRGBSlices###.tif';

list = dir(genericName);
for i = 1:length(list)
    delete(list(i).name);
end

savestack(ovr, patternName);

list = dir(genericName);
assertEqual(testCase, 27, length(list));

list = dir(genericName);
for i = 1:length(list)
    delete(list(i).name);
end

function test_SaveGrayStackMap(testCase)

D = load ('mri');
D = squeeze(D.D);

fName = 'testSaveGrayStackMap.tif';
if exist(fName, 'file')
    delete(fName);
end
map = jet(256);

savestack(D, map, fName);

info = imfinfo(fName);
assertEqual(testCase, 27, length(info));
assertFalse(testCase, isempty(info(1).Colormap));

delete(fName);

function test_SaveGraySlicesMap(testCase)

D = load ('mri');
D = squeeze(D.D);
map = jet(256);

genericName = 'testSaveGraySlicesMap*.tif';
patternName = 'testSaveGraySlicesMap###.tif';

list = dir(genericName);
for i = 1:length(list)
    delete(list(i).name);
end

savestack(D, map, patternName);

list = dir(genericName);
assertEqual(testCase, 27, length(list));
info = imfinfo(list(1).name);
assertFalse(testCase, isempty(info.Colormap));

list = dir(genericName);
for i = 1:length(list)
    delete(list(i).name);
end


function ASAversionchk(ASAcontrol)
%ASAVERSIONCHK Function version check
%   ASAVERSIONCHK(ASACONTROL) checks the compatibility of two functions
%   according to the information provided in the structure variable
%   ASACONTROL, if called from within the body of a m-file. If
%   incompatibility is detected, it halts execution and prints an error
%   message.
%
%   To apply a version check procedure when for example CALLER_FUNCTION
%   calls CALLED_FUNCTION, the latter must invoke ASAVERSIONCHK.
%   CALLER_FUNCTION must supply ASACONTROL as the last input argument
%   when it calls CALLED_FUNCTION. ASACONTROL must contain a (nested)
%   field named 'req_version.CALLED_FUNCTION' containing a version
%   identifier that defines the minimum version of CALLED_FUNCTION, as
%   required by CALLER_FUNCTION to guarantee consistency. In addition,
%   CALLED_FUNCTION must add two fields to ASACONTROL, named 'is_version'
%   and 'comp_version' prior to invoking ASAVERSIONCHK. Both fields
%   containing version identifiers, are used respectively to identify
%   CALLED_FUNCTION itself, with its own actual version, and to define
%   its downward compatibility with former versions. Operable version
%   check implementations can be found in all ARMASA main functions.
%
%   See also: ASACONTROL, STRUCT

caller_stack = dbstack;
stack_length = length(caller_stack);
if stack_length == 1
   error(ASAerr(7))
else
   [caller_path chk_caller] = fileparts(caller_stack(2).name);
   if stack_length >= 3
      [caller_path funct_caller] = fileparts(caller_stack(3).name);
   end
   if ~any(strcmp(fieldnames(ASAcontrol),'is_version'))|~any(strcmp(fieldnames(ASAcontrol),'comp_version'))
      error(ASAerr(22))
   end
end

if ~any(strcmp(fieldnames(ASAcontrol),'req_version'))
   chk = 0;
elseif ~any(strcmp(fieldnames(ASAcontrol.req_version),chk_caller))
   chk = 0;
else
   chk = 1;
   v = ASAcontrol.is_version;
   formatchk(v,'ASAcontrol.is_version',chk_caller);
   is_version = datenum(v(1),v(2),v(3),v(4),v(5),v(6));
   v = ASAcontrol.comp_version;
   formatchk(v,'ASAcontrol.comp_version',chk_caller);
   comp_version = datenum(v(1),v(2),v(3),v(4),v(5),v(6));
   v = getfield(ASAcontrol.req_version,chk_caller);
   formatchk(v,['ASAcontrol.req_version' chk_caller],chk_caller);
   req_version = datenum(v(1),v(2),v(3),v(4),v(5),v(6));
end

if isequal(chk,0)
   if stack_length > 2
      show_warn = 0; % <----  User adjustable: show_warn = 1 will enable warning messages
   else
      show_warn = 0;
   end
   if show_warn
      v = ASAcontrol.is_version;
      formatchk(v,'ASAcontrol.is_version',chk_caller);
      string = sprintf('%0.0f %0.0f %0.0f %0.0f %0.0f %0.0f',v);
      warning(ASAwarn(8,...
         {funct_caller;chk_caller;funct_caller;chk_caller;...
            string;chk_caller;funct_caller},ASAcontrol))
   end
elseif req_version > is_version
   if stack_length == 2
      error(ASAerr(3,chk_caller))
   else
      error(ASAerr(4,{chk_caller;funct_caller}))
   end
elseif req_version < comp_version
   if stack_length == 2
      error(ASAerr(5,chk_caller))
   else
      error(ASAerr(6,{chk_caller;funct_caller}))
   end
end

function formatchk(version,name_version,chk_caller)

if ~isnumeric(version) | ~isequal(length(version),6)
   error(ASAerr(10,{name_version;chk_caller}))
end

%Program history
%======================================================================
%
% Version                Programmer(s)          E-mail address
% -------                -------------          --------------
% [2000 12 30 20 0 0]    W. Wunderink           wwunderink01@freeler.nl


function success = test_most(verbose, exit_on_fail)
%TEST_MOST  Run all MOST tests.
%   TEST_MOST
%   TEST_MOST(VERBOSE)
%   TEST_MOST(VERBOSE, EXIT_ON_FAIL)
%   SUCCESS = TEST_MOST(...)
%
%   Runs all of the MOST tests. If VERBOSE is true (false by default),
%   it prints the details of the individual tests. If EXIT_ON_FAIL is true
%   (false by default), it will exit MATLAB or Octave with a status of 1
%   unless T_RUN_TESTS returns ALL_OK.
%
%   See also T_RUN_TESTS.

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

if nargin < 2
    exit_on_fail = 0;
    if nargin < 1
        verbose = 0;
    end
end

tests = {};

%% MOST tests
have_c3sopf = exist('c3sopf', 'file') == 2;
tests{end+1} = 't_most_3b_1_1_0';
tests{end+1} = 't_most_3b_3_1_0';
if have_c3sopf
    tests{end+1} = 't_most_3b_1_1_2';
    tests{end+1} = 't_most_3b_3_1_2';
end
tests{end+1} = 't_most_30b_1_1_0';
tests{end+1} = 't_most_30b_3_1_0';
if have_c3sopf
    tests{end+1} = 't_most_30b_1_1_17';
    tests{end+1} = 't_most_30b_3_1_17';
end
tests{end+1} = 't_most_fixed_res';
tests{end+1} = 't_most_30b_1_1_0_uc';
if have_c3sopf
    tests{end+1} = 't_most_sp';
    tests{end+1} = 't_most_spuc';
end
tests{end+1} = 't_most_mpopf';
tests{end+1} = 't_most_uc';
tests{end+1} = 't_most_suc';
tests{end+1} = 't_most_tlmp';
tests{end+1} = 't_most_w_ds';

%% run the tests
all_ok = t_run_tests( tests, verbose );

%% handle success/failure
if exit_on_fail && ~all_ok
    exit(1);
end
if nargout
    success = all_ok;
end


function [data] = ft_redefinetrial(cfg, data)

% FT_REDEFINETRIAL allows you to adjust the time axis of your data, i.e. to
% change from stimulus-locked to response-locked. Furthermore, it allows
% you to select a time window of interest, or to resegment your long trials
% into shorter fragments.
%
% Use as
%   [data] = ft_redefinetrial(cfg, data)
% where the input data should correspond to the output of FT_PREPROCESSING and the
% configuration should be specified as explained below. Note that some options are
% mutually exclusive. If you want to use both,  you neew two calls to this function
% to avoid confusion about the order in which they are applied.
%
% For selecting a subset of trials you can specify
%   cfg.trials    = 'all' or a selection given as a 1xN vector (default = 'all')
%
% For selecting trials with a minimum length you can specify
%   cfg.minlength = length in seconds, can be 'maxperlen' (default = [])
%
% For realiging the time axes of all trials to a new reference time
% point (i.e. change the definition for t=0) you can use the following
% configuration option
%   cfg.offset    = single number or Nx1 vector, expressed in samples relative to current t=0
%
% For selecting a specific subsection of (i.e. cut out a time window
% of interest) you can select a time window in seconds that is common
% in all trials
%   cfg.toilim    = [tmin tmax] to specify a latency window in seconds, can be Nx2 vector
%
% Alternatively you can specify the begin and end sample in each trial
%   cfg.begsample = single number or Nx1 vector, expressed in samples relative to the start of the input trial
%   cfg.endsample = single number or Nx1 vector, expressed in samples relative to the start of the input trial
%
% Alternatively you can specify a new trial definition, expressed in
% samples relative to the original recording
%   cfg.trl       = Nx3 matrix with the trial definition, see FT_DEFINETRIAL
%
% Alternatively you can specify the data to be cut into (non-)overlapping
% segments, starting from the beginning of each trial. This may lead to loss
% of data at the end of the trials
%   cfg.length    = number (in seconds) that specifies the length of the required snippets
%   cfg.overlap   = number between 0 and 1 (exclusive) specifying the fraction of overlap between snippets (0 = no overlap)
%
% Alternatively you can merge or stitch pseudo-continuous segmented data back into a
% continuous representation. This requires that the data has a valid sampleinfo field
% and that there are no jumps in the signal in subsequent trials (e.g. due to
% filtering or demeaning). If there are missing segments (e.g. due to artifact
% rejection), the output data will have one trial for each section where the data is
% continuous.
%   cfg.continuous = 'yes'
%
% To facilitate data-handling and distributed computing you can use
%   cfg.inputfile   =  ...
%   cfg.outputfile  =  ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_DEFINETRIAL, FT_RECODEEVENT, FT_PREPROCESSING

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

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

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

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

% store original datatype
dtype = ft_datatype(data);

% deal with the special case of timelock rpt_chan_time with 1 trial
oneRptTimelock = (strcmp(dtype, 'timelock') && ...
  strcmp(data.dimord, 'rpt_chan_time') && ...
  size(data.trial, 1) == 1);

% check if the input data is valid for this function, this will convert it to raw if needed
data = ft_checkdata(data, 'datatype', {'raw+comp', 'raw'}, 'feedback', 'yes');

% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'forbidden',  {'trial'}); % prevent accidental typos, see issue 1729

% set the defaults
cfg.offset       = ft_getopt(cfg, 'offset',     []);
cfg.toilim       = ft_getopt(cfg, 'toilim',     []);
cfg.begsample    = ft_getopt(cfg, 'begsample',  []);
cfg.endsample    = ft_getopt(cfg, 'endsample',  []);
cfg.minlength    = ft_getopt(cfg, 'minlength',  []);
cfg.trials       = ft_getopt(cfg, 'trials',     'all', 1);
cfg.feedback     = ft_getopt(cfg, 'feedback',   'yes');
cfg.trl          = ft_getopt(cfg, 'trl',        []);
cfg.length       = ft_getopt(cfg, 'length',     []);
cfg.overlap      = ft_getopt(cfg, 'overlap',    0);
cfg.continuous   = ft_getopt(cfg, 'continuous', 'no');

% select trials of interest
if ~strcmp(cfg.trials, 'all')
  if islogical(cfg.trials)
    ft_info('selecting %d trials\n', sum(cfg.trials));
  else
    ft_info('selecting %d trials\n', length(cfg.trials));
  end

  % select trials of interest
  tmpcfg = keepfields(cfg, {'trials', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
  data   = ft_selectdata(tmpcfg, data);
  % restore the provenance information
  [cfg, data] = rollback_provenance(cfg, data);

  if length(cfg.offset)>1 && length(cfg.offset)~=length(cfg.trials)
    cfg.offset = cfg.offset(cfg.trials);
  end
  if length(cfg.begsample)>1 && length(cfg.begsample)~=length(cfg.trials)
    cfg.begsample = cfg.begsample(cfg.trials);
  end
  if length(cfg.endsample)>1 && length(cfg.endsample)~=length(cfg.trials)
    cfg.endsample = cfg.endsample(cfg.trials);
  end
end

Ntrial = numel(data.trial);

% check the input arguments, only one method for processing is allowed
numoptions = ~isempty(cfg.toilim) + ~isempty(cfg.offset) + (~isempty(cfg.begsample) || ~isempty(cfg.endsample)) + ~isempty(cfg.trl) + ~isempty(cfg.length) + istrue(cfg.continuous);
if numoptions>1
  ft_error('you should specify only one of the options for redefining the data segments');
end
if numoptions==0 && isempty(cfg.minlength) && strcmp(cfg.trials, 'all')
  ft_error('you should specify at least one configuration option');
end

% start processing
if ~isempty(cfg.toilim)
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % select a latency window from each trial
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  if numel(cfg.toilim) == 2
    % specified as single [tstart tend] vector
    % expand into Ntrial X 2
    cfg.toilim = repmat(cfg.toilim(:)', Ntrial, 1);
  end

  begsample = zeros(Ntrial,1);
  endsample = zeros(Ntrial,1);
  skiptrial = false(Ntrial,1);
  for i=1:Ntrial
    if cfg.toilim(i,1)>data.time{i}(end) || cfg.toilim(i,2)<data.time{i}(1)
      begsample(i) = nan;
      endsample(i) = nan;
      skiptrial(i) = true;
    else
      begsample(i) = nearest(data.time{i}, cfg.toilim(i,1));
      endsample(i) = nearest(data.time{i}, cfg.toilim(i,2));
      data.trial{i} = data.trial{i}(:, begsample(i):endsample(i));
      data.time{i}  = data.time{i} (   begsample(i):endsample(i));
    end
  end

  % also correct the sample information
  if isfield(data, 'sampleinfo')
    data.sampleinfo(:, 1) = data.sampleinfo(:, 1) + begsample - 1;
    data.sampleinfo(:, 2) = data.sampleinfo(:, 1) + endsample - begsample;
  end

  data.time     = data.time(~skiptrial);
  data.trial    = data.trial(~skiptrial);
  if isfield(data, 'sampleinfo'),  data.sampleinfo  = data.sampleinfo(~skiptrial, :); end
  if isfield(data, 'trialinfo'),   data.trialinfo   = data.trialinfo(~skiptrial, :);  end
  ft_info('removing %d trials in which no data was selected\n', sum(skiptrial));

elseif ~isempty(cfg.offset)
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % shift the time axis from each trial
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  offset = cfg.offset(:);
  offset = round(offset); % this is in samples and hence it must be expressed as integers
  if length(cfg.offset)==1
    offset = repmat(offset, Ntrial, 1);
  end
  for i=1:Ntrial
    data.time{i} = data.time{i} + offset(i)/data.fsample;
  end

elseif ~isempty(cfg.begsample) || ~isempty(cfg.endsample)
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % select a latency window from each trial based on begin and/or end sample
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  begsample = cfg.begsample(:);
  endsample = cfg.endsample(:);
  if length(begsample)==1
    begsample = repmat(begsample, Ntrial, 1);
  end
  if length(endsample)==1
    endsample = repmat(endsample, Ntrial, 1);
  end
  for i=1:Ntrial
    data.trial{i} = data.trial{i}(:, begsample(i):endsample(i));
    data.time{i}  = data.time{i} (   begsample(i):endsample(i));
  end

  % also correct the sampleinfo
  if isfield(data, 'sampleinfo')
    sampleinfo = data.sampleinfo(:, 1);
    data.sampleinfo(:, 1) = sampleinfo(:, 1) + begsample - 1;
    data.sampleinfo(:, 2) = sampleinfo(:, 1) + endsample - 1;
  end

elseif ~isempty(cfg.trl)
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % select new trials from the existing data
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  if ischar(cfg.trl)
    % load the trial information from file
    newtrl = loadvar(cfg.trl, 'trl');
  else
    newtrl = cfg.trl;
  end

  % ensure that sampleinfo is present, otherwise ft_fetch_data will crash
  data = ft_checkdata(data, 'hassampleinfo', 'yes');

  % make a copy of the old data
  dataold = data;

  % make the header
  hdr = ft_fetch_header(dataold);

  % start with a completely new data structure
  data          = keepfields(dataold, {'cfg' 'fsample' 'label' 'topo' 'topolabel' 'unmixing' 'mixing' 'grad' 'elec' 'opto'}); % account for all potential fields to be copied over
  data.hdr      = hdr;
  data.trial    = cell(1,size(newtrl,1));
  data.time     = cell(1,size(newtrl,1));

  if isfield(dataold, 'trialinfo')
    ft_warning('Original data has trialinfo, using user-specified trialinfo instead');
  end

  if ~istable(newtrl)
    begsample = newtrl(:,1);
    endsample = newtrl(:,2);
    offset    = newtrl(:,3);
  else
    begsample = newtrl.begsample;
    endsample = newtrl.endsample;
    offset    = newtrl.offset;
  end
  trllength = endsample - begsample + 1;

  for iTrl=1:size(newtrl, 1)

    data.trial{iTrl} = ft_fetch_data(dataold, 'header', hdr, 'begsample', begsample(iTrl), 'endsample', endsample(iTrl), 'chanindx', 1:hdr.nChans, 'skipcheckdata', 1);
    data.time{iTrl}  = offset2time(offset(iTrl), dataold.fsample, trllength(iTrl));

    % The following ensures correct handling of trialinfo.

    % Determine which old trials are present in new trials
    iTrlorig = find(begsample(iTrl) <= dataold.sampleinfo(:,2) & endsample(iTrl) >= dataold.sampleinfo(:,1));

    if size(newtrl,2)>3 % In case user specified additional trialinfo
      data.trialinfo(iTrl,:) = newtrl(iTrl,4:end);
    elseif isfield(dataold,'trialinfo') % If old data has trialinfo
      if (numel(iTrlorig) == 1 ...      % only 1 old trial to copy trialinfo from, or
          || size(unique(dataold.trialinfo(iTrlorig,:),'rows'),1)) ... % all old trialinfo rows are identical
          && ~any(diff(dataold.sampleinfo(:,1))<=0) % and the trials are consecutive segments
        data.trialinfo(iTrl,:) = dataold.trialinfo(iTrlorig(1),:);
      else
        ft_error('Old trialinfo cannot be combined into new trialinfo, please specify trialinfo in cfg.trl(:,4)');
      end
    end
  end % for iTrl

  % adjust the sampleinfo in the output
  if isfield(dataold, 'sampleinfo')
    % adjust the sample information
    data.sampleinfo  = [begsample endsample];
  end

elseif ~isempty(cfg.length)
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % cut the existing trials into segments of the specified length
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  data = ft_checkdata(data, 'hassampleinfo', 'yes');

  % create dummy trl-matrix and recursively call ft_redefinetrial
  nsmp    = round(cfg.length*data.fsample);
  nshift  = round((1-cfg.overlap)*nsmp);

  if nshift<=0
    ft_error('the overlap is too large');
  end

  newtrl = zeros(0,4);
  for k = 1:numel(data.trial)
    begsample = data.sampleinfo(k,1);
    endsample = data.sampleinfo(k,2);
    offset    = time2offset(data.time{k}, data.fsample);
    thistrl   = (begsample:nshift:(endsample+1-nsmp))';
    if ~isempty(thistrl) % the trial might be too short
      thistrl(:,2) = thistrl(:,1) + nsmp - 1;
      thistrl(:,3) = thistrl(:,1) + offset - thistrl(1,1);
      thistrl(:,4) = k; % keep the trial number in the 4th column, this is needed further down
      newtrl = cat(1, newtrl, thistrl);
    end
  end
  clear begsample endsample offset

  tmpcfg = keepfields(cfg, {'feedback', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
  tmpcfg.trl = newtrl;

  if isfield(data, 'trialinfo') && ~istable(data.trialinfo)
    % replace the trial number with the original trial information
    tmpcfg.trl = [newtrl(:,1:3) data.trialinfo(newtrl(:,4),:)];
  elseif isfield(data, 'trialinfo') && istable(data.trialinfo)
    % construct the trl matrix as a table
    begsample = newtrl(:,1);
    endsample = newtrl(:,2);
    offset    = newtrl(:,3);
    tmpcfg.trl = [table(begsample, endsample, offset) data.trialinfo(newtrl(:,4),:)];
  elseif ~isfield(data, 'trialinfo')
    % discard the trial number
    tmpcfg.trl = newtrl(:,1:3);
  end

  data   = removefields(data, {'trialinfo'}); % these are in the additional columns of tmpcfg.trl
  data   = ft_redefinetrial(tmpcfg, data);
  % restore the provenance information
  [cfg, data] = rollback_provenance(cfg, data);

elseif istrue(cfg.continuous)
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % identify consecutive segments that can be glued back together
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  data = ft_checkdata(data, 'hassampleinfo', 'yes');

  boolvec = artifact2boolvec(data.sampleinfo);
  newtrl = boolvec2trl(boolvec);

  % In general: An offset of 0 means that the first sample of the trial corresponds
  % to the trigger. A positive offset indicates that the first sample is later than
  % the trigger.

  % here we want to use the start of the recording as t=0
  newtrl(:,3) = newtrl(:,1) - 1;

  tmpcfg = keepfields(cfg, {'feedback', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});
  tmpcfg.trl = newtrl;

  data   = removefields(data, {'trialinfo'}); % the trialinfo does not apply any more
  data   = ft_redefinetrial(tmpcfg, data);
  % restore the provenance information
  [cfg, data] = rollback_provenance(cfg, data);

end % processing the realignment or data selection

if ~isempty(cfg.minlength)
  Ntrial    = length(data.trial);
  trllength = zeros(Ntrial, 1);
  % determine the length of each trial
  for i=1:Ntrial
    trllength(i) = size(data.trial{i},2) * 1/data.fsample; % this the the DURATION of the selected samples
  end
  if ischar(cfg.minlength) && strcmp(cfg.minlength, 'maxperlen')
    minlength = max(trllength);
  else
    minlength = cfg.minlength;
  end
  % remove trials that are too short
  skiptrial = (trllength<minlength);
  %if ~isempty(trl), trl = trl(~skiptrial,:); end
  data.time  = data.time(~skiptrial);
  data.trial = data.trial(~skiptrial);
  if isfield(data, 'sampleinfo'), data.sampleinfo  = data.sampleinfo(~skiptrial, :); end
  if isfield(data, 'trialinfo'),  data.trialinfo   = data.trialinfo (~skiptrial, :); end
  ft_info('removing %d trials that are too short\n', sum(skiptrial));
end

% convert back to input type if necessary
switch dtype
  case 'timelock'
    data = ft_checkdata(data, 'datatype', 'timelock');
    if oneRptTimelock
      % deal with the special case of rpt_chan_time timelock data with one
      % repetition
      data.trial = reshape(data.avg, [1 size(data.avg)]);
      data.dimord = 'rpt_chan_time';
    end
  otherwise
    % keep the output as it is
end

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


% +XYZFUN
%
% Contains Functions that operate on a grid in 3D (XYZ) space
%
%
% Files
%   bgrid3dB - This subroutine assigns creates a 3D grid with
%   zgrid3d  -


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

function SpharmMatUtilImportObjs(confs, objs)

numSbj = length(objs);
if ~exist(confs.OutDirectory,'dir')
    mkdir(confs.OutDirectory);
end
if (~exist([confs.OutDirectory '/Logs'],'dir'))
    mkdir([confs.OutDirectory '/Logs']);
end

resampleFactor = confs.ResampleFactor;
%class(confs) - struct
%confs.vars -list of variable
%class(objs) - cell

h = waitbar(0,'Please wait...');
for i = 1:numSbj
    file = objs{i};
    [path, name, ext] = fileparts(file);
    diary(fullfile([confs.OutDirectory '/Logs'],[date, '_', num2str(round(cputime)), '_' name '_importObj.log']));

    vxsize = [1 1 1];
    switch upper(ext)
        case '.STL'
            [vertices,faces] = readSTL(file);
            origin = [0 0 0];
            new_name = [confs.OutDirectory '/' name '_obj.mat'];
            if exist(new_name,'file')
                prompt = {'Enter new filename:'};
                dlg_title = 'New File Name';
                num_lines = 1;
                def = {new_name};
                answer = inputdlg(prompt,dlg_title,num_lines,def);
                new_name = answer{1};
            end
            save(new_name, 'vertices', 'faces', 'origin');
        case '.HDR'
            [bim, origin] = NIfTI2bim(file, resampleFactor);
            new_name = [confs.OutDirectory '/' name '_bim.mat'];
            if exist(new_name,'file')
                prompt = {'Enter new filename:'};
                dlg_title = 'New File Name';
                num_lines = 1;
                def = {new_name};
                answer = inputdlg(prompt,dlg_title,num_lines,def);
                new_name = answer{1};
            end
            save(new_name, 'bim', 'origin', 'vxsize');
        case '.NII'
            [bim, origin] = NIfTI2bim(file, resampleFactor);
            new_name = [confs.OutDirectory '/' name '_bim.mat'];
            if exist(new_name,'file')
                prompt = {'Enter new filename:'};
                dlg_title = 'New File Name';
                num_lines = 1;
                def = {new_name};
                answer = inputdlg(prompt,dlg_title,num_lines,def);
                new_name = answer{1};
            end
            save(new_name, 'bim', 'origin', 'vxsize');
        case '.M'
            [vertices,faces] = readM(file);
            origin = [0 0 0];
            new_name = [confs.OutDirectory '/' name '_obj.mat'];
            if exist(new_name,'file')
                prompt = {'Enter new filename:'};
                dlg_title = 'New File Name';
                num_lines = 1;
                def = {new_name};
                answer = inputdlg(prompt,dlg_title,num_lines,def);
                new_name = answer{1};
            end
            save(new_name, 'vertices', 'faces', 'origin');
    end
    diary('off');
    waitbar(i/numSbj)
end
close(h);

return;


function [OverviewName, phdmeta, overviewmeta] = CreateImageOverview(filename,Prefs)
%CREATEIMAGEOVERVIEW Creates an image overview from CPHD data at the
%specified resolution

%generate overview name
[pathstr, fname] = fileparts(filename);
if strcmpi(Prefs.SICDLocation,'Colocated')
    OverviewName = [pathstr filesep fname '_Overview.nitf'];
else
    OverviewName = [Prefs.SICDLocation filesep fname '_Overview.nitf'];
end

ph_reader = open_ph_reader(filename);
phdmeta = ph_reader.get_meta();
ph_reader.close();

%if specified, use existing Overview file
if Prefs.UseOverview
    if ~isempty(dir(OverviewName))
        reader_obj = open_reader(OverviewName);
        overviewmeta = reader_obj.get_meta();
        reader_obj.close;
        return;
    end
end

%form image at specified resolution
overviewmeta = pfa_file(filename,OverviewName,'Resolution',[Prefs.MaxResolution Prefs.MaxResolution]);

end


function y = lut_fun(x, lut_table, lut_signs, varargin)
    i0 = 1;
    if numel(varargin) > 0
        i0 = 1 + varargin{1};
    end
    y = lut_table(round(x * (10^lut_signs)) + i0);
    y = reshape(y, size(x));
end


function [fg, OK] = dtiModifyFiberGroup(fg)
% Window popup to allow user to set properties of a fiber group in the UI
%
%  [fg, OK] = dtiModifyFiberGroup(fg)
%
% Fiber group name, thickness, visibility, and color can be changed.
%
% HISTORY:
%   2003.10.29 RFD (bob@white.stanford.edu) wrote it.
%
% (c) Stanford VISTA Team

if(~exist('fg','var') || isempty(fg)), fg = dtiNewFiberGroup; end

ans = inputdlg({'name:','thickness:','visible:','color:'},...
    'Fiber Group Info',1,...
    {fg.name, num2str(fg.thickness), num2str(fg.visible), num2str(fg.colorRgb)});

if(~isempty(ans))
    fg.name = ans{1};
    fg.thickness = str2num(ans{2});
    fg.visible = str2num(ans{3});
    fg.colorRgb = str2num(ans{4});
    OK = true;
else
    OK = false;
end

return;


function varargout=beta_w(varargin)

switch class(varargin{1})

    case 'double'
        varargout{1} = beta(varargin{2},varargin{1});

    case 'char'
        operator = CreateBasicOperator('convex','decreasing','positive','callback');
        operator.domain = [0 inf];
        varargout{1} = [];
        varargout{2} = operator;
        varargout{3} = varargin{3};

    otherwise
        error(['SDPVAR/' upper(mfilename) ' called with weird argument']);
end


function my_move_net(net_info, destination)

if strcmp(destination, 'gpu')

    for l=1:numel(net_info.ref.layers)
      switch net_info.ref.layers{l}.type
        case 'conv'
          for f = {'filters', 'biases', 'filtersMomentum', 'biasesMomentum'}
            f = char(f) ;
            if isfield(net_info.ref.layers{l}, f)
              net_info.ref.layers{l}.(f) = move_to_gpu_values(net_info.ref.layers{l}.(f)) ;
            end
          end
        otherwise
          % nothing to do ?
      end
    end

    net_info.ref.net_on_gpu=true;

end

if strcmp(destination, 'cpu')

    for l=1:numel(net_info.ref.layers)
      switch net_info.ref.layers{l}.type
        case 'conv'
          for f = {'filters', 'biases', 'filtersMomentum', 'biasesMomentum'}
            f = char(f) ;
            if isfield(net_info.ref.layers{l}, f)
              net_info.ref.layers{l}.(f) = move_to_cpu_values(net_info.ref.layers{l}.(f)) ;
            end
          end
        otherwise
          % nothing to do ?
      end
    end

    net_info.ref.net_on_gpu=false;

end

end


function k = plotDataTimeSeries(y, iS, iD, iDt, option)
if ~exist('option','var')
    option = '';
end
ml = y.GetMeasurementList('matrix');
k = find(ml(:,1)==iS & ml(:,2)==iD & ml(:,4)==iDt);
if ishandle(1)
    if ~strcmp(option,'keep') && ~strcmp(option,'keepopen') && ~strcmp(option,'open')
        close(1);
    end
end
figure
plot(y.dataTimeSeries(:,k))


% writecnt() - Write a Neuroscan continuous signal file.
%
% Usage:
%   >> writecnt(filename, CNT-dataset, varargin)
%
% Inputs:
%   filename - name of the file with extension
%   dataset -  name of the CNT-dataset, a structure with the following fields
%                   cntdataset.header
%                   cntdataset.electloc
%                   cntdataset.data
%                   cntdataset.Teeg
%                   cntdataset.event
%                   cntdataset.tag
%                   cntdataset.endtag
%
% Optional inputs:
%  't1'         - start at time t1, default 0
%  'sample1'    - start at sample1, default 0, overrides t1
%  'lddur'      - duration of segment to load, default = whole file
%  'ldnsamples' - number of samples to load, default = whole file,
%                 overrides lddur
%  'scale'      - ['on'|'off'] scale data to microvolt (default:'on')
%  'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data.
%                 Use 'int32' for 32-bit data.
%
% Outputs:
%  file         - file containing NeuroScan CNT file with the continuous
%                 data and other information
%
% Authors:   Sean Fitzgibbon, Arnaud Delorme, Michiel Vestjens 2000-2004
%
% Known limitations:
%  For more see http://www.cnl.salk.edu/~arno/cntload/index.html

% Copyright (C) 2000 Sean Fitzgibbon, <psspf@id.psy.flinders.edu.au>
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function f = writecnt(filename,cntdataset,varargin)

if ~isempty(varargin)
	 WriteOptions=struct(varargin{:});
else WriteOptions = [];
end;

try, WriteOptions.t1;         catch, WriteOptions.t1=0; end
try, WriteOptions.sample1;    catch, WriteOptions.sample1=[]; end
try, WriteOptions.lddur;      catch, WriteOptions.lddur=[]; end
try, WriteOptions.ldnsamples; catch, WriteOptions.ldnsamples=[]; end
try, WriteOptions.scale;      catch, WriteOptions.scale='on'; end
try, WriteOptions.dataformat;  catch, WriteOptions.dataformat='int16'; end

sizeEvent1 = 8  ; %%% 8  bytes for Event1
sizeEvent2 = 19 ; %%% 19 bytes for Event2

type='cnt';
if nargin ==1
    scan=0;
end

h   = cntdataset.header;
e   = cntdataset.electloc;
dat = cntdataset.data;
eT  = cntdataset.Teeg;
ev2 = cntdataset.event;
t   = cntdataset.tag;
endtag=cntdataset.endtag;

fid = fopen(filename,'w');
disp(['Writing file ' filename ' ...'])

% HEADER : 900 bytes => Starts at 0h, finishes with 383h.

fwrite(fid,h.rev,'char');
fwrite(fid,h.nextfile,'long');
fwrite(fid,h.prevfile,'long');
fwrite(fid,h.type,'char');
fwrite(fid,h.id,'char');
fwrite(fid,h.oper,'char');
fwrite(fid,h.doctor,'char');
fwrite(fid,h.referral,'char');
fwrite(fid,h.hospital,'char');
fwrite(fid,h.patient,'char');
fwrite(fid,h.age,'short');
fwrite(fid,h.sex,'char');
fwrite(fid,h.hand,'char');
fwrite(fid,h.med,'char');
fwrite(fid,h.category,'char');
fwrite(fid,h.state,'char');
fwrite(fid,h.label,'char');
fwrite(fid,h.date,'char');
fwrite(fid,h.time,'char');
fwrite(fid,h.mean_age,'float');
fwrite(fid,h.stdev,'float');
fwrite(fid,h.n,'short');
fwrite(fid,h.compfile,'char');
fwrite(fid,h.spectwincomp,'float');
fwrite(fid,h.meanaccuracy,'float');
fwrite(fid,h.meanlatency,'float');
fwrite(fid,h.sortfile,'char');
fwrite(fid,h.numevents,'int');
fwrite(fid,h.compoper,'char');
fwrite(fid,h.avgmode,'char');
fwrite(fid,h.review,'char');
fwrite(fid,h.nsweeps,'ushort');
fwrite(fid,h.compsweeps,'ushort');
fwrite(fid,h.acceptcnt,'ushort');
fwrite(fid,h.rejectcnt,'ushort');
fwrite(fid,h.pnts,'ushort');
fwrite(fid,h.nchannels,'ushort');
fwrite(fid,h.avgupdate,'ushort');
fwrite(fid,h.domain,'char');
fwrite(fid,h.variance,'char');
fwrite(fid,h.rate,'ushort');
fwrite(fid,h.scale,'double');
fwrite(fid,h.veogcorrect,'char');
fwrite(fid,h.heogcorrect,'char');
fwrite(fid,h.aux1correct,'char');
fwrite(fid,h.aux2correct,'char');
fwrite(fid,h.veogtrig,'float');
fwrite(fid,h.heogtrig,'float');
fwrite(fid,h.aux1trig,'float');
fwrite(fid,h.aux2trig,'float');
fwrite(fid,h.heogchnl,'short');
fwrite(fid,h.veogchnl,'short');
fwrite(fid,h.aux1chnl,'short');
fwrite(fid,h.aux2chnl,'short');
fwrite(fid,h.veogdir,'char');
fwrite(fid,h.heogdir,'char');
fwrite(fid,h.aux1dir,'char');
fwrite(fid,h.aux2dir,'char');
fwrite(fid,h.veog_n,'short');
fwrite(fid,h.heog_n,'short');
fwrite(fid,h.aux1_n,'short');
fwrite(fid,h.aux2_n,'short');
fwrite(fid,h.veogmaxcnt,'short');
fwrite(fid,h.heogmaxcnt,'short');
fwrite(fid,h.aux1maxcnt,'short');
fwrite(fid,h.aux2maxcnt,'short');
fwrite(fid,h.veogmethod,'char');
fwrite(fid,h.heogmethod,'char');
fwrite(fid,h.aux1method,'char');
fwrite(fid,h.aux2method,'char');
fwrite(fid,h.ampsensitivity,'float');
fwrite(fid,h.lowpass,'char');
fwrite(fid,h.highpass,'char');
fwrite(fid,h.notch,'char');
fwrite(fid,h.autoclipadd,'char');
fwrite(fid,h.baseline,'char');
fwrite(fid,h.offstart,'float');
fwrite(fid,h.offstop,'float');
fwrite(fid,h.reject,'char');
fwrite(fid,h.rejstart,'float');
fwrite(fid,h.rejstop,'float');
fwrite(fid,h.rejmin,'float');
fwrite(fid,h.rejmax,'float');
fwrite(fid,h.trigtype,'char');
fwrite(fid,h.trigval,'float');
fwrite(fid,h.trigchnl,'char');
fwrite(fid,h.trigmask,'short');
fwrite(fid,h.trigisi,'float');
fwrite(fid,h.trigmin,'float');
fwrite(fid,h.trigmax,'float');
fwrite(fid,h.trigdir,'char');
fwrite(fid,h.autoscale,'char');
fwrite(fid,h.n2,'short');
fwrite(fid,h.dir,'char');
fwrite(fid,h.dispmin,'float');
fwrite(fid,h.dispmax,'float');
fwrite(fid,h.xmin,'float');
fwrite(fid,h.xmax,'float');
fwrite(fid,h.automin,'float');
fwrite(fid,h.automax,'float');
fwrite(fid,h.zmin,'float');
fwrite(fid,h.zmax,'float');
fwrite(fid,h.lowcut,'float');
fwrite(fid,h.highcut,'float');
fwrite(fid,h.common,'char');
fwrite(fid,h.savemode,'char');
fwrite(fid,h.manmode,'char');
fwrite(fid,h.ref,'char');
fwrite(fid,h.rectify,'char');
fwrite(fid,h.displayxmin,'float');
fwrite(fid,h.displayxmax,'float');
fwrite(fid,h.phase,'char');
fwrite(fid,h.screen,'char');
fwrite(fid,h.calmode,'short');
fwrite(fid,h.calmethod,'short');
fwrite(fid,h.calupdate,'short');
fwrite(fid,h.calbaseline,'short');
fwrite(fid,h.calsweeps,'short');
fwrite(fid,h.calattenuator,'float');
fwrite(fid,h.calpulsevolt,'float');
fwrite(fid,h.calpulsestart,'float');
fwrite(fid,h.calpulsestop,'float');
fwrite(fid,h.calfreq,'float');
fwrite(fid,h.taskfile,'char');
fwrite(fid,h.seqfile,'char');
fwrite(fid,h.spectmethod,'char');
fwrite(fid,h.spectscaling,'char');
fwrite(fid,h.spectwindow,'char');
fwrite(fid,h.spectwinlength,'float');
fwrite(fid,h.spectorder,'char');
fwrite(fid,h.notchfilter,'char');
fwrite(fid,h.headgain,'short');
fwrite(fid,h.additionalfiles,'int');
fwrite(fid,h.unused,'char');
fwrite(fid,h.fspstopmethod,'short');
fwrite(fid,h.fspstopmode,'short');
fwrite(fid,h.fspfvalue,'float');
fwrite(fid,h.fsppoint,'short');
fwrite(fid,h.fspblocksize,'short');
fwrite(fid,h.fspp1,'ushort');
fwrite(fid,h.fspp2,'ushort');
fwrite(fid,h.fspalpha,'float');
fwrite(fid,h.fspnoise,'float');
fwrite(fid,h.fspv1,'short');
fwrite(fid,h.montage,'char');
fwrite(fid,h.eventfile,'char');
fwrite(fid,h.fratio,'float');
fwrite(fid,h.minor_rev,'char');
fwrite(fid,h.eegupdate,'short');
fwrite(fid,h.compressed,'char');
fwrite(fid,h.xscale,'float');
fwrite(fid,h.yscale,'float');
fwrite(fid,h.xsize,'float');
fwrite(fid,h.ysize,'float');
fwrite(fid,h.acmode,'char');
fwrite(fid,h.commonchnl,'uchar');
fwrite(fid,h.xtics,'char');
fwrite(fid,h.xrange,'char');
fwrite(fid,h.ytics,'char');
fwrite(fid,h.yrange,'char');
fwrite(fid,h.xscalevalue,'float');
fwrite(fid,h.xscaleinterval,'float');
fwrite(fid,h.yscalevalue,'float');
fwrite(fid,h.yscaleinterval,'float');
fwrite(fid,h.scaletoolx1,'float');
fwrite(fid,h.scaletooly1,'float');
fwrite(fid,h.scaletoolx2,'float');
fwrite(fid,h.scaletooly2,'float');
fwrite(fid,h.port,'short');
fwrite(fid,h.numsamples,'ulong');
fwrite(fid,h.filterflag,'char');
fwrite(fid,h.lowcutoff,'float');
fwrite(fid,h.lowpoles,'short');
fwrite(fid,h.highcutoff,'float');
fwrite(fid,h.highpoles,'short');
fwrite(fid,h.filtertype,'char');
fwrite(fid,h.filterdomain,'char');
fwrite(fid,h.snrflag,'char');
fwrite(fid,h.coherenceflag,'char');
fwrite(fid,h.continuoustype,'char');
fwrite(fid,h.eventtablepos,'long');
fwrite(fid,h.continuousseconds,'float');
fwrite(fid,h.channeloffset,'long');
fwrite(fid,h.autocorrectflag,'char');
fwrite(fid,h.dcthreshold,'uchar');  % = 383H

% ELECT.DESCRIPTIONS : 75*n.channels bytes.
% Starts with 384h, finishes with (899+75*nchannels)dec
% 10 channels: 671h   % 12 channels: 707h
% 24 channels: A8Bh   % 32 channels: CE3h
% 64 channels: 1643h  % 128 channels: 2903h

for n = 1:h.nchannels
    fwrite(fid,e(n).lab,'char');
    fwrite(fid,e(n).reference,'char');
    fwrite(fid,e(n).skip,'char');
    fwrite(fid,e(n).reject,'char');
    fwrite(fid,e(n).display,'char');
    fwrite(fid,e(n).bad,'char');
    fwrite(fid,e(n).n,'ushort');
    fwrite(fid,e(n).avg_reference,'char');
    fwrite(fid,e(n).clipadd,'char');
    fwrite(fid,e(n).x_coord,'float');
    fwrite(fid,e(n).y_coord,'float');
    fwrite(fid,e(n).veog_wt,'float');
    fwrite(fid,e(n).veog_std,'float');
    fwrite(fid,e(n).snr,'float');
    fwrite(fid,e(n).heog_wt,'float');
    fwrite(fid,e(n).heog_std,'float');
    fwrite(fid,e(n).baseline,'short');
    fwrite(fid,e(n).filtered,'char');
    fwrite(fid,e(n).fsp,'char');
    fwrite(fid,e(n).aux1_wt,'float');
    fwrite(fid,e(n).aux1_std,'float');
    fwrite(fid,e(n).senstivity,'float');
    fwrite(fid,e(n).gain,'char');
    fwrite(fid,e(n).hipass,'char');
    fwrite(fid,e(n).lopass,'char');
    fwrite(fid,e(n).page,'uchar');
    fwrite(fid,e(n).size,'uchar');
    fwrite(fid,e(n).impedance,'uchar');
    fwrite(fid,e(n).physicalchnl,'uchar');
    fwrite(fid,e(n).rectify,'char');
    fwrite(fid,e(n).calib,'float');
end

% finding if 32-bits of 16-bits file
% ----------------------------------
begdata = ftell(fid);
enddata = h.eventtablepos;   % after data
if strcmpi(WriteOptions.dataformat, 'int16')
     nums    = (enddata-begdata)/h.nchannels/2;
else nums    = (enddata-begdata)/h.nchannels/4;
end;

% number of sample to write
% -------------------------
if ~isempty(WriteOptions.sample1)
   WriteOptions.t1      = WriteOptions.sample1/h.rate;
else
   WriteOptions.sample1 = WriteOptions.t1*h.rate;
end;
if strcmpi(WriteOptions.dataformat, 'int16')
     startpos = WriteOptions.t1*h.rate*2*h.nchannels;
else startpos = WriteOptions.t1*h.rate*4*h.nchannels;
end;
if isempty(WriteOptions.ldnsamples)
     if ~isempty(WriteOptions.lddur)
          WriteOptions.ldnsamples = round(WriteOptions.lddur*h.rate);
     else WriteOptions.ldnsamples = nums;
     end;
end;

% scaling data from microvolts
% ----------------------------
if strcmpi(WriteOptions.scale, 'on')
    disp('Scaling data .....')
    for i=1:h.nchannels
       bas=e(i).baseline;
       sen=e(i).senstivity;
       cal=e(i).calib;
       mf=sen*(cal/204.8);
       dat(i,:)=(dat(i,:)/mf)+bas;
   end
end

% write data
% ----------
disp('Writing data .....')
if type == 'cnt'
    channel_off = h.channeloffset/2;

      fseek(fid, startpos, 0);
	  if channel_off <= 1
          for temploop =1:WriteOptions.ldnsamples;
              fwrite(fid, dat(1:h.nchannels, temploop), WriteOptions.dataformat)';
          end;
 	  else
          for temploop =1:h.nchannels;
              fwrite(fid, dat(temploop, 1:channel_off), WriteOptions.dataformat)';
          end;

		  counter = 1;
 		  while counter*channel_off < WriteOptions.ldnsamples

              for temploop =1:h.nchannels;
                fwrite(fid, dat(temploop, counter*channel_off+1:counter*channel_off+channel_off), WriteOptions.dataformat)';
              end;
              counter = counter + 1;
		  end;
	  end;

      % write event table
      % -----------------
      frewind(fid);
      fseek(fid,h.eventtablepos,'bof');

      disp('Writing Event Table...')
      fwrite(fid,eT.teeg,'uchar');
      fwrite(fid,eT.size,'ulong');
      fwrite(fid,eT.offset,'ulong');

      if eT.teeg==2
          nevents=eT.size/sizeEvent2;
      elseif eT.teeg==1
          nevents=eT.size/sizeEvent1;
      else
          disp('No !!! teeg <> 2 and teeg <> 1');
          ev2 = [];
      end

     %%%% to change offset in points back to bytes
     if ~isempty(ev2)
          ev2p=ev2;
          ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc
          for i=1:nevents
              ev2p(i).offset=((ev2p(i).offset + WriteOptions.sample1)*2*h.nchannels) +ioff; %% 2 short int end
          end
          ev2 = ev2p;
     end;

     if eT.teeg==2
          nevents=eT.size/sizeEvent2;
          for i=1:nevents
              ev2(i).stimtype      = fwrite(fid,ev2(i).stimtype,'ushort');
              ev2(i).keyboard      = fwrite(fid,ev2(i).keyboard,'char');
              ev2(i).keypad_accept = fwrite(fid,ev2(i).keypad_accept,'char');
              ev2(i).offset        = fwrite(fid,ev2(i).offset,'long');
              ev2(i).type          = fwrite(fid,ev2(i).type,'short');
              ev2(i).code          = fwrite(fid,ev2(i).code,'short');
              ev2(i).latency       = fwrite(fid,ev2(i).latency,'float');
              ev2(i).epochevent    = fwrite(fid,ev2(i).epochevent,'char');
              ev2(i).accept        = fwrite(fid,ev2(i).accept,'char');
              ev2(i).accuracy      = fwrite(fid,ev2(i).accuracy,'char');
          end
      elseif eT.teeg==1
          nevents=eT.size/sizeEvent1;
          for i=1:nevents
              ev2(i).stimtype      = fwrite(fid,ev2(i).stimtype,'ushort');
              ev2(i).keyboard      = fwrite(fid,ev2(i).keyboard,'char');
              ev2(i).keypad_accept = fwrite(fid,ev2(i).keypad_accept,'char');
              ev2(i).offset        = fwrite(fid,ev2(i).offset,'long');
          end;
      else
          disp('No !!! teeg <> 2 and teeg <> 1');
          ev2 = [];
      end
end

if size(endtag,1)>1
    fwrite(fid,endtag);
else
    fwrite(fid,t,'char');
end

fclose(fid);
disp(['Finished writing file ' filename ' ...'])


function vw = initMontageSlider(vw)
%
% vw = initMontageSlider(vw)
%
% initializes the slider that sets the size of
% an inplane montage.
%
% ras 09/04, off initSliceSlider
if ~strcmp(vw.viewType,'Inplane')
   error('initMontageSlider: Only used for INPLANE window');
end

ui = viewGet(vw,'ui');
sliderHandle = ui.montageSize.sliderHandle;

% Set the step size for clicking on the arrows and the trough
nSlices = viewGet(vw, 'numSlices');

% if there's only one slice, this slider should be turned off
if nSlices < 2
    nSlices=2;
    set(sliderHandle,'Enable','off');
else
    set(sliderHandle,'Enable','on');
end

% set the range and step size of the slider
set(sliderHandle,'Min',1,'Max',nSlices);
sliderStep = [1/(nSlices-1) , 3/(nSlices-1)];
set(sliderHandle,'sliderStep',sliderStep);

% Update the slider callback to be an integer.
sliderCb = 'val=round(get(gcbo,''Value''));';
sliderCb = sprintf('%s \n setSlider(%s,%s.ui.montageSize,val,0);',...
               sliderCb,vw.name,vw.name);
sliderCb = sprintf('%s \n %s=refreshScreen(%s);',...
                sliderCb,vw.name,vw.name);
set(vw.ui.montageSize.sliderHandle,'CallBack',sliderCb);

% Update the edit callback to be an integer.
editCb = 'val=round(str2num(get(gcbo,''String'')));';
editCb = sprintf('%s \n setSlider(%s,%s.ui.montageSize,val,0);',...
               editCb,vw.name,vw.name);
editCb = sprintf('%s \n %s=refreshScreen(%s);',...
                editCb,vw.name,vw.name);
set(vw.ui.montageSize.labelHandle,'CallBack',editCb);

% If we are first opening the window, create the text box.
if ~isfield(vw.ui.montageSize,'textHandle')

   % Position the text box to the right of the slider
   pos = get(sliderHandle,'Position');
   l2 = pos(1) + pos(3) + .01;
   w2 = pos(3)/4; b = pos(2); h = pos(4);
   position = [l2 b w2 h];

   vw.ui.montageSize.textHandle = ...
      uicontrol('Style','text',...
      'Units','normalized',...
      'Position',position);
end

% This text tells the user the max number of slices being
% shown in the montage (starting with the selected slice)
str = sprintf('%.0f',nSlices);
set(vw.ui.montageSize.textHandle, 'String', str);

vw = setSlider(vw, vw.ui.montageSize, 1, 0);

return


function gX =  whiteXwhiteKernGradX(whiteKern1, whiteKern2, X, X2)

% WHITEXWHITEKERNGRADX

% KERN

if nargin < 3,
    X2 = X;
else
    U = X;
    X = X2;
    X2 = U;
end

gX = zeros(size(X2, 1), size(X2, 2), size(X, 1));


function [varargout] = isequaln(varargin)

% ISEQUALN is a drop-in replacement for the same function that was
% introduced in MATLAB R2012a.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% see https://github.com/fieldtrip/fieldtrip/issues/899

alternatives = which(mfilename, '-all');
if ~iscell(alternatives)
  % this is needed for octave, see https://github.com/fieldtrip/fieldtrip/pull/1171
  alternatives = {alternatives};
end

keep = true(size(alternatives));
for i=1:numel(alternatives)
  keep(i) = keep(i) && ~any(alternatives{i}=='@');  % exclude methods from classes
  keep(i) = keep(i) && alternatives{i}(end)~='p';   % exclude precompiled files
end
alternatives = alternatives(keep);

if exist(mfilename, 'builtin') || any(strncmp(alternatives, matlabroot, length(matlabroot)) & cellfun(@isempty, strfind(alternatives, fullfile('private', mfilename))))
  % remove this directory from the path
  p = fileparts(mfilename('fullpath'));
  sw = warning('off','backtrace');
  warning('Removing "%s" from your path.\nSee http://www.fieldtriptoolbox.org/faq/should_i_add_fieldtrip_with_all_subdirectories_to_my_matlab_path/', p);
  warning(sw);
  rmpath(p);
  % call the original MATLAB function
  if exist(mfilename, 'builtin')
    [varargout{1:nargout}] = builtin(mfilename, varargin{:});
  else
    [varargout{1:nargout}] = feval(mfilename, varargin{:});
  end
  return
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is where the actual replacement code starts
% function tf = isequaln(varargin)

tf = isequalwithequalnans(varargin{:});

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% deal with the output arguments

varargout = {tf};


function model = ResNet101_for_RFCN_VOC0712_OHEM(model)
% ResNet 101layers with OHEM training (finetuned from res3a)

model.solver_def_file        = fullfile(pwd, 'models', 'rfcn_prototxts', 'ResNet-101L_OHEM_res3a', 'solver_80k110k_lr1_3.prototxt');
model.test_net_def_file      = fullfile(pwd, 'models', 'rfcn_prototxts', 'ResNet-101L_OHEM_res3a', 'test.prototxt');

model.net_file               = fullfile(pwd, 'models', 'pre_trained_models', 'ResNet-101L', 'ResNet-101-model.caffemodel');
model.mean_image             = fullfile(pwd, 'models', 'pre_trained_models', 'ResNet-101L', 'mean_image');

end


any(cellfun(@exist,{'fast_median', 'fast_median_ip', 'nth_element', 'nth_element_ip'})==3)


function strcell = numarray2strarray( vec )

N = length(vec);
strcell = cell( 1, N );
for i = 1:N
    strcell{i} = num2str( vec(i) );
end

end


function out = iembed(ob, x)
% recall that imask/omask and idim/odim are swapped on ctranspose
out = fatrix2_embed(ob.imask, ob.idim, x);


function spm_standalone(varargin)
% Gateway function for standalone SPM
%
% References:
%
%   SPM Standalone:  https://en.wikibooks.org/wiki/SPM/Standalone
%   MATLAB Compiler: http://www.mathworks.com/products/compiler/
%
% See also: config/spm_make_standalone.m
%__________________________________________________________________________
% Copyright (C) 2010-2017 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: spm_standalone.m 7372 2018-07-09 16:50:44Z guillaume $

if ~nargin, action = ''; else action = varargin{1}; end

if strcmpi(action,'run')
    warning('"Run" is deprecated: use "Batch".');
    action = 'batch';
end

exit_code = 0;

switch lower(action)

    case {'','pet','fmri','eeg','quit'}
    %----------------------------------------------------------------------
        spm(varargin{:});

    case {'-h','--help'}
    %----------------------------------------------------------------------
        cmd = lower(spm('Ver'));
        fprintf([...
            '%s - Statistical Parametric Mapping\n',...
            'https://www.fil.ion.ucl.ac.uk/spm/\n',...
            '\n'],...
            upper(cmd));
        fprintf([...
            'Usage: %s [ fmri | eeg | pet ]\n',...
            '       %s COMMAND [arg...]\n',...
            '       %s [ -h | --help | -v | --version ]\n',...
            '\n',...
            'Commands:\n',...
            '    batch          Run a batch job\n',...
            '    script         Execute a script\n',...
            '    function       Execute a function\n',...
            '    eval           Evaluate a MATLAB expression\n',...
            '    [NODE]         Run a specified batch node\n',...
            '\n',...
            'Options:\n',...
            '    -h, --help     Print usage statement\n',...
            '    -v, --version  Print version information\n',...
            '\n',...
            'Run ''%s [NODE] help'' for more information on a command.\n'],...
            cmd, cmd, cmd, cmd);

    case {'-v','--version'}
    %----------------------------------------------------------------------
        spm_banner;

    case 'batch'
    %----------------------------------------------------------------------
        inputs = varargin(2:end);
        flg = ismember(inputs,'--silent');
        if any(flg)
            quiet = true;
            inputs = inputs(~flg);
        else
            quiet = false;
        end
        flg = ismember(inputs,'--modality');
        if any(flg)
            idx = find(flg);
            try
                modality = inputs{idx+1};
            catch
                error('Syntax is: --modality <modality>.');
            end
            inputs([idx idx+1]) = [];
        else
            modality = 'fmri';
        end
        flg = ismember(inputs,'--cmdline');
        if any(flg)
            cmdline = true;
            inputs = inputs(~flg);
        else
            cmdline = false;
        end
        spm_banner(~quiet);
        spm('defaults',modality);
        spm_get_defaults('cmdline',cmdline);
        spm_jobman('initcfg');
        if isempty(inputs)
            h = spm_jobman;
            waitfor(h,'Visible','off');
        else
            try
                spm_jobman('run', inputs{:});
            catch
                fprintf('Execution failed: %s\n', inputs{1});
                exit_code = 1;
            end
        end
        spm('Quit');

    case 'script'
    %----------------------------------------------------------------------
        spm_banner;
        assignin('base','inputs',varargin(3:end));
        try
            if nargin > 1
                spm('Run',varargin(2));
            else
                spm('Run');
            end
        catch
            exit_code = 1;
        end

    case 'function'
    %----------------------------------------------------------------------
        spm_banner;
        if nargin == 1
            fcn = spm_input('function name','!+1','s','');
        else
            fcn = varargin{2};
        end
        try
            feval(fcn,varargin{3:end});
        catch
            exit_code = 1;
        end

    case 'eval'
    %----------------------------------------------------------------------
        spm_banner;
        if nargin == 1
            expr = spm_input('expression to evaluate','!+1','s','');
        else
            expr = varargin{2};
        end
        try
            eval(expr);
        catch
            exit_code = 1;
        end

    otherwise % cli
    %----------------------------------------------------------------------
        %spm('defaults','fmri');
        %spm_get_defaults('cmdline',true);
        spm_jobman('initcfg');
        try
            spm_cli(varargin{:});
        catch
            exit_code = 1;
        end

end

%-Display error message and return exit code (or use finish.m script)
%--------------------------------------------------------------------------
if exit_code ~= 0
    err = lasterror;
    msg{1} = err.message;
    if isfield(err,'stack')
        for i=1:numel(err.stack)
            if err.stack(i).line
                l = sprintf(' (line %d)',err.stack(i).line);
            else
                l = '';
            end
            msg{end+1} = sprintf('Error in %s%s',err.stack(i).name,l);
        end
    end
    fprintf('%s\n',msg{:});

    exit(exit_code);
end

%==========================================================================
function spm_banner(verbose)
% Display text banner
if nargin && ~verbose, return; end
[vspm,rspm] = spm('Ver');
tlkt = ver(spm_check_version);
if isdeployed, mcr = ' (standalone)'; else mcr = ''; end
fprintf('%s, version %s%s\n',vspm,rspm,mcr);
fprintf('%s, version %s\n',tlkt.Name,version);
spm('asciiwelcome');


function outlet = onl_lslsend_init(streamname,samplingrate,numchans,datatype)
if nargin<2
    samplingrate = 0;
end
if nargin<3
    numchans = 1;
end
if nargin<4
    datatype = 'cf_string';  % can also be cft_float32, etc...
end

% instantiate the library
lib = lsl_loadlib();
info = lsl_streaminfo(lib,streamname,'MATLAB-serialized',numchans,samplingrate,datatype,'whatevergd456546');
outlet = lsl_outlet(info);


classdef StokesComputer < handle

    properties (Access = public)
        computation
    end

    properties (Access = private)
        testName
    end

    methods (Access = public)
        function obj = StokesComputer(cParams)
            obj.testName = cParams.testName;
        end

        function compute(obj)
            a.fileName = obj.testName;
            s = StokesDataContainer(a);
            femSolver = FEM.create(s);
            femSolver.computeVariables;
            obj.computation = femSolver;
        end
    end

end


function a = in( x, y )

error( nargchk( 2, 2, nargin ) );
b = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '==' );
if nargout, a = b; end

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function [ links, params, requesturl, box] = opensearch( q )
%OPENSEARCH Queries GI-cat using the OpenSearch-geo interface
% Returns a list of available links from the matching resources
%
% Usage:  [ links, params, requesturl ] = opensearch( q )
%
%   q.endpoint = URL to opensearch server
%   q.string_text = text string to match
%   q.bbox= bounding box, vector [lon_min lon_max lat_min lat_max]
%       or string 'lon_min,lat_min,lon_max,lat_max'
%   q.time_start = start time, datenum/datestr or ISO string
%   q.time_end  = ending time, datenum/datestr or ISO string
%
% For full options and more explanation, see the GI-CAT OpenSearch doc
%    http://essi-lab.eu/cgi-bin/twiki/view/GIcat/OpenSearchGuide
%
% Example 1:
% q.endpoint='http://geoport.whoi.edu/gi-cat/services/opensearchgeo';
% q.string_text='sea_water_temperature';
% q.bbox=[-74.0 -66.0 39.0 45.];
% q.time_start='1999-01-20 04:33:45';
% q.time_end='1999-08-01 00:00:00';
% [links,params,request_url]=opensearch(q);   % make the query
% dap=links2dap(links); % find only the OPeNDAP links
%
% Example 2:
% q.endpoint='http://testbedapps.sura.org/gi-cat/services/opensearchgeo';
% q.string_text='sea_water_salinity';
% q.bbox=[-82 -73 36 40];
% q.time_start=[2000 06 20 04 33 45];
% q.time_end=[2006 08 01 00 00 00];
% [links,params,request_url]=opensearch(q);   % make the query
% dap=links2dap(links); % find only the OPeNDAP links
%
% Example 3:
% q.endpoint='http://geoport.whoi.edu/gi-cat/services/opensearchgeo';
% q.bbox=[-180 180 -30 70];  % whole globe from -30 to 70 north
% q.time_start=now_utc-28; % start 28 days ago
% q.time_end=now_utc;    % stop now
% q.string_text='relative_humidity'; %search for datasets containing 'relative_humidity'
% [links,params,request_url]=opensearch(q);   % make the query
% dap=links2dap(links); % find only the OPeNDAP links

if(nargin<1);help opensearch; return;end
if ~isfield(q,'endpoint'); disp('must define endpoint (URL)'); return; end
if ~isfield(q,'string_text'); q.string_text='';end
if ~isfield(q,'bbox')
    q.bbox='';
else
    if length(q.bbox)==4, % matlab style bbox [lon_min lon_max lat_min lat_max]
        q.bbox=sprintf('%g, %g, %g, %g',q.bbox([1 3 2 4]));
    end
end
if ~isfield(q,'time_start')
    q.time_start='';
else
    try
        dn=datenum(q.time_start); % handle datenum/datestr input
        q.time_start=datestr(dn,'yyyy-mm-ddTHH:MM:SSZ');
    catch
    end
end
if ~isfield(q,'time_end')
    q.time_end='';
else
    try
        dn=datenum(q.time_end);
        q.time_end=datestr(dn,'yyyy-mm-ddTHH:MM:SSZ');
    catch
    end
end
if ~isfield(q,'loc'); q.loc='';end
if ~isfield(q,'si'); q.si='1';end

% Default "&ct=&" returns only 10 records so specify default to be very
% large if not supplied.
if ~isfield(q,'ct'); q.ct='1000';end

% In GI-CAT 8.4, default "&rel=&" for rel:{geo:relation} returns
% records outside bounding box, so here we specify the default
% to be 'overlaps' if not supplied.  Options are
% {disjoint|overlaps|contains}
if ~isfield(q,'rel'); q.rel='overlaps';end

params = {
    'si';   q.si;
    'ct';   q.ct;
    'rel';  q.rel;
    'st';   q.string_text;
    'bbox'; q.bbox;
    'loc';  q.loc;
    'ts';   q.time_start;
    'te';   q.time_end;
    'outputFormat';'application/atom+xml';
    'enableCrawling'; 'false';
    };

% Optionally return the request URL used for the search
if nargout>2,
    requesturl=q.endpoint;
    for i=1:2:length(params)
        if (i == 1), separator = '?'; else separator = '&'; end
        param = char(java.net.URLEncoder.encode(params{i}));
        value = char(java.net.URLEncoder.encode(params{i+1}));
        requesturl = [requesturl separator param '=' value];
    end
end

% Execute the query
[results] = urlread(q.endpoint,'get', params);

% find all URL links
[~,~,~,~,links1]=regexp(results,'<gmd:URL>(.*?)</gmd:URL>','match'); % early versions of nciso/gicat
[~,~,~,~,links2]=regexp(results,'<dm:srvOp xmlns:dm="http://floraresearch.eu/sdi/services/7.0/dataModel/schema" name="(.*?)</dm:srvOp>','match'); % modern versions of nciso/gicat
for ind = 1:length(links2)
    link = links2(ind);
    st = regexp(link{1}, 'http');
    links2{ind}{1}(1:st{1}-1) = [];
end

% find all box values (bounding box)
[~,~,~,~,box]=regexp(results,'<box xmlns="http://www.georss.org/georss">(.*?)</box>','match');

if ~isempty(links2)
    links = links2;
else
    links = links1;
end

end


function nesp = nonempty_sp(sp)
% Returns the indices of non-empty sp

nesp = [];
for sus = 1:length(sp)
    if sp{sus}.size > 0
        nesp = [nesp, sus];
    end
end


function MakefMasksForAllFish(hfig)

% batch input data setup:
isFullData = 1;
data_masterdir = GetCurrentDataDir();

% M_fishset = GetFishStimset();
% M_stimrange = GetStimRange();

range_fish =  11:18; % range_fish = GetFishRange();

%% custom params here:
thres_minsize = 10000;
thres_maxsize = 6*10^5;

%%
for i = 1:length(range_fish),
    i_fish = range_fish(i);
    disp(i_fish);

        option
    [cIX,gIX,M_xyz_norm] = GetDefaultClustersFromLoad(hfig,i_fish,option);

    % Load fish
    LoadFullFish(hfig,i_fish,-1);
    absIX = getappdata(hfig,'absIX');
    ClusterIDs = GetClusterIDs();
    [cIX,gIX] = LoadCluster_Direct(i_fish,ClusterIDs(1),ClusterIDs(2),absIX);
    anat_stack_norm = getappdata(hfig,'anat_stack_norm');
    CellXYZ_norm = getappdata(hfig,'CellXYZ_norm');

    % make fMask for each auto-cluster
    fMASKs = [];
    MaskDatabase = sparse(0,0);
    mask_clusID = [];
    gIX = SqueezeGroupIX(gIX);
    for i_clus = 1:length(unique(gIX)),
        IX = find(gIX==i_clus);
        newMask = MakeFunctionalMask(anat_stack_norm,CellXYZ_norm,absIX,cIX(IX),'isBatch');
        sz = length(find(newMask));
        if sz>thres_minsize && sz<thres_maxsize,
            MaskDatabase(:, end+1) = newMask;
            mask_clusID = [mask_clusID;i_clus];
        end
    end
    fMASKs.MaskDatabase = MaskDatabase;
    fMASKs.mask_clusID = mask_clusID;
    fMASKs.i_fish = i_fish;
    fMASKs.note = 'Auto_defS_woA_Master0.5';
    % save:
    name = ['fMASKs_',num2str(i_fish),'.mat'];
    save(fullfile(data_masterdir,'fMASKs',name),'fMASKs');
end

github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/unused analyses/conserved cluster screens/obsl mask screen/MakefMasksForAllFish.m


function [gKern, gVarmeans, gVarcovars] = rbfardjitVardistPsi0Gradient(rbfardjitKern, vardist, covGrad)

% RBFARDJITVARDISTPSI0GRADIENT Description

% VARGPLVM

[gKern, gVarmeans, gVarcovars] = rbfard2VardistPsi0Gradient(rbfardjitKern, vardist, covGrad);


function track(imagefig,varargins)
global M
global Nsamples

%%% Setting figure properties to start tracking
set(gcf,'windowbuttondownfcn',@dataout);
set(gcf,'WindowButtonMotionFcn',@datain);
set(gcf,'userdata',[]);

%%% Creating initial input, since the filter will need samplea at
%%% n=0,-1,-2... When processing the X[n=1] sample.
for k=1:Nsamples
    temp=get(gca,'currentpoint');
    set(gcf,'userdata',[get(gcf,'userdata'); [temp(1,1:2), 0 ]]);
end
tic; % Begin time measuring


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

%%
clear; close all; clc;

%% Syntax
% |[M,G]=triSurf2ImSpec(F,V,voxelSize);|

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


function df = ipoptgp_callback_df(x,model)

global latest_x_f
global latest_df

x = x(:);
if isequal(x,latest_x_f)
    df = latest_df;
else
    [f,df] = fmincon_fungp(x,model);
    latest_df = df;
end


function net = initModel(param)
caffe.reset_all();
if exist(param.modelFile, 'file') == 0
  fprintf('%s does not exist. Start downloading ...\n', param.modelFile);
  downloadModel(param.modelName);
end
if ~exist(param.protoFile,'file')
  error('%s does not exist.', param.protoFile);
end

if param.useGPU
  fprintf('Using GPU Mode\n');
  caffe.set_mode_gpu();
  caffe.set_device(param.GPUID);
else
  fprintf('Using CPU Mode\n');
  caffe.set_mode_cpu;
end

net = caffe.Net(param.protoFile, param.modelFile, 'test');


function active_caffe_mex(gpu_id, caffe_version)
% active_caffe_mex(gpu_id, caffe_version)
% --------------------------------------------------------
% Faster R-CNN
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------

    % set gpu in matlab
    g = gpuDevice(gpu_id);

    if ~exist('caffe_version', 'var') || isempty(caffe_version)
        caffe_version = 'caffe';
    end
    cur_dir = pwd;
    caffe_dir = fullfile(pwd, 'external', 'caffe', 'matlab', caffe_version);

    if ~exist(caffe_dir, 'dir')
        warning('Specified caffe folder (%s) is not exist, change to default one (%s)', ...
            caffe_dir, fullfile(pwd, 'external', 'caffe', 'matlab'));
        caffe_dir = fullfile(pwd, 'external', 'caffe', 'matlab');
    end

    addpath(genpath(caffe_dir));
    cd(caffe_dir);
    caffe.set_device(gpu_id-1);
    cd(cur_dir);
end


%kPalette 'Palette Object Menuform'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros Palette.pane file
%
% Parameters:
% MultiChoice: paletteType 'Palette Type', default: 1: 'Type of palette to display'
%    Choices are:
%   1: 'Color Bar'
%   2: 'Color Cell'
%   3: 'Color Wheel'
% InputFile: colorColorfile ' InputFile', required: 'input file'
%
% Example: kPalette(colorColorfile, {'paletteType',1;'colorColorfile',''})
%
% Khoros helpfile follows below:
% .begin tagged
%
% .item "The Palette Visual Object"
% The palette visual object provides a visual display of the colors defined by a
% colormap.
%
% .item "Palette Type"
% This attribute specifies how the palette should be displayed; the palette
% may be displayed as a Color Bar, Color Cell, or Color Wheel.
%
% .item "Input File"
% This input file selection corresponds to the XVW_COLOR_COLORFILE attribute
% used by the palette object.  It is used to specify which input file should
% be used as the data object for which the palette will display colors.
%
% .end tagged

function varargout = kPalette(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,..] = kPalette(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'paletteType', 1;'colorColorfile', '__input'};
maxval={0,0};
minval={0,0};
istoggle=[0,0];
was_set=istoggle * 0;
paramtype={'MultiChoice','InputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; 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(0);
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
callKhoros([w 'Palette" '],Inputs,narglist);


%  INTERNAL FUNCTION: wishart distribution
%
%  Note:
%     One would rarely need to call distribution functions directly.
%     Refer to <densities.html> file for list of supported distributions.
%
%


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