if ~exist('n_ima'),
   fprintf(1,'No data to process.\n');
   return;
end;

if n_ima == 0,
    fprintf(1,'No image data available\n');
    return;
end;

if ~exist('active_images'),
	active_images = ones(1,n_ima);
end;
n_act = length(active_images);
if n_act < n_ima,
   active_images = [active_images ones(1,n_ima-n_act)];
else
   if n_act > n_ima,
      active_images = active_images(1:n_ima);
   end;
end;

ind_active = find(active_images);

% I did not call check_active_images, because I want to prevent a break
%check_active_images;

fprintf(1,'\nThis function is useful to select a subset of images to calibrate\n');

   fprintf(1,'\nThere are currently %d active images selected for calibration (out of %d):\n',length(ind_active),n_ima);

   if ~isempty(ind_active),

      if length(ind_active) > 2,

   		for ii = 1:length(ind_active)-2,

         	fprintf(1,'%d, ',ind_active(ii));

      	end;

      	fprintf(1,'%d and %d.',ind_active(end-1),ind_active(end));

      else

         if length(ind_active) == 2,

            fprintf(1,'%d and %d.',ind_active(end-1),ind_active(end));

         else

            fprintf(1,'%d.',ind_active(end));

         end;

      end;

   end;

   fprintf(1,'\n');

   if length(ind_active)==0,
      fprintf(1,'\nYou probably want to add images\n');
      choice = 1;
   else
      if length(ind_active)==n_ima,
         fprintf(1,'\nYou probably want to suppress images\n');
         choice = 0;
      else
         choice = 2;
      end;
   end;

   if (choice~=0) & (choice ~=1),
   	fprintf(1,'\nDo you want to suppress or add images from that list?\n');
   end;

while (choice~=0)&(choice~=1),
   choice = input('For suppressing images enter 0, for adding images enter 1 ([]=no change): ');
   if isempty(choice),
      fprintf(1,'No change applied to the list of active images.\n');
      return;
   end;
   if (choice~=0)&(choice~=1),
      disp('Bad entry. Try again.');
   end;
end;

if choice,

	ima_numbers = input('Number(s) of image(s) to add ([] = all images) = ');

if isempty(ima_numbers),
	   fprintf(1,'All %d images are now active\n',n_ima);
   	ima_proc = 1:n_ima;
	else
   	ima_proc = ima_numbers;
	end;

else

	ima_numbers = input('Number(s) of image(s) to suppress ([] = no image) = ');

	if isempty(ima_numbers),
      fprintf(1,'No image has been suppressed. No modication of the list of active images.\n',n_ima);
   	ima_proc = [];
	else
   	ima_proc = ima_numbers;
	end;

end;

if ~isempty(ima_proc),

   active_images(ima_proc) = choice * ones(1,length(ima_proc));

end;

   check_active_images;

   fprintf(1,'\nThere is now a total of %d active images for calibration:\n',length(ind_active));

   if ~isempty(ind_active),

      if length(ind_active) > 2,

   		for ii = 1:length(ind_active)-2,

         	fprintf(1,'%d, ',ind_active(ii));

      	end;

      	fprintf(1,'%d and %d.',ind_active(end-1),ind_active(end));

      else

         if length(ind_active) == 2,

            fprintf(1,'%d and %d.',ind_active(end-1),ind_active(end));

         else

            fprintf(1,'%d.',ind_active(end));

         end;

      end;

   end;

   fprintf(1,'\n\nYou may now run ''Calibration'' to recalibrate based on this new set of images.\n');


%% Define params
s_cam_definitions;

%% Load image for pathway xforms
ni_seg = niftiRead(fullfile(mask_dir,seg_filename));
% Calc xform from camino space to acpc space
xform = ni_seg.qto_xyz;
xform(1:3,1:3) = eye(3);
xform_cam_to_acpc = xform;
xform_cam_to_acpc(1:3,4) = xform_cam_to_acpc(1:3,4)+diag(ni_seg.qto_xyz(1:3,1:3))/2;
xform_img_to_acpc = ni_seg.qto_xyz;
fd_size = ni_seg.dim;

%% Fix image header
%filename = fullfile(camino_dir,'acm','t_mesd_gm_rh_exit_1cm_acm_sc.nii.gz');
filename = fullfile(camino_dir,'fa.nii.gz');
ni = niftiRead(filename);
dtiWriteNiftiWrapper(ni.data, xform_img_to_acpc, filename);

%% Load generated paths
% Load camino path file
tractsFile = fullfile(camino_dir,'tracts_clean.Bfloat');
fg_temp = mtrImportFibers(tractsFile);
fg = dtiNewFiberGroup;
fg.fibers = fg_temp.fibers;
%fg = dtiXformFiberCoords(fg, xform_cam_to_acpc);
mtrExportFibers(fg,fullfile(camino_dir,'tracts.pdb'));

%% Make fiber density map of all occ lobe
tractsFile = fullfile(camino_dir,'tracts_occ.Bfloat');
fg_temp = mtrImportFibers(tractsFile,eye(4));
fg = dtiNewFiberGroup;
fg.fibers = fg_temp.fibers;
fg = dtiXformFiberCoords(fg, xform_cam_to_acpc);
fd_img = dtiComputeFiberDensityNoGUI(fg, xform_img_to_acpc, fd_size);
dtiWriteNiftiWrapper(fd_img, xform_img_to_acpc, fullfile(camino_dir,'tracts_occ.nii.gz'));
% Intersect occ map with cortex
tracts_filename = 'tracts_occ.nii.gz';
ni_tracts = niftiRead(fullfile(camino_dir, tracts_filename));
ni_c = niftiRead(fullfile(mask_dir,'gm.nii.gz'));
ni_tracts.fname = fullfile(camino_dir,'tracts_occ_gm.nii.gz');
ni_tracts.data(ni_c.data==0) = 0;
writeFileNifti(ni_tracts);
% Intersect with retinotopic cortex
ni_tracts = niftiRead(fullfile(camino_dir, tracts_filename));
ni_c = niftiRead(fullfile(mask_dir,'atlas_mask.nii.gz'));
ni_tracts.fname = fullfile(camino_dir,'tracts_occ_atlas.nii.gz');
ni_tracts.data(ni_c.data==0) = 0;
writeFileNifti(ni_tracts);

%% Make fiber density map of exiting occ lobe
tractsFile = fullfile(camino_dir,'tracts_occ_exit.Bfloat');
fg_temp = mtrImportFibers(tractsFile,eye(4));
fg = dtiNewFiberGroup;
fg.fibers = fg_temp.fibers;
fg = dtiXformFiberCoords(fg, xform_cam_to_acpc);
fd_img = dtiComputeFiberDensityNoGUI(fg, xform_img_to_acpc, fd_size);
dtiWriteNiftiWrapper(fd_img, xform_img_to_acpc, fullfile(camino_dir,'tracts_occ_exit.nii.gz'));
% Intersect occ map with cortex
tracts_filename = 'tracts_occ_exit.nii.gz';
ni_tracts = niftiRead(fullfile(camino_dir, tracts_filename));
ni_c = niftiRead(fullfile(mask_dir,'gm.nii.gz'));
ni_tracts.fname = fullfile(camino_dir,'tracts_occ_exit_gm.nii.gz');
ni_tracts.data(ni_c.data==0) = 0;
writeFileNifti(ni_tracts);
% Intersect with retinotopic cortex
ni_tracts = niftiRead(fullfile(camino_dir, tracts_filename));
ni_c = niftiRead(fullfile(mask_dir,'atlas_mask.nii.gz'));
ni_tracts.fname = fullfile(camino_dir,'tracts_occ_exit_atlas.nii.gz');
ni_tracts.data(ni_c.data==0) = 0;
writeFileNifti(ni_tracts);

%% Tract surface measurements

%% Fix residual image
ni_b0 = niftiRead(fullfile(dti_dir,'b0.nii.gz'));
ni = niftiRead(fullfile(camino_dir,'wdt_rmsqr.nii.gz'));
ni_b0.fname =  fullfile(camino_dir,'wdt_rmsqr.nii.gz');
ni_b0.data = ni.data;
%ni_b0.data = ni.data(1:-1:end,:,:);
writeFileNifti(ni_b0);

%% Examine residuals
ni_mse = niftiRead(fullfile(camino_dir,'wdt_rmsqr.nii.gz'));
ni_std = niftiRead(fullfile(camino_dir,'wdt_std.nii.gz'));
ni_std.data(ni_std.data>100) = 100;
ni_mse.data(ni_mse.data>100) = 100;
showMontage(ni_std.data)
showMontage(ni_mse.data)
e_ratio = zeros(ni_std.dim);
e_ratio(ni_std.data>0) = ni_mse.data(ni_std.data>0) ./ ni_std.data(ni_std.data>0);
showMontage(e_ratio)

% Fix label image
filename_labels = fullfile(camino_dir,'cbs_labels_1_1_0.nii.gz');
ni = niftiRead(filename_labels);
ni_labels = ni_occ;
ni_labels.fname = filename_labels;
ni_labels.data = ni.data;
writeFileNifti(ni_labels);

filename_labels = fullfile(camino_dir,'cbs_labelcp_1_1_0.nii.gz');
ni = niftiRead(filename_labels);
ni_labels = ni_occ;
ni_labels.fname = filename_labels;
ni_labels.data = ni.data;
writeFileNifti(ni_labels);


classdef AltitudeOptimizationVariable < AbstractOptimizationVariable
    %AltitudeOptimizationVariable Summary of this class goes here
    %   Detailed explanation goes here

    properties
        varObj(1,1) AltitudeTermCondition = AltitudeTermCondition(0);

        lb(1,1) double = 0;
        ub(1,1) double = 0;

        useTf(1,1) = false;
    end

    methods
        function obj = AltitudeOptimizationVariable(varObj)
            obj.varObj = varObj;
            obj.varObj.optVar = obj;

            obj.id = rand();
        end

        function x = getXsForVariable(obj)
            x = [];

            if(obj.useTf)
                x = obj.varObj.altitude;
            end
        end

        function [lb, ub] = getBndsForVariable(obj)
            lb = obj.lb(obj.useTf);
            ub = obj.ub(obj.useTf);
        end

        function [lb, ub] = getAllBndsForVariable(obj)
            lb = obj.lwrBnd;
            ub = obj.uprBnd;
        end

        function setBndsForVariable(obj, lb, ub)
            obj.lb = lb;
            obj.ub = ub;
        end

        function useTf = getUseTfForVariable(obj)
            useTf = obj.useTf;
        end

        function setUseTfForVariable(obj, useTf)
            obj.useTf = useTf;
        end

        function updateObjWithVarValue(obj, x)
            obj.varObj.altitude = x;
        end

        function nameStrs = getStrNamesOfVars(obj, evtNum, varLocType)
            nameStrs = {sprintf('Event %i Altitude Termination Condition', evtNum)};
        end
    end
end


%mmf writer
function [keyframes,nframes]=mmfwriter2(inputfile,outputfile,obj,firstframe,lastframe)

%obj=VideoReader(inputfile);
foutput=fopen(outputfile,'wb');
%load text
ftexto=fopen('/groups/visitors/home/albam/Desktop/mmfreader/text.text');

texto=[];
for i=1:15
linea=fgets(ftexto);
texto=[texto linea];
end

%write header text
fwrite(foutput,texto,'char')
% end of the header
fwrite(foutput,0,'char')
%id_code
d=hex2dec('a3d2d45d');
fwrite(foutput,d,'ulong')
%header size
fwrite(foutput,10240,'int')
%calculate keyframes
keyframes=fix((lastframe-firstframe+1)/180)+1;
%keyframe
fwrite(foutput,keyframes,'int')
%other recording parameters TODO
% zero padded to reach header size
for i=ftell(foutput)+1:10240
fwrite(foutput,0,'uint8');
end
%calculate nframes
%
nframes=zeros(1,keyframes);
nframes(1:end-1)=180;
nframes(end)=(lastframe-firstframe+1)-(keyframes-1)*180;

isfirst=1;
% for the stacks
for stack=1:keyframes

%Image Stacks
begining_header=ftell(foutput);
%idcode
d=hex2dec('bb67ca20');
fwrite(foutput,d,'ulong')
%header size
fwrite(foutput,512,'int')
%total size of stack in disk TODO
fwrite(foutput,0,'int')
%nframes in this stack default=180 but the last one can be smaller
fwrite(foutput,nframes(stack),'int');
% zero padded to reach header size
for i=ftell(foutput)-begining_header+1:512
fwrite(foutput,0,'uint8');
end

%Backgorund image
begining_header=ftell(foutput);
%header size
fwrite(foutput,112,'int')
%imageid
fwrite(foutput,0,'int')
%numchannels
fwrite(foutput,1,'int')
%alphachannel
fwrite(foutput,0,'int')
%depth
fwrite(foutput,8,'int')
%colormodel
fwrite(foutput,[0 0 0 0],'char')
%channel seq
fwrite(foutput,[0 0 0 0],'char')
%data order
fwrite(foutput,0,'int')
% origin
fwrite(foutput,0,'int')
%align should 4 or 8 TODO
fwrite(foutput,0,'int')
%width
fwrite(foutput,obj.width,'int')
%height
fwrite(foutput,obj.height,'int')
%roi 0=> full image
fwrite(foutput,0,'int')
%mask roi
fwrite(foutput,0,'int')
%im id
fwrite(foutput,0,'int')
%tile info
fwrite(foutput,0,'int')
%images size (heightxwidth
fwrite(foutput,obj.width*obj.height,'int')
%imagedata
fwrite(foutput,0,'int')
%widthstep
fwrite(foutput,obj.width,'int')
%bordermode
fwrite(foutput,0,'int')
%borderconst
fwrite(foutput,0,'int')
%imagedataorigin
fwrite(foutput,0,'int')
% zero padded to reach header size
for i=ftell(foutput)-begining_header+1:112
fwrite(foutput,0,'uint8');
end
s=0;
im=zeros(obj.width,obj.height,nframes(stack));
if isfirst==1
    for i=firstframe:firstframe+nframes(stack);
        s=s+1;
        imrgbtemp=read(obj,i);
        imrgbtemp=double(imrgbtemp);
        im(:,:,s)=(sum(imrgbtemp,3)/3)';
    end
    isfirst=0;
else
    for i=firstframe+sum(nframes(1:stack-1)):firstframe+sum(nframes(1:stack))
        s=s+1;
        imrgbtemp=read(obj,i);
        imrgbtemp=double(imrgbtemp);
        im(:,:,s)=(sum(imrgbtemp,3)/3)';
    end
end

%%creting mean backgfix
bkgim=median(im,3);
%writing background image
fwrite(foutput,reshape(bkgim',1,obj.width*obj.height))

%Extracting larvae out of the images

 frames=zeros(size(im));
 SE=strel('disk',8);
 bounding=cell(1,nframes(stack));

for i=1:nframes(stack)
   begining_header=ftell(foutput);
   %id code
   d=hex2dec('f80921af');
   fwrite(foutput,d,'ulong')
   %header size
   fwrite(foutput,1024,'int')
   %depth
   fwrite(foutput,8,'int')
   %nchannels
   fwrite(foutput,1,'int')

   %calculating numims
    frames(:,:,i)=abs(im(:,:,i)-bkgim);
    %threshold automatically set
    %level(i)=graythresh(frames(:,:,i));
     bw=zeros(size(frames(:,:,1)));
     bw(frames(:,:,i)*10>max(max(frames(:,:,i))))=1;
     bw2=bwareaopen(bw,7);
     dilated=imdilate(bw2,SE);
     cc=bwconncomp(dilated);

     %numims
     fwrite(foutput,cc.NumObjects,'int')
     % zero padded to reach header size
        for k=ftell(foutput)-begining_header+1:1024
        fwrite(foutput,0,'uint8');
        end
%     %Creating bounding box
     STATS=regionprops(cc,'BoundingBox');
      bounding{i}=zeros(cc.NumObjects,4);
     for j=1:cc.NumObjects
         bounding{i}(j,:)=STATS(j,1).BoundingBox;
         %temp=zeros(fix(bounding{i}(j,4)),fix(bounding{i}(j,3)));
         if fix(bounding{i}(j,2))==0 && fix(bounding{i}(j,1))==0
            temp=im(1:fix(bounding{i}(j,4)),1:fix(bounding{i}(j,3)),i);
        elseif fix(bounding{i}(j,2))==0
            temp=im(1:fix(bounding{i}(j,4)),fix(bounding{i}(j,1)):fix(bounding{i}(j,1))+fix(bounding{i}(j,3))-1,i);
        elseif fix(bounding{i}(j,1))==0
            temp=im(fix(bounding{i}(j,2)):fix(bounding{i}(j,2))+fix(bounding{i}(j,4))-1,1:fix(bounding{i}(j,3)),i);
        else
            temp=im(fix(bounding{i}(j,2)):fix(bounding{i}(j,2))+fix(bounding{i}(j,4))-1,fix(bounding{i}(j,1)):fix(bounding{i}(j,1))+fix(bounding{i}(j,3))-1,i);
         end
        fwrite(foutput,fix(bounding{i}(j,:)),'int')
        fwrite(foutput,reshape(temp',1,fix(bounding{i}(j,3))*fix(bounding{i}(j,4))))
      end

end

end
fclose(foutput)


%% set parameters
folderpath = '/home/gyeongsikmoon/workspace//Data/Hand_pose_estimation/HANDS2017/training/images/';
filepath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/HANDS2017/training/Training_Annotation.txt';
frameNum = 957032;

%folderpath = '/home/gyeongsikmoon/workspace//Data/Hand_pose_estimation/HANDS2017/frame/images/';
%filepath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/HANDS2017/frame/BoundingBox.txt';
%frameNum = 295510;

fp = fopen(filepath);
fid = 1;

tline = fgetl(fp);
while fid <= frameNum

    disp(fid);

    splitted = strsplit(tline);
    img_name = splitted{1};

    if exist(strcat(folderpath,img_name), 'file')
        img = imread(strcat(folderpath,img_name));

        fp_save = fopen(strcat(folderpath,img_name(1:size(img_name,2)-3),'bin'),'w');
        fwrite(fp_save,permute(img,[2,1,3]),'float');
        fclose(fp_save);

        %delete(strcat(folderpath,img_name));
    end

    tline = fgetl(fp);
    fid = fid + 1;
end

fclose(fp);


%mmf writer
function [keyframes,nframes]=mmfwritertrans(inputfile,outputfile,obj,firstframe,lastframe)

%obj=VideoReader(inputfile);
foutput=fopen(outputfile,'wb');
%load text
ftexto=fopen('/groups/visitors/home/albam/Desktop/mmfreader/text.text');

texto=[];
for i=1:15
linea=fgets(ftexto);
texto=[texto linea];
end

%write header text
fwrite(foutput,texto,'char')
% end of the header
fwrite(foutput,0,'char')
%id_code
d=hex2dec('a3d2d45d');
fwrite(foutput,d,'ulong')
%header size
fwrite(foutput,10240,'int')
%calculate keyframes
keyframes=fix((lastframe-firstframe+1)/180)+1;
%keyframe
fwrite(foutput,keyframes,'int')
%other recording parameters TODO
% zero padded to reach header size
for i=ftell(foutput)+1:10240
fwrite(foutput,0,'uint8');
end
%calculate nframes
%
nframes=zeros(1,keyframes);
nframes(1:end-1)=180;
nframes(end)=(lastframe-firstframe+1)-(keyframes-1)*180;

isfirst=1;
% for the stacks
for stack=1:keyframes

%Image Stacks
begining_header=ftell(foutput);
%idcode
d=hex2dec('bb67ca20');
fwrite(foutput,d,'ulong')
%header size
fwrite(foutput,512,'int')
%total size of stack in disk TODO
fwrite(foutput,0,'int')
%nframes in this stack default=180 but the last one can be smaller
fwrite(foutput,nframes(stack),'int');
% zero padded to reach header size
for i=ftell(foutput)-begining_header+1:512
fwrite(foutput,0,'uint8');
end

%Backgorund image
begining_header=ftell(foutput);
%header size
fwrite(foutput,112,'int')
%imageid
fwrite(foutput,0,'int')
%numchannels
fwrite(foutput,1,'int')
%alphachannel
fwrite(foutput,0,'int')
%depth
fwrite(foutput,8,'int')
%colormodel
fwrite(foutput,[0 0 0 0],'char')
%channel seq
fwrite(foutput,[0 0 0 0],'char')
%data order
fwrite(foutput,0,'int')
% origin
fwrite(foutput,0,'int')
%align should 4 or 8 TODO
fwrite(foutput,0,'int')
%width
fwrite(foutput,obj.width,'int')
%height
fwrite(foutput,obj.height,'int')
%roi 0=> full image
fwrite(foutput,0,'int')
%mask roi
fwrite(foutput,0,'int')
%im id
fwrite(foutput,0,'int')
%tile info
fwrite(foutput,0,'int')
%images size (heightxwidth
fwrite(foutput,obj.width*obj.height,'int')
%imagedata
fwrite(foutput,0,'int')
%widthstep
fwrite(foutput,obj.width,'int')
%bordermode
fwrite(foutput,0,'int')
%borderconst
fwrite(foutput,0,'int')
%imagedataorigin
fwrite(foutput,0,'int')
% zero padded to reach header size
for i=ftell(foutput)-begining_header+1:112
fwrite(foutput,0,'uint8');
end
s=0;
im=zeros(obj.width,obj.height,nframes(stack));
if isfirst==1
    for i=firstframe:firstframe+nframes(stack);
        s=s+1;
        imrgbtemp=read(obj,i);
        imrgbtemp=double(imrgbtemp);
        imtemp=sum(imrgbtemp,3)/3;
        im(:,:,s)=imtemp';
    end
    isfirst=0;
else
    for i=firstframe+sum(nframes(1:stack-1)):firstframe+sum(nframes(1:stack))
        s=s+1;
        imrgbtemp=read(obj,i);
        imrgbtemp=double(imrgbtemp);
        imtemp=sum(imrgbtemp,3)/3;
        im(:,:,s)=imtemp';
    end
end

%%creting mean backgfix
bkgim=median(im,3);
%writing background image
fwrite(foutput,reshape(bkgim',1,obj.width*obj.height))

%Extracting larvae out of the images

 frames=zeros(size(im));
 SE=strel('disk',8);
 bounding=cell(1,nframes(stack));

for i=1:nframes(stack)
   begining_header=ftell(foutput);
   %id code
   d=hex2dec('f80921af');
   fwrite(foutput,d,'ulong')
   %header size
   fwrite(foutput,1024,'int')
   %depth
   fwrite(foutput,8,'int')
   %nchannels
   fwrite(foutput,1,'int')

   %calculating numims
    frames(:,:,i)=abs(im(:,:,i)-bkgim);
    %threshold automatically set
    %level(i)=graythresh(frames(:,:,i));
     bw=zeros(size(frames(:,:,1)));
     bw(frames(:,:,i)*10>max(max(frames(:,:,i))))=1;
     bw2=bwareaopen(bw,7);
     dilated=imdilate(bw2,SE);
     cc=bwconncomp(dilated);

     %numims
     fwrite(foutput,cc.NumObjects,'int')
     % zero padded to reach header size
        for k=ftell(foutput)-begining_header+1:1024
        fwrite(foutput,0,'uint8');
        end
%     %Creating bounding box
     STATS=regionprops(cc,'BoundingBox');
      bounding{i}=zeros(cc.NumObjects,4);
     for j=1:cc.NumObjects
         bounding{i}(j,:)=STATS(j,1).BoundingBox;
         %temp=zeros(fix(bounding{i}(j,4)),fix(bounding{i}(j,3)));
         if fix(bounding{i}(j,2))==0 && fix(bounding{i}(j,1))==0
            temp=im(1:fix(bounding{i}(j,4)),1:fix(bounding{i}(j,3)),i);
        elseif fix(bounding{i}(j,2))==0
            temp=im(1:fix(bounding{i}(j,4)),fix(bounding{i}(j,1)):fix(bounding{i}(j,1))+fix(bounding{i}(j,3))-1,i);
        elseif fix(bounding{i}(j,1))==0
            temp=im(fix(bounding{i}(j,2)):fix(bounding{i}(j,2))+fix(bounding{i}(j,4))-1,1:fix(bounding{i}(j,3)),i);
        else
            temp=im(fix(bounding{i}(j,2)):fix(bounding{i}(j,2))+fix(bounding{i}(j,4))-1,fix(bounding{i}(j,1)):fix(bounding{i}(j,1))+fix(bounding{i}(j,3))-1,i);
         end
        fwrite(foutput,fix(bounding{i}(j,[2 1 4 3])),'int')
        fwrite(foutput,reshape(temp',1,fix(bounding{i}(j,3))*fix(bounding{i}(j,4))))
      end

end

end
fclose(foutput)


function test_issue1334

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_selectdata ft_channelselection

load(dccnpath('/home/common/matlab/fieldtrip/data/test/test_issue1334.mat'));

%%

cfg = [];
cfg.channel={'megref'}; % reference data

dataRef = ft_preprocessing(cfg, data);
assert(numel(dataRef.label)==27);

%%
% see https://github.com/fieldtrip/fieldtrip/pull/1342#issuecomment-601265279

data = [];
data.label = {};

% this should return empty, but it gave an error
assert(isempty(ft_channelselection('MLO', data)));


% PURPOSE  : 	Clears ERPset(s)
%
% FORMAT   :
%
% >> ALLERP = pop_deleterpset( ALLERP, index);
%
% EXAMPLE  :
%
% >> ALLERP = pop_deleterpset( ALLERP, [3 5]);
%
% INPUTS   :
%
% ALLERP    - Includes all ERPsets in workspace
% Index     - ERPset(s) that you want to clear from the workspace
%
% OUTPUTS  :
%
% - updated (output) ALLERP. Will include all ERPsets, minus that deleted
%
% *** This function is part of ERPLAB Toolbox ***
% Author: Javier Lopez-Calderon
% Center for Mind and Brain
% University of California, Davis,
% Davis, CA
% 2009

function [ALLERP, erpcom] = pop_deleterpset(ALLERP, varargin)
erpcom = '';
if nargin<1
        help pop_deleterpset
end
if nargin==1
        try
                CURRENTERP = evalin('base', 'CURRENTERP');
        catch
                CURRENTERP = 0;
        end
        if  CURRENTERP == 0
                msgboxText =  'ERPsets menu is already empty...';
                title      =  'ERPLAB: no erpset(s)';
                errorfound(msgboxText, title);
                return
        end

        prompt    = {'Erpset(s) to clear:'};
        dlg_title = 'Delete erpset(s)';
        num_lines = 1;
        def = {num2str(CURRENTERP)}; %01-13-2009

        %
        % open window
        %
        answer = inputvalue(prompt,dlg_title,num_lines,def);

        if isempty(answer)
                disp('User selected Cancel')
                return
        end

        erpindex =  str2num(answer{1});
        nerpset  = length(ALLERP);
        erpindex = unique_bc2(erpindex);

        if isempty(erpindex)
                msgboxText =  'Wrong erpset index(es)';
                title      =  'ERPLAB: unrecognizable erpset(s)';
                errorfound(msgboxText, title);
                return
        end
        if max(erpindex)>nerpset || min(erpindex)<1
                erpm     = findobj('tag', 'linerp');
                nerpmenu = length(erpm);
                if max(erpindex)<=nerpmenu && nerpmenu>=1 && max(erpindex)>=1
                        %...
                else
                        msgboxText = ['Wrong erpset index(es)\n'...
                                'Check your erpset menu or write length(ALLERP) at command window for comprobation'];
                        title        =  'ERPLAB: pop_deleterpset not existing erpset(s)';
                        errorfound(sprintf(msgboxText), title);
                        return
                end
        end

        %
        % Somersault
        %
        [ALLERP, erpcom] = pop_deleterpset(ALLERP, 'Erpsets', erpindex, 'Saveas', 'on','History', 'gui');
        return
end

%
% Parsing inputs
%
p = inputParser;
p.FunctionName  = mfilename;
p.CaseSensitive = false;
p.addRequired('ALLERP');
% option(s)
p.addParamValue('Erpsets', 1); % erpset index or input file
p.addParamValue('Warning', 'off', @ischar); % history from scripting
p.addParamValue('Saveas', 'off', @ischar); % 'on', 'off'
p.addParamValue('History', 'script', @ischar); % history from scripting
p.parse(ALLERP, varargin{:});

erpindex = p.Results.Erpsets;
if strcmpi(p.Results.Warning,'on')
        warnop = 1;
else
        warnop = 0;
end
if ismember_bc2({p.Results.Saveas}, {'on','yes'})
        issaveas  = 1;
else
        issaveas  = 0;
end
if strcmpi(p.Results.History,'implicit')
        shist = 3; % implicit
elseif strcmpi(p.Results.History,'script')
        shist = 2; % script
elseif strcmpi(p.Results.History,'gui')
        shist = 1; % gui
else
        shist = 0; % off
end
nerpset = length(ALLERP);
erpindex   = unique_bc2(erpindex);

if isempty(erpindex)
        msgboxText =  'Wrong erpset index(es)';
        error(['ERPLAB says: ' msgboxText])
end
if max(erpindex)>nerpset || min(erpindex)<1
        msgboxText = 'Wrong erpset index(es)';
        error(['ERPLAB says: ' msgboxText])
end
detect   = ~ismember_bc2(1:nerpset,erpindex);
newindex = find(detect);
if isempty(newindex)
        ALLERP = [];
else
        ALLERP = ALLERP(newindex);
end
if issaveas
        updatemenuerp(ALLERP, -1)
        assignin('base','ALLERP',ALLERP);  % save to workspace. Dec 5, 2012
end
% erpcom = sprintf('ALLERP = pop_deleterpset( ALLERP, [%s]);', num2str(erpindex));
%
% History
%
skipfields = {'ALLERP', 'History'};
fn     = fieldnames(p.Results);
erpcom = sprintf( '%s = pop_deleterpset( %s ', inputname(1), inputname(1) );
for q=1:length(fn)
        fn2com = fn{q};
        if ~ismember_bc2(fn2com, skipfields)
                fn2res = p.Results.(fn2com);
                if ~isempty(fn2res)
                        if ischar(fn2res)
                                if ~strcmpi(fn2res,'off')
                                        erpcom = sprintf( '%s, ''%s'', ''%s''', erpcom, fn2com, fn2res);
                                end
                        else
                                if iscell(fn2res)
                                        if ischar([fn2res{:}])
                                                fn2resstr = sprintf('''%s'' ', fn2res{:});
                                        else
                                                fn2resstr = vect2colon(cell2mat(fn2res), 'Sort','on');
                                        end
                                        fnformat = '{%s}';
                                else
                                        fn2resstr = vect2colon(fn2res, 'Sort','on');
                                        fnformat = '%s';
                                end
                                if strcmpi(fn2com,'Criterion')
                                        if p.Results.Criterion<100
                                                erpcom = sprintf( ['%s, ''%s'', ' fnformat], erpcom, fn2com, fn2resstr);
                                        end
                                else
                                        erpcom = sprintf( ['%s, ''%s'', ' fnformat], erpcom, fn2com, fn2resstr);
                                end
                        end
                end
        end
end
erpcom = sprintf( '%s );', erpcom);

% get history from script. ERP
switch shist
        case 1 % from GUI
                displayEquiComERP(erpcom);
        case 2 % from script
                for i=1:length(ALLERP)
                        ALLERP(i) = erphistory(ALLERP(i), [], erpcom, 1);
                end
        case 3
                % implicit

                %for i=1:length(ALLERP)
                %        ALLERP(i) = erphistory(ALLERP(i), [], erpcom, 1);
                %end
                %fprintf('%%Equivalent command:\n%s\n\n', erpcom);
        otherwise %off or none
                erpcom = '';
end

%
% Completion statement
%
msg2end
eeglab redraw
return


function [str,iter]=display_simple(comp,tab,iter)

  global display_tree_array_indexing;
  if isempty(display_tree_array_indexing)
      display_tree_array_indexing=2;
  end;
  global display_tree_index_at_front;
  if isempty(display_tree_index_at_front)
      display_tree_index_at_front=1;
  end;

  if nargin==3
   if isempty(iter)
    iter{1}=[];
   else
      i=length(iter);
      iter{i+1}=iter{i};  %% <--- new member of tree
   end

   if display_tree_array_indexing==0
     if isempty(iter{length(iter)})
      index=[];
     else
      index=[num2str(length(iter)-1) ':'];
     end
     if display_tree_index_at_front
      str=[ index get_name(comp) '\n'];
     else
      str=[ get_name(comp) ' (' index(length(index))  ')\n'];
     end;
   else
     index=[];
     if ~isempty(iter{length(iter)})
      index= num2str(iter{length(iter)});
      a=find(index==32);
      a=a(1:2:length(a));
      a=setdiff([1:length(index)],a);
      index=index(a);

      if display_tree_array_indexing==2
         index= num2str(iter{length(iter)});
	     fTmp=find(index==' ');
         fTmp=max(setdiff(fTmp,length(index)));
	        if ~isempty(fTmp)
	            index=index(fTmp+1:length(index));
        	end
      end
      index=['[' index ']:'];
     end;

     if display_tree_index_at_front
      str=[ index  get_name(comp) '\n'];
     else
      str=[ get_name(comp)  ' ' index(1:length(index)-1)  '\n'];
     end;
   end

  else
   disp([get_name(comp)]);
  end


function view = selectROI(view,n)
%
% view = selectROI(view,n)
%
% Selects the Nth ROI in view.ROIs to be the selected ROI by
% setting the view.selectedROI field.
%
% If isstr(n), then the ROI with the name n is selected.
%
% djh, 1/26/98
% bw,aab  Allowed n to be a string.
% ras, 8/17/04 -- for volume views, auto centers on the selected ROI.
% prevRoi = view.selectedROI; % useful for fast redraws below

if isstr(n)
    roiName = n;
    if ~isempty(view.ROIs)
        nROIs = length(view.ROIs);
        for ii=1:nROIs
            if strmatch(roiName,view.ROIs(ii).name);
                view = selectROI(view,ii);
                return;
            end
		end
		view.selectedROI = 0;
        warning(sprintf('No ROI with name %s.',roiName));
    else
        warning(sprintf('No ROIs in current view.'));
    end

elseif ~isempty(view.ROIs)
    % Select it
    view.selectedROI = n;
    % Reset prevCoords
    view.prevCoords = [];
else
    view.selectedROI = 0;
end

% Update the ROI popup menu and ROI lines, if they exist
% (won't for hidden views)
if checkfields(view, 'ui', 'ROI', 'popupHandle')
    setROIPopup(view);
%     view = refreshScreen(view);
end

return;


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

%%
clear; close all; clc;

%% Syntax
% |d=divisors(x,arg);|

%% 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 keyinfo
%% KEYINFO catch all the keyboard infomation
% The function requires no input arguments and return a value in terms of
% a column vector [3 x 1]
%
% Finally, I wish you will enjoy this tiny function, and any comment is
% appreciated
%
% Name: Fu-Sung Wang
% E-mail: fusung.wang@gmail.com
% Organization: www.terasoft.com.tw


function dark_mode(use_dark_mode)
  % DARK_MODE  Switch command and figures windows to dark background with light
  % text.
  %
  % dark_mode
  % dark_mode(flag)
  %
  % Optional input:
  %   flag  whether to switch to dark mode {false} or back to default (true)
  %
  % Examples:
  %   % Place this in startup.m to add a timer that checks every 5mins whether
  %   % its ≥6am or ≥6pm and toggles dark mode accordingly.
  %   dmt = timer('TimerFcn',@(x,y) dark_mode(mod(clock*[0;0;0;1;0;0]+6,24)<12),'Period',60*5,'ExecutionMode','fixedDelay');
  %   start(dmt);
  %
  %   % Detect if Mac OS X is dark and match
  %   dark_mode(system('defaults read -g AppleInterfaceStyle 2&>/dev/null')==0);
  %

  % Adapted from:
  % https://github.com/benhager/solarized-matlab/blob/master/setupSolarized.m

  if ~exist('use_dark_mode','var') || use_dark_mode
    sys = false;
    txc = [1 1 1];
    bgc = [30 30 30]/255;
    fbg = [1 1 1].*40/255;
    alc = [1 1 1];
    ac = [30 30 30]/255;
    str = [254.1188  106.3358  255.0000]/255;
    ustr = [203  75  22] / 255;
    hyp = [ 38 139 210] / 255;
    cmt = [ 54 139  54] / 255;
    scmd = [198 160  20] / 255;
    errs = [230 40 40]/255;
  else
    sys = true;
    txc = [0 0 0];
    bgc = [1 1 1];
    fbg = get(0,'factoryFigureColor');
    alc = 'k';
    ac = 'w';
    str = [160  32 240]/255;
    ustr = [178   0   0]/255;
    hyp = [0 0 1];
    cmt = [ 34 139  34] / 255;
    scmd = [178 140   0] / 255;
    errs = [230 0 0]/255;
  end
  kwd = hyp;
  warn = ustr;

  % Main colors
  com.mathworks.services.Prefs.setBooleanPref('ColorsUseSystem',sys);
  com.mathworks.services.Prefs.setColorPref('ColorsText',java.awt.Color(txc(1), txc(2), txc(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('ColorsText');
  com.mathworks.services.Prefs.setColorPref('ColorsBackground',java.awt.Color(bgc(1), bgc(2), bgc(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('ColorsBackground');
  com.mathworks.services.Prefs.setColorPref('Colors_M_Strings',java.awt.Color(str(1), str(2), str(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Strings');
  com.mathworks.services.Prefs.setColorPref('Colors_M_UnterminatedStrings',java.awt.Color(ustr(1), ustr(2), ustr(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_UnterminatedStrings');
  com.mathworks.services.Prefs.setColorPref('Colors_M_Keywords',java.awt.Color(kwd(1), kwd(2), kwd(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Keywords');
  com.mathworks.services.Prefs.setColorPref('Colors_M_Comments',java.awt.Color(cmt(1), cmt(2), cmt(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Comments');
  com.mathworks.services.Prefs.setColorPref('Colors_M_SystemCommands',java.awt.Color(scmd(1), scmd(2), scmd(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_SystemCommands');
  com.mathworks.services.Prefs.setColorPref('Colors_M_Errors',java.awt.Color(errs(1), errs(2), errs(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Errors');
  com.mathworks.services.Prefs.setColorPref('Colors_HTML_HTMLLinks',java.awt.Color(hyp(1), hyp(2), hyp(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_HTML_HTMLLinks');
  com.mathworks.services.Prefs.setColorPref('Colors_M_Warnings',java.awt.Color(warn(1), warn(2), warn(3)));
  com.mathworks.services.ColorPrefs.notifyColorListeners('Colors_M_Warnings');
  %com.mathworks.services.Prefs.setBooleanPref('ColorsUseMLintAutoFixBackground',afhb);
  %com.mathworks.services.Prefs.setColorPref('ColorsMLintAutoFixBackground',java.awt.Color(afh(1), afh(2), afh(3)));
  %com.mathworks.services.ColorPrefs.notifyColorListeners('ColorsMLintAutoFixBackground');
  %com.mathworks.services.Prefs.setColorPref('Editor.NonlocalVariableHighlighting.TextColor',java.awt.Color(vwss(1), vwss(2), vwss(3)));
  %com.mathworks.services.ColorPrefs.notifyColorListeners('Editor.NonlocalVariableHighlighting.TextColor');
  %com.mathworks.services.Prefs.setBooleanPref('EditorCodepadHighVisible',hsb);
  %com.mathworks.services.Prefs.setColorPref('Editorhighlight-lines', java.awt.Color(hsbc(1), hsbc(2), hsbc(3)));
  %com.mathworks.services.Prefs.setBooleanPref('Editorhighlight-caret-row-boolean',hclb);
  %com.mathworks.services.Prefs.setColorPref('Editorhighlight-caret-row-boolean-color',java.awt.Color(hcl(1), hcl(2), hcl(3)));
  %com.mathworks.services.ColorPrefs.notifyColorListeners('Editorhighlight-caret-row-boolean-color');
  %com.mathworks.services.Prefs.setBooleanPref('EditorShowLineNumbers',slnb);
  %com.mathworks.services.Prefs.setBooleanPref('EditorRightTextLineVisible',rtlb);

  % Figure windows
  set(0,'defaultfigurecolor',fbg)
  arrayfun(@(f) set(f,'Color',fbg),get(groot, 'Children'));
  % axes labels
  set(groot,{'DefaultAxesXColor','DefaultAxesYColor','DefaultAxesZColor','DefaultAxesColor','DefaultTextColor','DefaultLineColor'},{alc,alc,alc,ac,alc,alc})
  arrayfun(@(a) set(a,{'Xcolor','YColor','ZColor','Color'},{alc,alc,alc,ac}),findall(0,'type','axes'));
  arrayfun(@(t) set(t,'Color',alc),findall(0,'type','text'));

end


function test_suite=test_moxunit_fieldtrip_test_suite_filtering
% #   For MOxUnit_fieldtrip's copyright information and license terms,   #
% #   see the COPYING file distributed with MOxUnit_fieldtrip.           #

    try % assignment of 'localfunctions' is necessary in Matlab >= 2016
        test_functions=localfunctions();
    catch % no problem; early Matlab versions can use initTestSuite fine
    end
    initTestSuite;

function test_fieldtrip_suite_filter_basics()
% test that object can be instantiated and has expected properties

    % each element in the struct below containes these elements:
    % - the label for suite.filter ('maxwalltime','maxmem','loadfile')
    % - the value for suite.filter
    % - lines for which test cases should be kept    after the filter
    % - "                                  " removed "              "
    s=struct();
    s.walltime={'maxwalltime',...
                {20,'20'},...
                {'','% WALLTIME 10','% WALLTIME 00:00:10'},...
                {'% WALLTIME 30','% WALLTIME 00:05:00'}};

    s.mem={'maxmem',...
                {10000,'10000'},...
                {'','% MEM 10','% MEM 1kb'},...
                {'% MEM 20000','% MEM 1tb'}};
    s.dccnpath={'loadfile',...
                {false,'no'},...
                {'','% dccnpath'},...
                {'dccnpath','fullfile(dccnpath,''bar'')'}};

    keys=fieldnames(s);
    for k=1:numel(keys)
        key=keys{k};
        prop=s.(key);

        label=prop{1};
        values=prop{2};

        for skip_test=[false,true]
            prop_idx=3;
            if skip_test
                prop_idx=prop_idx+1;
            end
            line_cell=prop{prop_idx};

            for j=1:numel(line_cell)
                line=line_cell{j};
                for m=1:numel(values)
                    value=values{m};

                    test_dir=tempname();
                    fn=randtestfilename(test_dir);

                    helper_test_single_test_case_filter(fn,...
                                                        label,...
                                                        value,...
                                                        line,...
                                                        skip_test);
                end
            end
        end
    end

function test_fieldtrip_suite_filter_exclude_if_prefix_equals_failed()
    test_dir=tempname();

    prefix='failed_';

    arg='exclude_if_prefix_equals_failed';
    no_yes_values={{'no',false},...
                    {'yes',true}};
    for k=1:numel(no_yes_values)
        exclude=k>1;
        for j=1:numel(no_yes_values{k})
            value=no_yes_values{k}{j};

            fn=randtestfilename(test_dir,prefix);
            helper_test_single_test_case_filter(fn,arg,value,'',exclude);
        end
    end

function helper_test_single_test_case_filter(fn,arg,value,...
                                                line,...
                                                skip_test)

    % make test case
    test_dir=fileparts(fn);
    suite=make_basic_test_suite(test_dir);
    dir_cleaner=onCleanup(@()clean_dir(test_dir));

    tc=build_test_case(fn, {line});

    % suite is empty initially
    assertEqual(countTestCases(suite),0);

    % after adding the test it must be in the suite
    suite=addFromFile(suite,fn);
    assertEqual(countTestCases(suite),1);
    assertEqual(getLocation(getTestNode(suite,1)),...
                    getLocation(tc));

    % skip test
    suite=filter(suite,arg,value);

    % tests must still be there
    assertEqual(countTestCases(suite),1);

    report=MOxUnitTestReport(0,1,'');
    report=run(suite,report);

    assertEqual(countTestOutcomes(report),1);

    % get test outcome.
    outcome=getTestOutcome(report,1);

    % test should not have failed
    assertEqual(isNonFailure(outcome),true);

    % succesful if test was not skipped
    is_success=isSuccess(outcome);
    assertEqual(is_success,~skip_test);

    if skip_test
        assertTrue(isa(outcome,'MOxUnitSkippedTestOutcome'));
    end

function s=randstr
    s=char(ceil(rand(1,10)*26+64));

function suite=make_basic_test_suite(test_dir)
    suite=MOxUnitFieldTripTestSuite();
    mkdir(test_dir);

function fn=randtestfilename(parent_dir,prefix)
    if nargin<2
        prefix='test_';
    end
    test_name=randstr();
    func_name=sprintf('%s%s',prefix,test_name);
    fn=fullfile(parent_dir,sprintf('%s.m',func_name));

function clean_dir(dir_name)
    ds=dir(dir_name);
    n=numel(ds);
    for k=1:n
        d=ds(k);
        if ~d.isdir
            % delete file
            pth=fullfile(dir_name,d.name);
            delete(pth);
        end
    end

    rmdir(dir_name);

function tc=build_test_case(fn, body_lines)
    [unused,func_name]=fileparts(fn);
    lines=[sprintf('function %s',func_name),...
            body_lines];
    write_content(fn,lines);
    tc=MOxUnitFieldTripTestCase(fn);

function write_content(fn,lines)
    fid=fopen(fn,'w');
    cleaner=onCleanup(@()fclose(fid));
    fprintf(fid,'%s\n',lines{:});


function v = zUpDown

v = 2*strcmpi(getMTEXpref('zAxisDirection'),'outOfPlane')-1;

end


function obj = setType(obj, type)
    % Sets the type (either LINEAR or NONLINEAR) of the NLP function
    %
    % Parameters:
    % type: the type of the NLP function @type char

    % specify the function type
    if strcmpi(type, 'Linear')
        obj.Type = 'Linear';
    elseif strcmpi(type, 'Nonlinear')
        obj.Type = 'Nonlinear';
    else
        error('NlpFunction:incorrectFunctionType',...
            'Unspecified function type detected.\n');
    end
end


% to prepare the events for inversion based
% on Lu Zhongs code.

report_this_filefun(mfilename('fullpath'));

think
tmp = [a(:,10:12)];
do = ['save ' hodo 'data.inp tmp -ascii'];
err =  ['Error - could not save file ' hodo 'data.inp - permission?'];
err2 = ['errordlg(err);return'];
eval(do,err2)

infi = [hodo 'data.inp'];
outfi = [hodo 'tmpout.dat'];
outfi2 = [hodo 'tmpout2.dat'];

fid = fopen([hodo 'inmifi.dat'],'w');

fprintf(fid,'%s\n',infi);
fprintf(fid,'%s\n',outfi);

fclose(fid);
comm = ['!/bin/rm ' outfi];
eval(comm)

comm = ['!  ' hodi '/stinvers/datasetupSTR_new < ' hodo 'inmifi.dat ' ]
eval(comm)

comm = ['!grep  "1.0" ' outfi  '>'  outfi2];
eval(comm)

comm = ['load ' hodo 'tmpout2.dat'];
eval(comm)

l = a(:,length(a(1,:)));
a(:,10:13) = [];
a = [a  tmpout2  l];

done


function obj = coeftq1_pnp_func_new(in1)
coef_J11 = in1(:,11);
coef_J20 = in1(:,20);
coef_J30 = in1(:,30);
coef_J26 = in1(:,26);
coef_J45 = in1(:,45);
coef_J63 = in1(:,63);
coef_J55 = in1(:,55);
coef_J39 = in1(:,39);
coef_J49 = in1(:,49);
coef_J59 = in1(:,59);
obj = [coef_J11,coef_J20,coef_J26,coef_J30,coef_J39,coef_J45,coef_J49,coef_J55,coef_J59,coef_J63];


function tck = dtiExportFibersMrtrix(fg, tck_filename)
%
%   tck = dtiExportFibersMrtrix(fg, tck_filename)
%
%   Saves a FG structure to disk in MRTRIX format (.tck)
%
% INPUTS:
%     fg -           vistasoft fiber group structure
%     tck_filename - file path to output .ick
%
% OUTPUT:
%     tck - reconstructed TCK file structure.
%
%   Based on MATLAB functions distributed with mrtrix 0.3
%
%   Note 1. The .tck HEADER is reconstructed before writing to disk from
%   information found in fg.params. The HEADER does not seem to be necessary
%   to for the final .tck file to be compatible to MRTRIX and mrview.
%
%   Note 2. The HEADER can contain information aboutThe ROIs used for tracking.
%   However, if multiple ROIs were used for tracking currently the MATLAB code
%   only stores the last ROI name used. This is a limitation existent in the
%   original MATLAB code provided with MRTRIX. We could try to solve this but
%   have not yet.
%
% Brent McPherson, Indiana University (C), 2017
% Updated by Lindsey Kitchell, Indiana University 2017
% Edits to comments by Franco Pestilli

% initialize output
tck = dtiGetFgParams(fg);

% transpose the streamline order
tck.data = fg.fibers';

for ii = 1:length(tck.data)
    % transpose the node order
    tck.data{ii} = tck.data{ii}';

end
clear ii

% save the file w/ mrtrix fxn
write_mrtrix_fibers(tck, tck_filename);

return
end

%%%%%%%%%%%%%%%%%%%%%%
% AUXILIARY FUNCTION %
%%%%%%%%%%%%%%%%%%%%%%
function write_mrtrix_fibers (fibers, filename)
%
% function: write_mrtrix_fibers (fibers, filename)
%
% writes the track data stored as a cell array in the 'data' field of the
% fibers variable to the MRtrix format track file 'filename'. All other fields
% of the fibers variable will be written as text entries in the header, and are
% expected to supplied as character arrays.
%
%
% This function was originally distributed with mrtrix 0.2/0.3

if ~isfield (fibers, 'data')
  disp ('ERROR: input fibers variable does not contain required ''data'' field');
  return;
end

if ~iscell (fibers.data)
  disp ('ERROR: input fibers.data variable should be a cell array');
  return;
end

f = fopen (filename, 'w', 'ieee-le');
if (f < 1)
  disp (['error opening ' filename ]);
  return;
end

fprintf (f, 'mrtrix fibers\ndatatype: Float32LE\ncount: %d\n', prod(size(fibers.data)));
names = fieldnames(fibers);
for i=1:size(names)
  if strcmpi (names{i}, 'data'), continue; end
  if strcmpi (names{i}, 'count'), continue; end
  if strcmpi (names{i}, 'datatype'), continue; end
  fprintf (f, '%s: %s\n', names{i}, getfield(fibers, names{i}));
end
fprintf (f, '%s: %s\n', 'timestamp: ', num2str(now)); % This allows visualizing the streamlines in mrview
data_offset = ftell (f) + 20;
fprintf (f, 'file: . %d\nEND\n', data_offset);

fwrite (f, zeros(data_offset-ftell(f),1), 'uint8');
for i = 1:prod(size(fibers.data))
  fwrite (f, fibers.data{i}', 'float32');
  fwrite (f, [ nan nan nan ], 'float32');
end

fwrite (f, [ inf inf inf ], 'float32');
fclose (f);

end


%
% lines = my_cat(file_name)
%
% Simulate the function of "cat" in Unix systems.
% The input is a file name.
% The output is a cell array, each cell contains one line of the file
% content.
% Author: Xiong Xiao,
%         School of Computer Engineering, Nanyang Technological University
% Date Created: 23 Oct, 2008
% Last Modified: 23 Oct, 2008
%
function lines = my_cat(file_name)

FID = fopen(file_name, 'r');

lines = read_line_by_line(FID);

fclose(FID);


function fileName = gpWriteResult(model, dataSet, number)

% GPWRITERESULT Write a GP result.
% FORMAT
% DESC writes a GP result.
% ARG model : the model to write.
% ARG dataSet : the name of the data set to write.
% ARG number : the number of the GP run to write.
% RETURN fileName : the file name used to write.
%
% SEEALSO : gpLoadResult
%
% COPYRIGHT : Neil D. Lawrence, 2009

% GP

dataSet(1) = upper(dataSet(1));
type = model.type;
type(1) = upper(type(1));
fileName = ['dem' dataSet type num2str(number)];

[kern, noise, gpInfo] = gpDeconstruct(model);

save(fileName, 'kern', 'noise', 'gpInfo');


function dataset = ch_data_import(path)

tbl = readtable(path);

if sum(ismember(tbl.Properties.VariableNames,'AccX'))
    dataset.imu.acc(1,:) = tbl.AccX';
end

if sum(ismember(tbl.Properties.VariableNames,'AccY'))
    dataset.imu.acc(2,:) = tbl.AccY';
end

if sum(ismember(tbl.Properties.VariableNames,'AccZ'))
    dataset.imu.acc(3,:) = tbl.AccZ';
end

if sum(ismember(tbl.Properties.VariableNames,'GyrX'))
    dataset.imu.gyr(1,:) = tbl.GyrX';
end

if sum(ismember(tbl.Properties.VariableNames,'GyrY'))
    dataset.imu.gyr(2,:) = tbl.GyrY';
end

if sum(ismember(tbl.Properties.VariableNames,'GyrZ'))
    dataset.imu.gyr(3,:) = tbl.GyrZ';
end

if sum(ismember(tbl.Properties.VariableNames,'MagX'))
    dataset.imu.mag(1,:) = tbl.MagX';
end

if sum(ismember(tbl.Properties.VariableNames,'MagY'))
    dataset.imu.mag(2,:) = tbl.MagY';
end

if sum(ismember(tbl.Properties.VariableNames,'MagZ'))
    dataset.imu.mag(3,:) = tbl.MagZ';
end

if sum(ismember(tbl.Properties.VariableNames,'Roll'))
    dataset.eul.roll = tbl.Roll';
end

if sum(ismember(tbl.Properties.VariableNames,'Pitch'))
    dataset.eul.pitch = tbl.Pitch';
end

if sum(ismember(tbl.Properties.VariableNames,'Yaw'))
    dataset.eul.yaw = tbl.Yaw';
end


% AGENT CONTROL INPUT TRAJECTORIES
function [currentFigure,figureHandle] = GetFigure_inputs(SIM,objectIndex,DATA,currentFigure)
% Draws the seperations of all agents from each other, neglecting waypoint
% objects.

figureHandle = [];

% SANITY CHECK 1
if DATA.totalAgents == 0
    warning('No agent data available.');
    return
else
    % LOGICALLY SELECT THE AGENTS FROM THE OBJECT INDEX
    agentObjectIndex = objectIndex([SIM.OBJECTS.type] == OMAS_objectType.agent); % The agents themselves
end

iter = 0;
for ID1 = 1:SIM.totalAgents
    % TRY TO GET THE REQUIRED PROPERTIES
    try
       testA = agentObjectIndex{ID1}.DATA.inputNames;
       testB = agentObjectIndex{ID1}.DATA.inputs;
    catch
       iter = iter + 1;
    end
end

% SANITY CHECK 2
if iter == SIM.totalAgents
    warning('No agents have input timeseries stored in (agent).DATA.inputs. Use the "DATA.inputNames" and "DATA.inputs" fields if desired.');
    return
end

% Declare title string for figure
figurePath = strcat(SIM.outputPath,'inputs');

% FIGURE META PROPERTIES
figureHandle = figure('Name','OpenMAS control inputs');
setappdata(figureHandle, 'SubplotDefaultAxesLocation', [0.1, 0.1, 0.85, 0.85]);
set(figureHandle,'Position', DATA.figureProperties.windowSettings);        % [x y width height]
set(figureHandle,'Color',DATA.figureProperties.figureColor);               % Background colour
plotCellA = 1; plotCellWidth = 4;                                          % The width of each figure, the start of the plot

% FOR EACH AGENT'S PERSPECTIVE
for ID1 = 1:SIM.totalAgents
    % GET EVALUATION OBJECT
    evalAgent = agentObjectIndex{ID1};
    % CHECK SKIP CONDITION
    if isempty(evalAgent.DATA)
        warning('[OUTPUT]\tProperty .DATA is empty for agent %s',evalAgent.name);
        continue
    end

    % GET TH AGENT-LOCAL 'DATA' STRUCTURE
    inputTrajectories = evalAgent.DATA.inputs;
    inputCount = size(inputTrajectories,1);

    % BUILD THE SUB-PLOT
    plotCellB = double(ID1*plotCellWidth);                                         % The end of the plot
    plotLocation = subplot(double(DATA.totalAgents),plotCellWidth,[plotCellA plotCellB]);
    set(plotLocation,...
        'Color',DATA.figureProperties.axesColor,...
        'GridLineStyle','--',...
        'GridAlpha',0.25,...
        'GridColor','k');
    hold on;

    % LEGEND LABELS
    legendEntries = cell(inputCount,1);
    numericLabelling = 1;
    if isfield(evalAgent.DATA,'inputNames')
        if length(evalAgent.DATA.inputNames) ~= inputCount
            warning('Incorrect number of input labels for agent %s, reverting to numeric labelling',simName);
            numericLabelling = 1;
        else
            % FETCH THE INPUT LABEL
            for entry = 1:size(inputTrajectories,1)
                legendEntries{entry} = evalAgent.DATA.inputNames{entry};
            end
            numericLabelling = 0;
        end
    end
    if numericLabelling
        % DEFAULT TO GENERIC NAMING
        for entry = 1:size(inputTrajectories,1)
            legendEntries{entry} = sprintf('Input %s',num2str(entry));
        end
    end

    % PLOT THE SEPERATION DATA ON CURRENT FIGURE
    plot(plotLocation,...
         DATA.timeVector(:,1:SIM.TIME.endStep),...
         inputTrajectories(:,1:SIM.TIME.endStep),...
        'LineStyle','-',...
        'LineWidth',DATA.figureProperties.lineWidth);
    % Y-Label
    ylabel(plotLocation,...
        sprintf('Inputs \n [ID-%s]',num2str(evalAgent.objectID)),...
        'Interpreter',DATA.figureProperties.interpreter,...
        'fontname',DATA.figureProperties.fontName,...
        'fontweight',DATA.figureProperties.fontWeight,...
        'fontSize',DATA.figureProperties.axisFontSize,...
        'FontSmoothing','On');
    % Axes
    set(plotLocation,...
        'TickLabelInterpreter',DATA.figureProperties.interpreter,...
        'fontname',DATA.figureProperties.fontName,...
        'Fontweight',DATA.figureProperties.fontWeight,...
        'FontSize',DATA.figureProperties.axisFontSize,...
        'FontSmoothing','on',...
        'Color',DATA.figureProperties.axesColor,...
        'GridLineStyle','--',...
        'GridAlpha',0.25,...
        'GridColor','k');
    % Legend
    legend(legendEntries,...
        'Location','eastoutside',...
        'fontname',DATA.figureProperties.fontName,...
        'Interpreter',DATA.figureProperties.interpreter);

    grid on; box on; grid minor;
    % Show the timestep difference in the figure
    %plotLocation.XAxis.MinorTickValues = plotLocation.XAxis.Limits(1):SIM.TIME.dt:plotLocation.XAxis.Limits(2);
    % ADD FIGURE TITLE TO FIRST PLOT HEADER
    if plotCellA == 1
        % Title
        title(plotLocation,sprintf('Agent control trajectories over a period of %ss',num2str(SIM.TIME.endTime)),...
            'Interpreter',DATA.figureProperties.interpreter,...
            'fontname',DATA.figureProperties.fontName,...
            'fontweight',DATA.figureProperties.fontWeight,...
            'fontsize',DATA.figureProperties.titleFontSize);               % Append title to first subplot
    end
    % Prevent overlap of x-label
    if ID1 == DATA.totalAgents
        % X-Label
        xlabel(plotLocation,'t (s)',...
            'Interpreter', DATA.figureProperties.interpreter,...
            'fontname',DATA.figureProperties.fontName,...
            'fontweight',DATA.figureProperties.fontWeight,...
            'fontSize',DATA.figureProperties.axisFontSize,...
            'FontSmoothing','On');
    else
        set(plotLocation,'XTickLabel',[]);
    end
    % Define the x-limits
    xlim([SIM.TIME.startTime,SIM.TIME.endTime]);                           % Ensures plot alignment/sizing
    plotCellA = plotCellA + plotCellWidth; % Move to next subplot location
end
hold off;

% SAVE THE OUTPUT FIGURE
savefig(figureHandle,figurePath);

% Publish as .pdf if requested
if DATA.figureProperties.publish
	GetFigurePDF(figureHandle,figurePath);
end

% INCREMENT THE FIGURE INDEX
DATA.figureProperties.alignment = DATA.figureProperties.alignment + DATA.figureProperties.spacing;
currentFigure = currentFigure + 1;
end


function demo_tcca()

% Set the various paths
rootpath = filesepStandard(fileparts(which('Homer3.m')));
currpath = pwd;
subjFolder = 'UnitTests/Example6_GrpTap';
subjFolder = [rootpath, subjFolder];
procStreamConfigFile = './processOpt_tcca.cfg';   % proc stream config file path relative to subject folder
cd(subjFolder);
resetGroupFolder('');

fprintf('Loading subject folder:  %s\n', subjFolder);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Change processing stream param values to newval
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dataTree = LoadDataTree(subjFolder, [], procStreamConfigFile);
iG = dataTree.GetCurrElemIndexID();
dataTree.groups(iG).Calc();
dataTree.groups(iG).Save();

cd(currpath)


function [model] = generateRules(model, printLevel)
% If a model does not have a model.rules field but has a model.grRules
% field, can be regenerated using this script
%
% USAGE:
%
%    [model] = generateRules(model)
%
% INPUT:
%    model:        COBRA model with model.grRules
%    printLevel:   optional variable to print out all new genes
%                  (default = TRUE), can be zero if not needed
%
% OUTPUT:
%    model:     same model but with model.rules added
%
% .. Author: - Aarash Bordar 11/17/2010
%            - Uri David Akavia 6-Aug-2017, bug fixes and speedup
%            - Diana El Assal 30/8/2017
%            - Laurent Heirendt December 2017, speedup

if ~exist('printLevel', 'var')
    printLevel = 1;
end
if ~isfield(model, 'grRules')
    warning('generateRules can be only be used on a model that has grRules field!');
    return;
end
[preParsedGrRules,genes] = preparseGPR(model.grRules);  % preparse all model.grRules
allGenes =  unique([genes{~cellfun(@isempty,genes)}]); %Get the unique gene list
if (~isfield(model, 'genes'))
    newGenes = allGenes;
else
    %         C = setdiff(A,B) for vectors A and B, returns the values in A that
    %         are not in B with no repetitions. C will be sorted.
    newGenes = setdiff(allGenes,model.genes);
end
if ~isempty(newGenes)
    if printLevel
        warning('Found the following genes in grRules that were not present in model.genes:\n%s\nAdding them to the model.',strjoin(newGenes,'\n'));
    end
    model = addGenes(model,newGenes);
end

% determine the number of rules
nRules = length(model.grRules);

% allocate the model.rules field
model.rules = cell(nRules, 1);
% loop through all the grRules
for i = 1:nRules
    if ~isempty(preParsedGrRules{i})
        genePos = zeros(numel(genes{i}));
        for j = 1:numel(genes{i})
            genePos(j) = find(strcmp(model.genes,genes{i}{j}));
        end
        rule = parseGPR(preParsedGrRules{i}, genes{i}, true, genePos);
        model.rules{i, 1} = rule;
    else
        model.rules{i, 1} = '';
    end
end
end


function dtiRawReprocess(subDir, dtiDirName, rawBaseName, t1File, rawDirName)
%
% dtiRawReprocessMany(subDir, dtiDirName, dwRawBaseName, t1File, [rawDirName='raw'])
%
% E.g.:
% subDirList = '/biac3/wandell4/data/reading_longitude/dti_adults/ab_090809';
% dtiDirName = 'dti06';
% rawBaseName = 'dti_g13_b800';
% t1File = 'full/path/to/t1.nii.gz';
%
% DY 09/2008: modified from dtiRawReprocessMany to work for just one
% subject at a time in the context of dti_FFA_preprocessScript_fixEddyRT
%
% NOTE: I also set clobber to TRUE just in case (forces recomputation of
% everything). Also, I checked that the eddyCorrect flag is set to default
% (true).

if(~exist('rawDirName','var')||isempty(rawDirName))
    rawDirName = 'raw';
end

rawDir = fullfile(subDir, rawDirName);
d = dir(fullfile(rawDir, [rawBaseName '.*']));
bvec = ''; bval = ''; dwRaw = '';

if(numel(d)>=3)
    tmp = {d.name};
    % now sort bvecs, bvals, nifti file
    try
        bvec = tmp{find(~cellfun('isempty',regexpi(tmp,'\.bvec.$','once')))};
        bval = tmp{find(~cellfun('isempty',regexpi(tmp,'\.bval.$','once')))};
        dwRaw = tmp{find(~cellfun('isempty',regexpi(tmp,'\.nii$|\.nii.gz','once')))};
    catch
    end
end

if(isempty(bvec)||isempty(bval)||isempty(dwRaw))
    disp('FAILED: Can''t find dwRaw/bvec/bval files.');
else
    if(~exist(t1File,'file'))
        disp('FAILED: Can''t find t1 file.');
    else
        outDir = fullfile(subDir, dtiDirName);
        oldDir = fullfile(subDir, [dtiDirName '_OLD' datestr(now,'yymmdd')]);
        % Rename the current data dir and put old raw 'aligned' files
        % in there.
        try
            movefile(outDir, oldDir);
            movefile(fullfile(rawDir, [rawBaseName '_aligned.*']), oldDir);
        catch
        end
        dtiRawPreprocess(fullfile(rawDir,dwRaw), t1File, [], [], true, outDir);
    end
end

return;


find(strcmp(labels,'occluder'))


function color = isColorStack(img)
%ISCOLORSTACK  Check if a 3D stack is color or gray-scale
%
%   COL = isColorStack(IMG)
%   Returns TRUE if the 3D image has a color dimension, or FASLE if the
%   image is gray scale image.
%
%   This function was mainly created for simplifying the listings of other
%   functions in the same package.
%
%   Example
%   img = analyze75read(analyze75info('brainMRI.hdr'));
%   isColorStack(img)
%   ans =
%       0
%
%
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2010-07-02,    using Matlab 7.9.0.529 (R2009b)
% http://www.pfl-cepia.inra.fr/index.php?page=slicer
% Copyright 2010 INRA - Cepia Software Platform.

dim = size(img);
color = length(dim)>3;


classdef PTKAirwaysLungsAndVessels < PTKPlugin
    % PTKAirwaysLungsAndVessels. Plugin for displaying segented airways, lungs and vessels together
    %
    %     This is a plugin for the Pulmonary Toolkit. Plugins can be run using
    %     the gui, or through the interfaces provided by the Pulmonary Toolkit.
    %     See PTKPlugin.m for more information on how to run plugins.
    %
    %     Plugins should not be run directly from your code.
    %
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    properties
        ButtonText = 'Airways, Lungs<BR> and vesssels'
        ToolTip = 'Shows a segmentation of the airways and lungs'
        Category = 'Lungs'

        AllowResultsToBeCached = true
        AlwaysRunPlugin = true
        PluginType = 'ReplaceOverlay'
        HidePluginInDisplay = false
        FlattenPreviewImage = true
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 2
        GeneratePreview = true
        Visibility = 'Developer'
    end

    methods (Static)
        function results = RunPlugin(dataset, reporting)

            % Get the airway results
            [airways_results, airways_image] = dataset.GetResult('PTKAirways');

            % Get the results for the left and right lung segmentations
            [left_and_right_lungs_results, left_and_right_lungs_image] = dataset.GetResult('PTKLeftAndRightLungs');

            % Get the vessel results
            vesselness_image = dataset.GetResult('PTKVesselness');

            % Make our output image the lugn segmentation
            results = left_and_right_lungs_image.BlankCopy;

            % Make an image matrix with 1 for right lung, 2 for left lung and 3
            % for airways
            combined_image_raw = uint8(left_and_right_lungs_image.RawImage > 0);
            combined_image_raw(vesselness_image.RawImage > 0.3) = 3;
            combined_image_raw(airways_image.RawImage == 1) = 6;

            % Change the output image
            results.ChangeRawImage(combined_image_raw);

        end
    end
end


% pop_readbdf() - Read Biosemi 24-bit BDF file
%
% Usage:
%   >> EEG = pop_readbdf;             % an interactive window pops up
%   >> EEG = pop_readbdf( filename ); % no pop-up window
%   >> EEG = pop_readbdf( filename, range, eventchans, ref, delchan);
%
% Graphical interface:
%   "Data block range to read" - {edit box] see command line
%                    parameter 'range' below.
%   "Event channel index(s)" - {edit box] see command line
%                    parameter 'eventchans' below.
%   "Index(s) of reference channel(s)" - {edit box] see command line
%                    parameter 'ref' below.
% Inputs:
%   filename       - Biosemi 24-bit BDF file name
%
% Optional input:
%   range          - [min max] integer range of data blocks to import.
%                    Default is empty -> import all data blocks.
%   eventchans     - [integer] event channel index(s). Default: none.
%   ref            - [integer] channel index or index(s) for the reference.
%                    Reference channels are not removed from the data,
%                    allowing easy re-referencing. If more than one
%                    channel, data are referenced to the average of the
%                    indexed channels. WARNING! Biosemi Active II data
%                    are recorded reference-free, but LOSE 40 dB of SNR
%                    if no reference is used!. If you do not know which
%                    channel to use, pick one and then re-reference after
%                    the channel locations are read in. {default: none}
%   delchan        - ['on'|'off'] delete event channel. Default if 'on'\
%
% Outputs:
%   EEG            - EEGLAB data structure
%
% Author: Arnaud Delorme, CNL / Salk Institute, 13 March 2002
%
% See also: openbdf(), readbdf()

% Copyright (C) 13 March 2002 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.
%adbdf( filename ); % no pop-up window
%   >> EEG = pop_readbdf( filename, range, eventchans, ref, delchan);
%
% Graphical interface:
%   "Data block range to read" - {edit box] see command line
%                    parameter 'range' below.
%   "Event channel index(s)" - {edit box] see command line
%                    parameter 'eventchans' below.
%   "Index(s) of reference channel(s)" - {edit box] see command line
% 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

% programmed from pop_readedf() version 1.15

function [EEG, command] = pop_readbdf(filename, blockrange, eventchans, ref, delchan);
EEG = [];
command = '';

if nargin < 2
    blockrange = [];
end;
if nargin < 3
    eventchans = [];
end;
if nargin < 4
    ref = [];
end;
if nargin < 5
    delchan = 'on';
end;

if nargin < 1
	% ask user
	[filename, filepath] = uigetfile('*.BDF;*.bdf', 'Choose an BDF file -- pop_readbdf()');
    drawnow;

	if filename == 0 return; end;
	filename = [filepath filename];
    disp('We highly recommend that you choose a reference channel IF these are Biosemi data');
    disp('(e.g., a mastoid or other channel). Otherwise the data will lose 40 dB of SNR!');

    dat = openbdf(filename);
    promptstr    = { [ 'Data block range to read (default all [1 ' int2str(dat.Head.NRec) '])' ]
                     [ 'Event channel number(s) (default:none [1-' int2str(dat.Head.NS)  '])' ]
                     'If Biosemi data, reference chan(s) number(s)'
                     'Delete event channel' };
    inistr       = { '' int2str(dat.Head.NS) '' 'on' };
    result       = inputdlg2( promptstr, 'Import BDF file -- pop_readbdf()', 1,  inistr, 'pop_readbdf');
    if length(result) == 0 return; end;
    blockrange   = eval( [ '[' result{1} ']' ] );
    eventchans   = eval( [ '[' result{2} ']' ] );
    ref          = eval( [ '[' result{3} ']' ] );
    delchan      = result{4};
end;

% load datas
% ----------
EEG = eeg_emptyset;
fprintf('Reading BDF data in 24-bit format...\n');
dat = openbdf(filename);
%dat.Head = sopen(filename);
if isempty(dat.Head.NRec)
    dat.Head.NRec = 100;
end;
if isempty(blockrange)
    blockrange = [1 dat.Head.NRec];
end;
vectrange = [blockrange(1):min(blockrange(2), dat.Head.NRec)];
DAT=readbdf(dat,vectrange);
EEG.nbchan          = size(DAT.Record,1);
EEG.srate           = dat.Head.SampleRate(1);
EEG.data            = DAT.Record;
EEG.pnts            = size(EEG.data,2);
EEG.trials          = 1;
EEG.setname 		= 'BDF file';
disp('Event information might be encoded in the last channel');
disp('To extract these events, use menu File > Import event info > From data channel');
EEG.filename        = filename;
EEG.filepath        = '';
EEG.xmin            = 0;
EEG.chanlocs        = struct('labels', cellstr(dat.Head.Label));
EEG = eeg_checkset(EEG);

% extract events
% --------------
disp('Extracting events...');
warning off;
if ~isempty(eventchans)
    if any(eventchans > EEG.nbchan) | any(eventchans < 1)
        error('Event channel index or indices out of range');
    end;
    disp('Applying 8-bit masks to event channels (only for BIOSEMI files).');
    %EEG.data(eventchans,:) = bitand(uint32(EEG.data(eventchans,:)), 32767);

    %thiscode = 0;lastcode=0;
    %for p = 1:size(EEG.data,2)-1
    %    prevcode = thiscode;
    %    thiscode = mod(EEG.data(end,p),256*256);   % andrey's code - 16 bits
    %    if (thiscode ~= 0) && (thiscode~=prevcode) && (thiscode~=lastcode) % fix to avoid repeated codes (per Ying's demand)
    %        EEG.event(end+1).latency =  p;
    %        EEG.event(end).type = thiscode;
    %        lastcode = thiscode;
    %    end;
    %end;
    thiscode = 0;
    for p = 1:size(EEG.data,2)-1
        prevcode = thiscode;
        thiscode = mod(EEG.data(end,p),256*256);   % andrey's code - 16 bits
        if (thiscode ~= 0) && (thiscode~=prevcode)
            EEG.event(end+1).latency =  p;
            EEG.event(end).type = thiscode;
        end;
    end;
    if strcmpi(delchan, 'on')
        EEG = pop_select(EEG, 'nochannel', size(EEG.data,1));
    end;
    EEG = eeg_checkset(EEG, 'makeur');

    %EEG = pop_chanevent(EEG, eventchans, 'edge', 'leading', 'delchan', delchan);
end;
warning on;

% rerefencing
% -----------
if ~isempty(ref)
    disp('Re-referencing...');
    if ~isempty(eventchans) & any(ref > eventchans(1))
        error('Event channel index cannot be before ref channel index, contact arno@salk.edu');
    end;
    EEG.data = EEG.data - repmat(mean(EEG.data(ref,:),1), [size(EEG.data,1) 1]);
    if length(ref) == 1
        disp([ 'Warning: channel ' int2str(ref) ' is now zeroed (but still present in the data)' ]);
    else
        disp([ 'Warning: data matrix rank has decreased through re-referencing' ]);
    end;
end;

% history
% -------
if ~isempty(blockrange) | ~isempty(eventchans)
    command = sprintf('EEG = pop_readbdf(''%s'', %s);', filename, vararg2str({blockrange eventchans ref}));
else
    command = sprintf('EEG = pop_readbdf(''%s'');', filename);
end;

return;


classdef TopOptTestsSuite < handle

    methods

        function obj = TopOptTestsSuite()
            warning('off', 'MATLAB:structOnObject')
            % testFastDisplacement, testMacro, testMicro
            results = runtests("TopOptTests","ProcedureName","testFastDisplacement", 'Debug', true);
%             results = runtests("TopOptTests","ProcedureName","testAnalyticVsRegularizedPerimeter", 'Debug', true);
%             results = runtests("TopOptTests", 'Debug', true);
            table(results)
            warning('on', 'MATLAB:structOnObject')
        end

    end
end


% Init Script
% Remarks:
%   1.  If there is a predefined variable called 'subStreamNumberDefault'
%       it will be used to set the SubStream of the Random Number
%       Generator.
% TODO:
% 	1.  A
% Release Notes
% - 1.0.005     02/08/2019  Royi Avital
%   *   Added Octave Compatibility.
% - 1.0.004     05/07/2018  Royi Avital
%   *   Added case for 'subStreamNumberDefault = 0'.
% - 1.0.003     29/06/2018  Royi Avital
%   *   Clearing all variables but 'subStreamNumberDefault'.
%   *   Setting 'subStreamNumber' only if 'subStreamNumberDefault' not
%       defined.
% - 1.0.002     19/04/2018  Royi Avital
%   *   Added 'markerSizeMedium' (Matches 'markerSizeNormal').
% - 1.0.001     24/11/2016  Royi Avital
%   *   Added figure positions options.
% - 1.0.000     08/11/2016  Royi Avital
%   *   First release.
%
%
%% General Parameters

close('all');
clearvars('-except', 'subStreamNumberDefault');
clc();

FALSE   = 0;
TRUE    = 1;

OFF     = 0;
ON      = 1;

% See https://stackoverflow.com/questions/2246579
isOctave = (exist('OCTAVE_VERSION', 'builtin') ~= 0);

% set(0, 'DefaultFigureWindowStyle', 'docked');
% defaultLoosInset = get(0, 'DefaultAxesLooseInset');
% set(0, 'DefaultAxesLooseInset', [0.05, 0.05, 0.05, 0.05]);

figPosSmall     = [100, 100, 0400, 0300];
figPosMedium    = [100, 100, 0800, 0600];
figPosLarge     = [100, 100, 0960, 0720];
figPosXLarge    = [100, 100, 1100, 0825];
figPosX2Large   = [100, 100, 1200, 0900];
figPosX3Large   = [100, 100, 1400, 1050];
figPosDefault   = [100, 100, 0560, 0420];

fontSizeTitle   = 14;
fontSizeAxis    = 12;
fontSizeString  = 12;

lineWidthThin   = 1;
lineWidthNormal = 3;
lineWidthThick  = 4;

markerSizeSmall     = 4;
markerSizeMedium    = 8;
markerSizeNormal    = 8;
markerSizeLarge     = 10;

% https://www.mathworks.com/help/matlab/graphics_transition/why-are-plot-lines-different-colors.html
% https://www.mathworks.com/matlabcentral/answers/160332
mColorOrder = get(groot, 'DefaultAxesColorOrder');

if(isOctave == FALSE)
    randomNumberStream  = RandStream('mlfg6331_64', 'NormalTransform', 'Ziggurat');

    if(exist('subStreamNumberDefault', 'var') && (subStreamNumberDefault ~= 0))
        subStreamNumber = subStreamNumberDefault;
    else
        subStreamNumber = round(sum(clock()));
    end
    set(randomNumberStream, 'Substream', subStreamNumber);
    RandStream.setGlobalStream(randomNumberStream);
end


% JM: 2006/07/19
% viewer for data Tc on domain Omega

function varargout = viewImage(varargin);
% this is just output and hence not commented; fell free to improve (-;
% function varargout = viewImage(Tc,Omega,m,varargin);

persistent PARA

if nargin == 0,
  varargout{1} = PARA;
  return;
end;

% set persistent parameter
if nargin >= 1 & strcmp(varargin{1},'set'),
  PARA = setPARA(PARA,varargin{2:end});
  varargout{1} = PARA;
  return;
end;

if isstr(varargin{1}) & strcmp(varargin{1},'clear'),
  PARA = [];
  return;
end;

if isempty(PARA),
  PARA = setPARA(PARA,'viewer','image2D','colmap',gray(256));
  varargout{1} = PARA;
  warning('!!! no PARA given yet, set viewer to image2D !!!')
end;

% -----------------------------------------------------------------------------
% start to work

Tc    = varargin{1};
Omega = varargin{2};
m     = varargin{3};
varargin(1:3) = [];

% start with global parameters and update
para = PARA;
for j=1:length(varargin)/2,
  field = varargin{2*j-1};
  value = varargin{2*j};
  para  = setfield(para,field,value);
end;

if ~para.plots, return;  end;          % do nothing, just return;

% build parameter list
fields = fieldnames(para);
for j=1:length(fields);
  optn{2*j-1} = fields{j};
  optn{2*j}   = getfield(para,fields{j});
end;

% scale image to [0,255]
if isfield(para,'scale')  & para.scale,
  maxTc = max(Tc);
  Tc = 255/(maxTc+(maxTc==0))*Tc;
end;

% invert image
if isfield(para,'invert') & para.invert,
  Tc = max(Tc)-Tc;
end;

% setup figure
if ~isfield(para,'fig'), para.fig = [];   end;
if isempty(para.fig),    para.fig = gcf;  end;

fig = figure(para.fig);
if any(para.sub ~= 1),
  subplot(para.sub(1),para.sub(2),para.sub(3)); cla;
end;

if ~isempty(para.figname),
  set(fig,'numbertitle','off','name',sprintf('[JM-%d]: %s',fig,para.figname));
end;

% call the viewer
fh = feval(para.viewer,Tc,Omega,m,optn{:});
str = sprintf('%s',para.name);
title(str);

if nargout>0,
  varargout{1} = fh;
end;

return;
%==============================================================================
function PARA = setPARA(PARA,varargin);

% set default parameter
p.viewer   = [];
p.figname  = [];
p.fig      = [];
p.sub      = [1,1,1];
p.name     = '';
p.plots    = 1;
p.scale    = 0;
p.invert   = 0;

% get default values
fn = fieldnames(p);
for j=1:length(fn),
  default{2*j-1} = fn{j};
  default{2*j}   = getfield(p,fn{j});
end;

% get old values
if isempty(PARA),
  current = {};
else
  fn = fieldnames(PARA);
  for j=1:length(fn),
    current{2*j-1} = fn{j};
    current{2*j}   = getfield(PARA,fn{j});
  end;
end;

% get new values
if strcmp(varargin{1},'para') | strcmp(varargin{1},'PARA'),
  PARA = varargin{2};
  fn = fieldnames(PARA);
  for j=1:length(fn),
    new{2*j-1} = fn{j};
    new{2*j}   = getfield(PARA,fn{j});
  end;
else
  new = varargin;
end;

optn = {default{:},current{:},new{:}};

% rewrite default parameter
PARA = [];
for j=1:length(optn)/2,
  field = optn{2*j-1};
  value = optn{2*j};
  PARA  = setfield(PARA,field,value);
end;

fprintf('%s: set view parameter, viewer=%s\n',mfilename,PARA.viewer);
return;
% -----------------------------------------------------------------------------


function model = gpSubspaceOptimise(model,varargin)

% GPSUBSPACEOPTIMISE
%
% COPYRIGHT : Carl Henrik Ek, 2008

% GP

model = gpOptimise(model,varargin{:});

return;


% --------------------------------------------------------
% MDP Tracking
% Copyright (c) 2015 CVGL Stanford
% Licensed under The MIT License [see LICENSE for details]
% Written by Yu Xiang
% --------------------------------------------------------
%
% compile cpp files
% change the include and lib path if necessary
function compile

include = ' -I/usr/local/include/opencv/ -I/usr/local/include/ -I/usr/include/opencv/';
lib = ' -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_video';
eval(['mex lk.cpp -O' include lib]);

mex distance.cpp
mex imResampleMex.cpp
mex warp.cpp

disp('Compilation finished.');


function exportAISegToDICOM(planC,origScanNum,outputDicomPath,fname,dcmExportOptS,allLabelNamesC)
% function exportAISegToDICOM(planC,outputDicomPath,fname,dcmExportOptS,allLabelNamesC)
%
% APA, 4/28/2022

indexS = planC{end};

%Get custom options for DICOM export
% Handle special case of assignig reference UID fromanother structure
% (e.g. exporting registered images from MIM assistant changes their frameOfreferenceUID)
structRefForC = {};
count = 0;
if exist('dcmExportOptS','var') && isstruct(dcmExportOptS)
    structNameC = {planC{indexS.structures}.structureName};
    for iDcmOpt = 1:length(dcmExportOptS)
        if isfield(dcmExportOptS(iDcmOpt),'rt_struct') && ...
                isfield(dcmExportOptS(iDcmOpt).rt_struct,'referencedFrameOfReference')
            % Update to handle multiple structures
            toStructureName = dcmExportOptS(iDcmOpt).rt_struct.referencedFrameOfReference.toStructureName;
            fromStructureName = dcmExportOptS(iDcmOpt).rt_struct.referencedFrameOfReference.fromStructureName;
            strIndex = getMatchingIndex(fromStructureName,structNameC,'exact');
            assocScanV = getStructureAssociatedScan(strIndex,planC);
            strIndex = strIndex(assocScanV==origScanNum);
            if isempty(strIndex)
                continue
            end
            count = count + 1;
            structRefFrameOfReferenceUID = planC{indexS.structures}(strIndex).referencedFrameOfReferenceUID;
            refSeriesInstanceUID = planC{indexS.structures}(strIndex).referencedSeriesUID;
            sopClassUidC = {planC{indexS.structures}(strIndex).contour.referencedSopClassUID};
            sopInstanceUidC = {planC{indexS.structures}(strIndex).contour.referencedSopInstanceUID};
            structRefForC{count,1} = toStructureName;
            structRefForC{count,2} = structRefFrameOfReferenceUID;
            structRefForC{count,3} = refSeriesInstanceUID;
            structRefForC{count,4} = sopClassUidC;
            structRefForC{count,5} = sopInstanceUidC;
        end
    end
end

%Retain only user-input structures (in allLabelNamesC)
numStr = length(planC{indexS.structures});
allStrC = {planC{indexS.structures}.structureName};
keepStrNumV = zeros(length(allLabelNamesC),1);
for i=1:length(allLabelNamesC)
    matchStrNum = getMatchingIndex(allLabelNamesC{i},allStrC,'EXACT');
    keepStrNumV(i) =  max(matchStrNum);
end

allStrV = 1:numStr;
allStrV(keepStrNumV)=[];

planC = deleteStructure(planC,allStrV);

%Export DICOM RT structs to outputDicomPath
planC = generate_DICOM_UID_Relationships(planC,structRefForC);
export_RS_IOD(planC,outputDicomPath,fname);


function [cell_case_study,xmesh,ymesh,zmesh] = dicomrt_loadRTdose(filename_list,force)
% dicomrt_loadRTdose(filename_list,force)
%
% Read dicom dose for a case study using MATLAB native function dicomread.
%
% filename contains a list of dose matrices to import.
% filename does not contain link to an RTPLAN in the first line
%
% Dose matrices are stored in a single 3D matrix: case_study
% x-y-z coordinates of the center of the dose-pixel are stored in xmesh,ymesh,zmesh
% cell_case_study is a simple cell array with the following structure:
%
%  ------------------------
%  | [ rtplan structure ] |
%  | ----------------------
%  | [ 3D dose matrix   ] |
%  | ---------------------
%  | [ voxel dimension  ] |
%  ------------------------
%
% NOTE: this function and dicomrt_loaddose differs because in this case the
% RTPLAN is not imported and left black
%
%
% See also dicomrt_loadct, dicomrt_getPatientPosition
%
% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org)

% Retrieve the number of images
nlines=dicomrt_nASCIIlines(filename_list);

% Get dose images and create 3D Volume
fid=fopen(filename_list);
nfiles=0;
skip_header_mf=0;
DoseGridScaling_mf=1;
case_study=[];
CELLStore=0;

% import plan information
rtplan_location=fgetl(fid);

dictFlg = checkDictUse;
if dictFlg
    rtplan=dicominfo(rtplan_location, 'dictionary', 'ES - IPT4.1CompatibleDictionary.mat');
else
    rtplan=dicominfo(rtplan_location);
end

% retrieve number of beams and beam labels
beams=fieldnames(rtplan.BeamSequence);
nbeams=size(beams,1);

% Define cell array to store info
case_study_info=cell(1);
case_study_info{1}=rtplan;

if exist('force')==0
    [PatientPositionCODE]=dicomrt_getPatientPosition(rtplan);
elseif exist('force')~=0
    if force==0;
        [PatientPositionCODE]=dicomrt_getPatientPosition(rtplan);
    end
else
    warning('dicomrt_loaddose: Dicom load was forced. No PatientPosition check is performed!');
end

try
    fractions=rtplan.FractionGroupSequence.Item_1.NumberOfFractionsPlanned;
    if isempty(fractions)==1
        fractions=1;
    end
catch
    disp('This is a single franction plan');
    fractions=1;
end

% Progress bar
h = waitbar(0,['Loading progress:']);
set(h,'Name','dicomrt_loaddose: loading RTDOSE objects');

% loop until the end-of-file is reached and build 3D dose matrix
while (feof(fid)~=1);
    nfiles=nfiles+1; % counting
    nfilescheck=nfiles; % check for eof
    file_location{1,nfiles}=fgetl(fid);
    if isnumeric(file_location{1,nfiles}), nfiles=nfiles-1, break, end % end of line reached

    dictFlg = checkDictUse;
    if dictFlg
        % import dose information
        if isdeployed
            info_image = dicominfo(file_location{1,nfiles}, 'dictionary', ...
                fullfile(getCERRPath,'bin','ES - IPT4.1CompatibleDictionary.mat'));
        else
            info_image = dicominfo(file_location{1,nfiles}, 'dictionary',...
                'ES - IPT4.1CompatibleDictionary.mat');
        end
    else
        info_image=dicominfo(file_location{1,nfiles});
    end

    try
        image=dicomread(file_location{1,nfiles}); % import pixel data
        dimage=double(squeeze(image)); % convert pixel data to double
    catch
        dictFlg = checkDictUse;
        if dictFlg
            info_image_mf=dicominfo(file_location{1,nfiles}, 'dictionary', 'ES - IPT4.1CompatibleDictionary.mat');
        else
            info_image_mf=dicominfo(file_location{1,nfiles});
        end

        DoseGridScaling_mf=info_image_mf.DoseGridScaling;
        skip_header_mf=1;
        % Give option to load individual beam/segments or total dose
        disp('This appear to be a Multi-frame study with dose contribution');
        disp('Do you want to:');
        disp('(1) load the dose matrix as a sum of all beams [default]');
        disp('(2) keep individual dose contribution');
        % with option (2) it is supposed that only beam contribution is exported
        % no support for segment contribution is given for the time being
        % because no TPS is currently capable of doing this
        STOREoption = input('Option: ');
        if STOREoption == 2
            CELLStore = 1;
            case_study = cell(nbeams,2);
        else
            CELLStore = 0;
        end
    end
    if skip_header_mf==1 & nfiles==1
    elseif skip_header_mf==1 & nfiles>1 & CELLStore == 1
        % Multi-frame with dose contribution
        if strcmpi(info_image.DoseSummationType,'FRACTION')==1 | ...
                strcmpi(info_image.DoseSummationType,'BEAM')==1
            dimage=dimage.*info_image.DoseGridScaling.*DoseGridScaling_mf;
        elseif strcmpi(info_image.DoseSummationType,'PLAN')==1
            dimage=dimage./info_image.DoseGridScaling.*fractions.*DoseGridScaling_mf;
        end
        case_study_info{nfiles}=info_image;
        case_study{nfiles-1,1}=getfield(rtplan,'BeamSequence',char(beams(nfiles-1)),'BeamName');
        case_study{nfiles-1,2}=dimage;
        zmesh=info_image.ImagePositionPatient(3)+info_image.GridFrameOffsetVector;
    elseif skip_header_mf==1 & nfiles>1 & CELLStore == 0
        % Multi-frame with dose contribution
        if strcmpi(info_image.DoseSummationType,'FRACTION')==1 | ...
                strcmpi(info_image.DoseSummationType,'BEAM')==1
            dimage=dimage.*info_image.DoseGridScaling.*DoseGridScaling_mf;
        elseif strcmpi(info_image.DoseSummationType,'PLAN')==1
            dimage=dimage./info_image.DoseGridScaling.*fractions.*DoseGridScaling_mf;
        end
        case_study_info{nfiles+1}=info_image;
        if length(case_study)==0
            case_study=dimage;
        else
            case_study=case_study+dimage;
        end
        zmesh=info_image.ImagePositionPatient(3)+info_image.GridFrameOffsetVector;
    elseif  skip_header_mf==0
        if length(size(image))==4
            % this is a Multi-frame study without dose components
            if strcmpi(info_image.DoseSummationType,'FRACTION')==1 | ...
                    strcmpi(info_image.DoseSummationType,'BEAM')==1
                dimage=dimage.*info_image.DoseGridScaling.*DoseGridScaling_mf;
            elseif strcmpi(info_image.DoseSummationType,'PLAN')==1
                dimage=dimage./info_image.DoseGridScaling.*fractions.*DoseGridScaling_mf;
            end
            case_study_info{nfiles+1}=info_image;
            case_study=dimage;
            zmesh=info_image.ImagePositionPatient(3)+info_image.GridFrameOffsetVector;
        else % not a multi-frame !
            if strcmpi(info_image.DoseSummationType,'FRACTION')==1 | ...
                    strcmpi(info_image.DoseSummationType,'BEAM')==1
                dimage=dimage.*info_image.DoseGridScaling.*DoseGridScaling_mf;
            elseif strcmpi(info_image.DoseSummationType,'PLAN')==1
                dimage=dimage./info_image.DoseGridScaling.*fractions.*DoseGridScaling_mf;
            end
            case_study_info{nfiles+1}=info_image;
            case_study(:,:,nfiles)=dimage;
            zmesh(nfiles)=info_image.ImagePositionPatient(3);
        end
    end
    waitbar(nfiles/nlines,h);
end

% Make zmesh a column vector
zmesh=dicomrt_makevertical(zmesh);

fclose(fid);

if nfilescheck~=nfiles;
    warning('dicomrt_loaddose: End of file was prematurely reached. Check the expected dimensions of your data. It may be OK to continue');
end

% PatientOrientation     ImageOrientationPatient
%
% HFS                    (1,0,0) (0,1,0)
% FFS                    (1,0,0) (0,1,0)
% HFP                    (-1,0,0) (0,-1,0)
% FFP                    (-1,0,0) (0,-1,0)
%
%
if PatientPositionCODE == 1 | PatientPositionCODE == 2
    min_x=info_image.ImagePositionPatient(1);
    pixel_spacing_x=info_image.PixelSpacing(1);

    min_y=info_image.ImagePositionPatient(2);
    pixel_spacing_y=info_image.PixelSpacing(2);

    [xmesh] = dicomrt_create1dmesh(min_x,pixel_spacing_x,size(image,2),0);
    [ymesh] = dicomrt_create1dmesh(min_y,pixel_spacing_y,size(image,1),0);

else
    max_x=info_image.ImagePositionPatient(1);
    pixel_spacing_x=info_image.PixelSpacing(1);

    max_y=info_image.ImagePositionPatient(2);
    pixel_spacing_y=info_image.PixelSpacing(2);

    [xmesh] = dicomrt_create1dmesh(max_x,pixel_spacing_x,size(image,2),1);
    [ymesh] = dicomrt_create1dmesh(max_y,pixel_spacing_y,size(image,1),1);

end

zmesh=dicomrt_mmdigit(zmesh*0.1,7);
ymesh=dicomrt_mmdigit(ymesh*0.1,7);
xmesh=dicomrt_mmdigit(xmesh*0.1,7);

% Check support for current Patient Position
if PatientPositionCODE == 1 % supported Patient Position: HFS
    disp('dicomrt_loadRTdose: Patient Position is Head First Supine (HFS).');
elseif PatientPositionCODE == 2 % supported Patient Position: FFS
    disp('dicomrt_loadRTdose: Patient Position is Feet First Supine (FFS).');
elseif PatientPositionCODE == 3 % supported Patient Position: HFP
    disp('dicomrt_loadRTdose: Patient Position is Head First Prone (HFP).');
elseif PatientPositionCODE == 4 % supported Patient Position: FFP
    disp('dicomrt_loadRTdose: Patient Position is Feet First Prone (FFP).');
else
    warning('dicomrt_loaddose: Unable to determine Patient Position');
    PatientPosition=input('dicomrt_loadRTdose: Please specify Patient Position: HFS(default),FFS,HFP,FFP: ','s');
    if isempty(PatientPosition)==1
        PatientPosition='HFS';
    end

    if strcmpi(PatientPosition, 'HFS')
        PatientPositionCODE = 1;
    elseif strcmpi(PatientPosition, 'FFS')
        PatientPositionCODE = 2;
    elseif strcmpi(PatientPosition, 'HFP')
        PatientPositionCODE = 3;
    elseif strcmpi(PatientPosition, 'FFP')
        PatientPositionCODE = 4;
    end

end

% Create a cell array where to store rtplan and dose matrix
cell_case_study=cell(3,1);
cell_case_study{1,1}=case_study_info;
cell_case_study{2,1}=case_study;
cell_case_study{3,1}=[];
% Completed

% Close progress bar
close(h);


% mff_exportcategories - export MFF EEG event from EEGLAB structure to
%                    'categories.xml' file
% Usage:
%   mff_exportcategories(EEG, mffFile);
%
% Inputs:
%  EEG     - EEGLAB structure
%  mffFile - filename/foldername for the MFF file (MFF file/folder must
%            already exist)

% This file is part of mffmatlabio.
%
% mffmatlabio 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.
%
% mffmatlabio 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 mffmatlabio.  If not, see <https://www.gnu.org/licenses/>.

function indtle = mff_exportcategories(EEG, mffFile)

indtle = []; % time locking event indices
if EEG.trials == 1
    return;
end

p = fileparts(which('mff_importsignal.m'));
warning('off', 'MATLAB:Java:DuplicateClass');
javaaddpath(fullfile(p, 'MFF-1.2.2-jar-with-dependencies.jar'));
warning('on', 'MATLAB:Java:DuplicateClass');

% Create a factory.
mfffactorydelegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
mfffactory         = javaObject('com.egi.services.mff.api.MFFFactory', mfffactorydelegate);

categoriesRType = javaObject('com.egi.services.mff.api.MFFResourceType', javaMethod('valueOf', 'com.egi.services.mff.api.MFFResourceType$MFFResourceTypes', 'kMFF_RT_Categories'));
if mfffactory.createResourceAtURI(fullfile(mffFile, 'categories.xml'), categoriesRType)
    fprintf('categories.xml file created successfully\n');
else
    fprintf('categories.xml ressource already exist, overwriting\n');
end
catsResource = mfffactory.openResourceAtURI( fullfile(mffFile, 'categories.xml'), categoriesRType);

% find time-locking events
% ------------------------
events   = EEG.event;
eventlat = abs(eeg_point2lat( [ events.latency ], [ events.epoch ], EEG.srate, [EEG.xmin EEG.xmax]));
indtle    = find(eventlat == 0);
if length(indtle) < EEG.trials
    indtle    = find(eventlat < 0.02);
    if length(indtle) ~= EEG.trials
        if isfield(EEG.event, 'begintime')
            indtle = find(cellfun(@isempty, { EEG.event.begintime }));
            if length(indtle) ~= EEG.trials
                disp('WARNING: NOT THE RIGHT NUMBER OF TIME-LOCKING EVENTS');
            end
        end
    end
end

events = events(indtle);
uniqueType = unique( { events.type } );
jCatList = javaObject('java.util.ArrayList');
epochLen = [];
for iType = 1:length(uniqueType)
    trials = strmatch( uniqueType{iType}, { events.type }, 'exact'); % get time locking events

    catObj = javaObject('com.egi.services.mff.api.Category');
    catObj.setName( events(trials(1)).type );
    jList = javaObject('java.util.ArrayList');
    for iTrial = 1:length(trials)
        segmentObj = javaObject('com.egi.services.mff.api.Segment');
        epoch      = events(trials(iTrial)).epoch;

        segmentObj.setName( events(trials(iTrial)).type );
        segmentObj.setBeginTime(  round((epoch-1)*EEG.pnts/round(EEG.srate)*1000000) );
        segmentObj.setEndTime(    round((epoch  )*EEG.pnts/round(EEG.srate)*1000000) );
        segmentObj.setEventBegin( round((events(trials(iTrial)).latency-1)/round(EEG.srate)*1000000) );
        if isfield(events(trials(iTrial)), 'duration') && ~isempty(events(trials(iTrial)).duration)
             duration = events(trials(iTrial)).duration;
        else duration = 0;
        end
        segmentObj.setEventEnd(   round((events(trials(iTrial)).latency-1+duration)/round(EEG.srate)*1000000) );
        if isfield(events, 'status')
            segmentObj.setStatus(  events(trials(iTrial)).status );
        end
        if isfield(events, 'mffkeysbackup')
            % if additional keys are present -> average (not sure this heuristic is always correct)
            segmentObj.setName( 'Average' );

            if ~isempty(events(trials(iTrial)).mffkeysbackup)
                jListKeys = javaObject('java.util.ArrayList');
                tmpKeys = eval(events(trials(iTrial)).mffkeysbackup);
                for iKey = 1:length(tmpKeys);
                    keyObj = javaObject('com.egi.services.mff.api.Key');
                    keyObj.setCode(tmpKeys(iKey).code);
                    keyObj.setData(tmpKeys(iKey).data);
                    keyObj.setDataType(tmpKeys(iKey).datatype);
                    keyObj.setDescription(tmpKeys(iKey).description);
                    jListKeys.add(keyObj);
                end
                segmentObj.setKeys(jListKeys);
            end
        end

        % check epoch length
        epochLenTmp = segmentObj.getEndTime() - segmentObj.getBeginTime();
        if isempty(epochLen)
            epochLen = epochLenTmp;
        elseif epochLen ~= epochLenTmp
            error('Epoch length export error')
        end

        jList.add(segmentObj);
    end
    catObj.setSegments(jList);
    jCatList.add(catObj);
end

catsResource.setCategories(jCatList);
catsResource.saveResource();


function a = linIt(A)
% function a = linIt(A)
%	a = A(:);
	a = A(:);
end


function [success,msg] = ConvertLarvaeRiveraAlba2JAABA(varargin)

success = false;
msg = '';

[inmoviefile,intrxfile,...
  expdir,moviefilestr,trxfilestr,perframedirstr,...
  dosoftlink] = myparse(varargin,...
  'inmoviefile','','intrxfile','',...
  'expdir','','moviefilestr','movie.ufmf','trxfilestr','trx.mat','perframedirstr','perframe',...
  'dosoftlink',false);

% check that required inputs are given
if isempty(inmoviefile),
  msg = 'Input movie file is empty';
  return;
end
if isempty(intrxfile),
  msg = 'Input trx mat file is empty';
  return;
end

% output file locations
moviefile = fullfile(expdir,moviefilestr);
trxfile = fullfile(expdir,trxfilestr);
perframedir = fullfile(expdir,perframedirstr);

% load in the trx
try
  td = load(intrxfile,'-regexp','^(trx|timestamps)$');
  if ~isfield(td,'trx'),
    msg = sprintf('No trx variable in file %s',intrxfile);
    return;
  end
  trx = td.trx;
  if isfield(td,'timestamps'),
    timestamps = td.timestamps;
  else
    timestamps = [];
  end
  clear td;
catch ME,
  msg = sprintf('Could not load trx from file %s: %s',intrxfile,getReport(ME));
  return;
end

% compute timestamps
if isempty(timestamps),
  nframes = max([trx.endframe]);
  dt = zeros(1,nframes-1);
  n = zeros(1,nframes-1);
  for i = 1:numel(trx),
    dt(trx(i).firstframe:trx(i).endframe-1) = ...
      dt(trx(i).firstframe:trx(i).endframe-1) + trx(i).dt;
    n(trx(i).firstframe:trx(i).endframe-1) = ...
      n(trx(i).firstframe:trx(i).endframe-1) + 1;
  end
  dt(n>0) = dt(n>0) / n(n>0);
  mediandt = median(dt(dt>0));
  dt(n==0) = mediandt;
  timestamps = [0,cumsum(dt)]; %#ok<NASGU>
end

% create the experiment directory
if ~exist(expdir,'dir'),
  [success1,msg1] = mkdir(expdir);
  if ~success1,
    msg = msg1;
    return;
  end
end

% save the trx file
try
  save(trxfile,'trx','timestamps');
catch ME,
  msg = sprintf('Could not save to file %s: %s',trxfile,getReport(ME));
  return;
end
if ~exist(trxfile,'file'),
  msg = sprintf('Failed to save trx to file %s',trxfile);
  return;
end

% copy/soft-link movie
if strcmp(fullfile(inmoviefile),fullfile(moviefile)),
  fprintf('Input and out movie files are the same, not copying/linking.\n');
else

  if dosoftlink,
    if isunix,
      cmd = sprintf('ln -s %s %s',inmoviefile,moviefile);
      unix(cmd);
      % test to make sure it worked
      [status,result] = unix(sprintf('readlink %s',moviefile));
      result = strtrim(result);
      if status ~= 0 || ~strcmp(result,inmoviefile),
        warndlg(sprintf('Failed to make soft link, copying %s to %s instead',inmoviefile,moviefile));
        dosoftlink = false;
      end
    elseif ispc,
      cmd = sprintf('mkshortcut.vbs /target:"%s" /shortcut:"%s"',inmoviefile,moviefile);
      fprintf('Making a Windows shortcut file at "%s" with target "%s"\n',inmoviefile,moviefile);
      system(cmd);
      % test to make sure that worked
      [equalmoviefile,didfind] = GetPCShortcutFileActualPath(moviefile);
      if ~didfind || ~strcmp(equalmoviefile,inmoviefile),
        warndlg(sprintf('Failed to make shortcut, copying %s to %s instead',inmoviefile,moviefile));
        dosoftlink = false;
      end
    else
      warndlg(sprintf('Unknown OS, not soft-linking movie file %s',inmoviefile));
      dosoftlink = false;
    end
  end

  if ~dosoftlink,
    [success1,msg1] = copyfile(inmoviefile,moviefile);
    if ~success1,
      msg = msg1;
      success = false;
      return;
    end
  end
end

% make per-frame directory
if ~exist(perframedir,'dir'),
  [success1,msg1] = mkdir(perframedir);
  if ~success1,
    msg = msg1;
    return;
  end
end

success = true;