function methods = get_method_configs()
% Get properties of all proposal methods. For examples, this includes paths to
% candidate files, intermediate files, and also information about how to sort
% candidates.

% If you want to add your own method, add it at the bottom.

colormap = [
228, 229, 97
163, 163, 163
218, 71, 56
219, 135, 45
145, 92, 146
83, 136, 173
106,61,154
225, 119, 174
142, 195, 129
51,160,44
223, 200, 51
92, 172, 158
177,89,40
177,89,40
188, 128, 189
177,89,40
251,154,153
31,120,180
177,89,40
177,89,40
177,89,40
177,89,40
177,89,40
177,89,40
177,89,40
] ./ 256;

  config = get_config();

  methods = [];

  i = numel(methods) + 1;
  methods(i).name = 'Objectness';
  methods(i).short_name = 'O';
  methods = add_paths(methods(i), config, 'objectness/');
  methods(i).order = 'descend';
  methods(i).extract = @run_objectness;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'Rahtu';
  methods(i).short_name = 'R1';
  methods(i) = add_paths(methods(i), config, 'categ_indep_detection/');
  methods(i).order = 'none';
  methods(i).extract = @run_categ_independent;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'SelectiveSearch';
  methods(i).short_name = 'SS';
  methods(i) = add_paths(methods(i), config, 'selective_search/');
  methods(i).order = 'ascend';
  methods(i).extract = @run_selective_search;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'RandomizedPrims';
  methods(i).short_name = 'RP';
  methods(i) = add_paths(methods(i), config, 'randomized_prims/');
  methods(i).gt_recall_num_candidates = 20000;
  methods(i).rerun_num_candidates = [];
  methods(i).repeatability_num_candidates = 5000;
  methods(i).order = 'none';
  methods(i).extract = @run_randomized_prims;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'Uniform';
  methods(i).short_name = 'U';
  methods(i) = add_paths(methods(i), config, 'random_uniform/');
  methods(i).order = 'random';
  methods(i).extract = @sample_uniform;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = true;

  i = numel(methods) + 1;
  methods(i).name = 'Gaussian';
  methods(i).short_name = 'G';
  methods(i) = add_paths(methods(i), config, 'random_gaussian/');
  methods(i).order = 'random';
  methods(i).extract = @sample_gaussian;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = true;

  i = numel(methods) + 1;
  methods(i).name = 'CPMC';
  methods(i).short_name = 'C';
  methods(i) = add_paths(methods(i), config, 'CPMC/');
  methods(i).order = 'descend';
  methods(i).extract = @run_cpmc;
  methods(i).num_candidates = false;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'Bing';
  methods(i).short_name = 'B';
  methods(i) = add_paths(methods(i), config, 'BING/');
  methods(i).order = 'descend';
  methods(i).extract = @run_bing;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'Endres';
  methods(i).short_name = 'E';
  methods(i) = add_paths(methods(i), config, 'endres/');
  methods(i).order = 'none';
  methods(i).extract = @run_prop;
  methods(i).num_candidates = false;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'Rantalankila';
  methods(i).short_name = 'R4';
  methods(i) = add_paths(methods(i), config, 'Rantalankila/');
  methods(i).order = 'none';
  methods(i).extract = @run_rantalankila;
  methods(i).num_candidates = true;
  methods(i).rerun_num_candidates = [100 1000 10000];
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'Superpixels';
  methods(i).short_name = 'SP';
  methods(i) = add_paths(methods(i), config, 'segmentation_baseline/');
  methods(i).order = 'none';
  methods(i).extract = @run_felsen_candidates;
  methods(i).num_candidates = false;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = true;

  i = numel(methods) + 1;
  methods(i).name = 'Sliding window';
  methods(i).short_name = 'SW';
  methods(i) = add_paths(methods(i), config, 'sliding_window/');
  methods(i).order = 'none';
  methods(i).extract = @sample_bing_windows;
  methods(i).num_candidates = true;
  methods(i).rerun_num_candidates = ceil(10 .^ (2:0.5:4));
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = true;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes';
  methods(i).short_name = 'EB70';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_70/');
  methods(i).order = 'descend';
  methods(i).extract = @run_edge_boxes;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes50';
  methods(i).short_name = 'EB50';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_50/');
  methods(i).order = 'descend';
  methods(i).extract = @run_edge_boxes50;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;
  methods(i).line_style = ':';

  i = numel(methods) + 1;
  methods(i).name = 'MCG';
  methods(i).short_name = 'M';
  methods(i) = add_paths(methods(i), config, 'MCG2015/');
  methods(i).order = 'none';
  methods(i).extract = @run_MCG2015;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes90';
  methods(i).short_name = 'EB90';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_90/');
  methods(i).order = 'descend';
  methods(i).extract = @run_edge_boxes90;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;
  methods(i).line_style = '-.';

  i = numel(methods) + 1;
  methods(i).name = 'Rigor';
  methods(i).short_name = 'Ri';
  methods(i) = add_paths(methods(i), config, 'rigor/');
  methods(i).order = 'none';
  methods(i).extract = @run_rigor;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;
  methods(i).rerun_num_candidates = [10 100 1000 2000 10000];

  i = numel(methods) + 1;
  methods(i).name = 'Geodesic';
  methods(i).short_name = 'G';
  methods(i) = add_paths(methods(i), config, 'geodesic/');
  methods(i).order = 'none';
  methods(i).extract = @run_gop;
  methods(i).num_candidates = false;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;
  methods(i).rerun_num_candidates = [10 100 1000 2000 10000];

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes60';
  methods(i).short_name = 'EB60';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_60/');
  methods(i).order = 'descend';
  methods(i).extract = @run_edge_boxes60;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes80';
  methods(i).short_name = 'EB80';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_80/');
  methods(i).order = 'descend';
  methods(i).extract = @run_edge_boxes80;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes55';
  methods(i).short_name = 'EB55';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_55/');
  methods(i).order = 'descend';
  methods(i).extract = @(im,num) run_edge_boxes(im, num, 0.65, 0.60);
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes65';
  methods(i).short_name = 'EB65';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_65/');
  methods(i).order = 'descend';
  methods(i).extract = @(im,num) run_edge_boxes(im, num, 0.65, 0.70);
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes75';
  methods(i).short_name = 'EB75';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_75/');
  methods(i).order = 'descend';
  methods(i).extract = @(im,num) run_edge_boxes(im, num, 0.70, 0.80);
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'EdgeBoxes85';
  methods(i).short_name = 'EB85';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_85/');
  methods(i).order = 'descend';
  methods(i).extract = @(im,num) run_edge_boxes(im, num, 0.80, 0.90);
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  i = numel(methods) + 1;
  methods(i).name = 'Edge Boxes AR';
  methods(i).short_name = 'EBAR';
  methods(i) = add_paths(methods(i), config, 'edge_boxes_AR/');
  methods(i).order = 'descend';
  methods(i).extract = @run_edge_boxes_AR;
  methods(i).num_candidates = true;
  methods(i).color = colormap(i,:);
  methods(i).is_baseline = false;

  % add your own method here:
  if false
  i = numel(methods) + 1;
  methods(i).name = 'The full name of your method';
  methods(i).short_name = 'a very short version of the name';
  methods(i) = add_paths(methods(i), config, 'ours-wip/');
  % This specifies how to order candidates so that the first n, are the best n
  % candidates. For example we run a method for 10000 candidates and then take
  % the first 10, instead of rerunning for 10 candidates. Valid orderings are:
  %   none: candidates are already sorted, do nothing
  %   ascend/descend: sort by score descending or ascending
  %   random: random order
  %   biggest/smallest: sort by size of the bounding boxes
  methods(i).order = 'descend';
  % A function pointer to a method that runs your proposal detector.
  methods(i).extract = @run_edge_boxes90;
  % If your method supports sorting this should be empty. If your method has to
  % be rerun for every number of candidates we want, specify the number of
  % candidates here:
  methods(i).rerun_num_candidates = []; % ceil(10 .^ (2:0.5:4));
  % Specifies whether or not your method takes the desired number of candidates
  % as an input.
  % TODO(hosang): Is this actually used anywhere?
  methods(i).num_candidates = true;
  % color for drawing
  methods(i).color = colormap(i,:);
  % This should be false. Is used for drawing baselines dashed.
  methods(i).is_baseline = false;
  end

  % do the sorting dance
  sort_keys = [num2cell([methods.is_baseline])', {methods.name}'];
  for i = 1:numel(methods)
    sort_keys{i,1} = sprintf('%d', sort_keys{i,1});
  end
  [~,idx] = sortrows(sort_keys);
  for i = 1:numel(methods)
    methods(idx(i)).sort_key = i;
  end
end

function method = add_paths(method, config, method_subdir)
  method.candidate_dir = fullfile(config.precomputed_candidates, method_subdir, 'mat');
  method.repeatability_candidate_dir = fullfile(config.precomputed_candidates, method_subdir, 'repeatability_mat');
  method.best_voc07_candidates_file = fullfile(config.precomputed_candidates, method_subdir, 'best_candidates.mat');
  method.best_imagenet_candidates_file = fullfile(config.precomputed_candidates, method_subdir, 'best_candidates_imagenet.mat');
  method.repeatability_matching_file = fullfile(config.precomputed_candidates, method_subdir, 'repeatability_matching.mat');
  method.candidate_dir_coco = fullfile(config.precomputed_candidates_coco, method_subdir, 'mat');
  method.best_coco14_candidates_file = fullfile(config.precomputed_candidates_coco, method_subdir, 'best_candidates_coco14.mat');
end


% Visualize validation results of system identification

%% Show training and prediction
clear ph
h = figure;
ccolors = get(gca,'colororder');
subplot(3,1,1), box on, hold on
plot([tA(1),tA(1)],[-15 260],':','Color',[0.4,0.4,0.4],'LineWidth',1.5)
text(tA(1)-30,230,'Training', 'FontSize',12)
text(5+tA(1),230,'Validation', 'FontSize',12)
plot([t;tA],[x(:,1);xA(:,1)],'Color',[.4 .4 .4],'LineWidth',1.5);
plot(tA,xA(:,1),'k','LineWidth',1.5);
plot(tB,xB(:,1),'--','Color','r','LineWidth',1.5);
grid on
ylim([-25 25])
ylabel('x_1','FontSize',13)
set(gca,'FontSize',13)
subplot(3,1,2), box on, hold on
plot([tA(1) tA(1)],[0 60],':')
plot([t;tA],[x(:,2);xA(:,2)],'Color',[.4 .4 .4],'LineWidth',1.5);
plot(tA,xA(:,2),'k','LineWidth',1.5);
plot(tB,xB(:,2),'--','Color','r','LineWidth',1.5);
grid on
ylim([-25 25])
ylabel('x_3','FontSize',13)
set(gca,'FontSize',13)

subplot(3,1,3), box on, hold on
plot([tA(1) tA(1)],[0 60],':')
ph(1) = plot([t;tA],[x(:,3);xA(:,3)],'Color',[.4 .4 .4],'LineWidth',1.5);
ph(2) = plot(tA,xA(:,3),'k','LineWidth',1.5);
ph(3) = plot(tB,xB(:,3),'--','Color','r','LineWidth',1.5);
l1=legend(ph,'Training','Validation',ModelName);
set(l1,'Location','NorthWest')
grid on
ylim([0 50])
ylabel('x_3','FontSize',13)
set(gca,'FontSize',13)
xlabel('Time','FontSize',13)
set(gca,'FontSize',13)

set(h,'Units','Inches');
set(gcf,'Position',[1 1 6. 5.5])
pos = get(h,'Position');
set(h,'PaperPositionMode','Auto','PaperSize',[pos(3), pos(4)])
print(h,'-painters','-depsc2', '-loose','-cmyk', [figpath,['EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_Validation.eps']],'-r0');

%%

clear ph
figure,box on, hold on,
ccolors = get(gca,'colororder');
plot([tA(1),tA(1)],[min(xB(:)) max([xA(:);xB(:)])],':','Color',[0.4,0.4,0.4],'LineWidth',1.5)
ylim([min([xA(:);xB(:)]) max([xA(:);xB(:)])])
plot(t,x(:,1),'Color',ccolors(1,:),'LineWidth',1);
plot(t,x(:,2),'Color',ccolors(2,:),'LineWidth',1);
ph(1) = plot([t;tA],[x(:,1);xA(:,1)],'Color',ccolors(1,:),'LineWidth',1);
ph(2) = plot([t;tA],[x(:,2);xA(:,2)],'Color',ccolors(2,:),'LineWidth',1);
ph(3) = plot([t;tA],[x(:,3);xA(:,3)],'Color',ccolors(3,:),'LineWidth',1);
ph(4) = plot(tB,xB(:,1),'-.','Color',ccolors(1,:)-[0 0.2 0.2],'LineWidth',2);
ph(5) = plot(tB,xB(:,2),'-.','Color',ccolors(2,:)-[0.1 0.2 0.09],'LineWidth',2);
ph(6) = plot(tB,xB(:,3),'-.','Color',ccolors(3,:)-[0.1 0.2 0.09],'LineWidth',2);
grid off
xlim([0 tB(end)])
xlabel('Time')
ylabel('xi')
t1 = text(tA(1)-5,40,'Training', 'FontSize',12);
t2 = text(1+tA(1),40,'Validation', 'FontSize',12);
lh = legend(ph([1,4]),'True',ModelName);
lh.Position = [lh.Position(1)-0.5,lh.Position(2)-0.15,lh.Position(3:4)];
set(gca,'LineWidth',1, 'FontSize',14)
set(gcf,'Position',[100 100 300 200])
set(gcf,'PaperPositionMode','auto')
print('-depsc2', '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_Validation_OneFig.eps']);

delete(lh); delete(t1), delete(t2);
print('-depsc2', '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_Validation_OneFig_noleg.eps']);
%% Actuation signal
clear ph
figure,box on, hold on,
ccolors = get(gca,'colororder');
plot([tA(1),tA(1)],[min([u;uv]) max([u;uv])],':','Color',[0.4,0.4,0.4],'LineWidth',1.5)
plot(t,u,'-k','LineWidth',1);
plot(tv,uv,'-k','LineWidth',1);
grid off
ylim([min([u;uv])+0.05*min([u;uv]) max([u;uv])+0.05*max([u;uv])])
xlim([0 tB(end)])
xlabel('Time')
ylabel('Input')
set(gca,'LineWidth',1, 'FontSize',14)
set(gcf,'Position',[100 100 300 200])
set(gcf,'PaperPositionMode','auto')
print('-depsc2', '-loose','-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_Actuation_OneFig.eps']);


function tf = all(I)

tf = all(I.Z(:));


function plotStream(sx,sy,samplesNum,startFrom)
% PLOTSTREAM  Plots a pair of streams (x,y) for a certain number of samples
if nargin<4 startFrom=1; end
plot(cell2mat(streamRange(sx,startFrom,samplesNum)), ...
     cell2mat(streamRange(sy,startFrom,samplesNum)));


function write_tsurf_to_obj_and_png(fileprefix, tsh)

  % Check that plot is set up for per-vertex data
  assert(strcmp(tsh.FaceColor,'interp'));
  % Even though you may pass it  with 'CData' seems it gets moved to
  % 'FaceVertexCData'
  assert(size(tsh.FaceVertexCData,2) == 1);
  assert(size(tsh.FaceVertexCData,1) == size(tsh.Vertices,1));

  % get color map
  CM = tsh.Parent.Colormap;
  im = permute(flipud(CM),[1 3 2]);
  % make it a square
  im = repmat(im,[1 size(im,1), 1]);
  % use at least 1024
  im = imresize(im,ceil(1024/size(im,1)),'nearest');
  imwrite(im,[fileprefix '.png']);

  V = tsh.Vertices;
  F = tsh.Faces;
  CA = caxis(tsh.Parent);
  D = min( max( (tsh.FaceVertexCData-CA(1))/(CA(2)-CA(1)) , 0+1/size(im,1)),1-1/size(im,1));

  save([fileprefix '.mat'],'V','F','CA','D','CM');

  writeOBJ([fileprefix '.obj'],V,F,[D D],F);
  text = fileread([fileprefix '.obj']);
  fp = fopen([fileprefix '.obj'],'w');
  fprintf(fp,'mtllib %s.mtl\n',fileprefix);
  fprintf(fp,'usemtl Textured\n');
  fprintf(fp,'%s',text);
  fclose(fp);

  fp = fopen([fileprefix '.mtl'],'w');
  fprintf(fp,'newmtl Textured\n');
  fprintf(fp,'Ka 1.000 1.000 1.000\n');
  fprintf(fp,'Kd 1.000 1.000 1.000\n');
  fprintf(fp,'Ks 0.000 0.000 0.000\n');
  fprintf(fp,'d 1.0\n');
  fprintf(fp,'illum 2\n');
  fprintf(fp,'# the diffuse texture map\n');
  fprintf(fp,'map_Kd %s.png\n',fileprefix);
  fclose(fp);

end


function [dat] = read_besa_mul(filename)

% READ_BESA_MUL reads data from a BESA multiplexed (*.mul) file
%
% Use as
%   dat = read_besa_mul(filename);

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

dat = [];
fid = fopen(filename, 'rt');

% According to the BESA documentation, the ASCII Multiplexed Format is as
% follows:
%
% The first of two header lines contains similar information to that of the
% BESA ASCII file:
%
% TimePoints= 200 Channels= 27 BeginSweep[ms]= -500.00
% SamplingInterval[ms]= 5.000 Bins/uV= 1.000 SegmentName=Condition1
%
% Note that the item 'SegmentName' is missing if no segment comment is
% specified when writing a segment to file.
%
% If an epoch of a continuous EEG is exported in ASCII multiplexed format,
% the first header line contains the additional item 'Time', which
% indicates the daytime of the first sample in the exported segment:
%
% TimePoints= 200 Channels= 27 BeginSweep[ms]= 0.00 SamplingInterval[ms]=
% 5.000 Bins/uV= 1.000 Time=22:02:53 SegmentName=Segment1

hdr1 = fgetl(fid);
% split the first header line into separate elements
%!!! 2009/09/25
%tmp = tokenize(hdr1, ' ');
tmp = tokenize(hdr1, ' ',1);
for i=1:length(tmp)
  % extract the information from each element
  dum = tokenize(tmp{i}, '=');
  var = dum{1}; % this is the name of the header variable
  val = dum{2}; % this is the value of the header variable
  var(var=='/') = '_';  % replace characters that are not valid in a structure element name
  var(var=='[') = '_';  % replace characters that are not valid in a structure element name
  var(var==']') = '_';  % replace characters that are not valid in a structure element name
  var(var=='.') = '_';  % replace characters that are not valid in a structure element name
  num = str2num(val);
  if ~isempty(num)
    dat = setfield(dat, var, num);
  else
    dat = setfield(dat, var, val);
  end
end

% The second line of the header contains labels for each channel, which may
% be either the original channel names, or the names of the channels of the
% current montage, e.g.
%
% O1 Oz P3 T5 T3 C3 F7 F3 Fp1 Fz Cz Pz Fp2 F4 F8 C4 T4 T6 P4 Fpz O2 M2 M1
% F10 F9 T10 T9
%
% Each subsequent line contains values for all 'Channels' at one time
% point, in floating point or scientific format. Values are given for the
% current or the original montage, selected as described above.
%
% Labels for source montages have the following form: 'TAr-L'.
%
% The first two letters indicate the head region:
%
% The small letter indicates in part the orientation: r=radial,
% t=tangential, and in part the relative location of the basal temporal
% source: l=lateral, m=mesial.
%
% The final letter after the hyphen indicates L=left, M=middle, R=right.

hdr2 = fgetl(fid);
% split the second header line into channel/source labels
%!!! 2009/09/25
%dat.label = tokenize(hdr2, ' ');
dat.label = tokenize(hdr2, ' ',1);

% read the actual data
dat.data = fscanf(fid, '%g');
dat.data = reshape(dat.data, [dat.Channels dat.TimePoints]);

fclose(fid);
return


function varargout = cumsum2(varargin)
%CUMSUM2   Double indefinite integral of a DISKFUN.
%   This is not allowed and returns an error.  This function exists so that the
%   error message is meaningful to a DISKFUN user.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

error('CHEBFUN:DISKFUN:CUMSUM2:fail',...
      'The indefinite integral is not supported for a diskfun.');
end


%% Reads ECG annotations in AHA format
% Reads ECG annotations in AHA format. Implements the documentation
% available in the help of the application provided with the database.
%
% Arguments:
%   + filename: recording to be read.
%   + start_sample: (opt) start sample to read. Default 1.
%   + end_sample: (opt) end sample to read. Default min(All recording, ECG block of 200 Mbytes)
%
% Output:
%   + ann: annotations for the ECG recordings.
%
%
% See also read_AHA_format, read_AHA_header, read_ECG, ECGwrapper
%
% Author: Mariano Llamedo Soria
% <matlab:web('mailto:llamedom@electron.frba.utn.edu.ar','-browser') (email)>
% Version: 0.1 beta
% Birthdate: 17/12/2010
% Last update: 19/11/2014
% Copyright 2008-2015
%
function [ ann last_sample] = read_AHA_ann( filename, start_sample, end_sample )

ann = [];
last_sample = [];

%No leer bloques mas grandes de 200 megabytes
MaxIOread = 200; %megabytes

if( nargin < 2 || isempty( start_sample ) )
    start_sample = 1;
else
    start_sample = max(1,start_sample);
end

fidECG = fopen( filename, 'r');

if( fidECG > 0 )

    fseek(fidECG, 0, 'eof');
    bytes_totales = ftell(fidECG);

    %esto es as� en la DB, si fuera necesario se podria cambiar.
    heasig.nsamp = (bytes_totales / 5);
    heasig.nsig = 2;

    if( nargin < 3 || isempty( end_sample ) )
        %Intento la lectura total por defecto
        samples2read = heasig.nsamp - (start_sample-1);
    else
        samples2read = min(heasig.nsamp, end_sample) - (start_sample-1);
    end

    if( (samples2read*heasig.nsig*2) > (MaxIOread * 1024^2) )
        samples2read = (MaxIOread * 1024^2) / heasig.nsig / 2;
        warning(['No es recomendable leer mas de ' num2str(MaxIOread) ' Mb. Realice varias lecturas.'])
    end

    try

        fseek(fidECG, ((start_sample-1)*5)+4, 'bof');

        iAnnotations = fread(fidECG, samples2read, 'char', 4);

        fclose(fidECG);

    catch ME
        fclose(fidECG);
        rethrow(ME)
    end

    last_sample = size(iAnnotations,1) + start_sample - 1;

    bMask = iAnnotations ~= '.';

    ann.time = find(bMask);

    ann.anntyp = char(iAnnotations(bMask));

end


function model = load_svm_model(filename)
%
% This file is part of the code that implements the following ICCV2015 accepted paper:
% title: "Object detection via a multi-region & semantic segmentation-aware CNN model"
% authors: Spyros Gidaris, Nikos Komodakis
% institution: Universite Paris Est, Ecole des Ponts ParisTech
% Technical report: http://arxiv.org/abs/1505.01749
% code: https://github.com/gidariss/mrcnn-object-detection
%
%
% AUTORIGHTS
% --------------------------------------------------------
% Copyright (c) 2015 Spyros Gidaris
%
% "Object detection via a multi-region & semantic segmentation-aware CNN model"
% Technical report: http://arxiv.org/abs/1505.01749
% Licensed under The MIT License [see LICENSE for details]
% ---------------------------------------------------------

load(filename, 'weights', 'bias');
model = {weights; bias};
end


function t = uminus(t)
%UMINUS Unary minus (-) for sptenmat.
%
%   See also SPTENMAT.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2012) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

t.vals = -t.vals;


function tDel = getTDel(planC)

 indexS = planC{end};
 tDelC = arrayfun(@(x) x.scanInfo(1).DICOMHeaders.TriggerTime,planC{indexS.scan},'un',0);
 nonZeroTDelV = [tDelC{:}]>0;
 n = find(nonZeroTDelV,1,'first');
 tDel = tDelC{n};

end


function img = read_pfm(filename, bPhotoshopCompatibility)
%
%
%       img = read_pfm(filename, bPhotoshopCompatibility)
%
%        Input:
%           -filename: the name of the file to open
%           -bPhotoshopCompatibility: a flag for enabling compability with
%           Adobe Photoshop. If it is set to 1 the compability is on.
%
%        Output:
%           -img: the opened image
%
%     Copyright (C) 2011-14  Francesco Banterle
%
%     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/>.
%

if(~exist('bPhotoshopCompatibility', 'var'))
    bPhotoshopCompatibility = 0;
end

%by default PFM files are open in little-endian format
fid = fopen(filename, 'r', 'l');

%reading the header
str = fscanf(fid, '%c', 3);

channels = 3;
iValid = 0;

if(str(1) == 'P')
    iValid = 1;
end

if(str(2) == 'f')
    channels = 1;
    iValid = iValid + 1;
end

if(str(2) == 'F')
    iValid = iValid + 1;
end

if(iValid ~= 2)
    fclose(fid);
    error('This is not a valid PFM file.');
end

%image size
m = fscanf(fid,'%d',1);
fscanf(fid,'%c',1);
n = fscanf(fid,'%d',1);

fscanf(fid,'%c',1);
endian_selector = fscanf(fid,'%f',1);
fscanf(fid,'%c',1);

%we have a big-endian encoded file
if(endian_selector > 0.0)
    fclose(fid);

    %reopen the file in big-endian mode
    fid = fopen(filename, 'r', 'b');
    fscanf(fid,'%c',3);
    m = fscanf(fid,'%d',1);
    fscanf(fid,'%c',1);
    n = fscanf(fid,'%d',1);
    fscanf(fid,'%c',1);
    endian_selector = fscanf(fid,'%f',1);
    fscanf(fid,'%c',1);
end

img = zeros([m, n, channels]);

total = n * m * channels;
tmpImg = fread(fid, total, 'float');

for i=1:channels
    tmpC = i:channels:total;
    img(:,:,i) = reshape(tmpImg(tmpC), m, n);
end

img = imrotate(img, 90, 'nearest');

if(bPhotoshopCompatibility)
    for i=1:channels
        img(:,:,i) = flipud(img(:,:,i));
    end
end

fclose(fid);

end


function [R, verbose] = tapas_physio_load_other_multiple_regressors(...
    filename_other_regressors, verbose)
% reads other multiple regressors from .txt-file or as variable R from .mat
%
%   R = tapas_physio_load_other_multiple_regressors(filename_other_regressors)
%
% IN
%   filename_other_regressors   filename (.mat or .txt) of other confound
%                               regressors
%
% OUT
%   R                           [Nscans NconfoundRegressors] matrix of multiple regressors
% EXAMPLE
%   tapas_physio_load_other_multiple_regressors
%
%   See also tapas_physio_orthogonalise_physiological_regressors tapas_physio_main_create_regressors

% Author: Lars Kasper
% Created: 2013-02-21
%
% Copyright (C) 2013, Institute for Biomedical Engineering, ETH/Uni Zurich.
%
% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

[fp, fn, fs] = fileparts(filename_other_regressors);

if ~exist(filename_other_regressors, 'file')
    verbose = tapas_physio_log('No input multiple regressors found', verbose, 1);
    R = [];
else
    rp = load(filename_other_regressors);
    if strcmp('.txt', fs) % text-file
        R = rp;
    else % mat file
        R = rp.R;
    end
end
end


classdef PTKDivideLungsIntoSagittalBins < PTKPlugin
    % PTKDivideLungsIntoSagittalBins. Plugin for dividing the lungs into bins along
    % the left-right axis
    %
    %     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, 2014.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    properties
        ButtonText = 'Sagittal<br>bins'
        ToolTip = 'Divides the lungs into bins along the left-right axis'
        Category = 'Lungs'

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

    methods (Static)
        function results = RunPlugin(dataset, reporting)
            whole_lung_mask = dataset.GetTemplateImage(PTKContext.Lungs);
            orientation = PTKImageOrientation.Sagittal;
            results = PTKDivideVolumeIntoSlices(whole_lung_mask, orientation, reporting);
            results.SetPreferredOrientation(PTKImageOrientation.Coronal);
            results.SetPreferredSliceNumber(round(results.ImageSize/2));
        end

        function results = GenerateImageFromResults(bins_results, image_templates, reporting)
            results = bins_results.BinImage;
            results.SetPreferredOrientation(PTKImageOrientation.Coronal);
            results.SetPreferredSliceNumber(round(results.ImageSize/2));
        end
    end
end


%% Run highPassAndPrepCleanICA on VEP PREPPED data

%% Read in the file and set the necessary parameters
basename = 'vep';
indir = 'O:\ARL_Data\VEP\VEP_Robust_1Hz'; % Input data directory used for this demo
outdir = 'O:\ARL_Data\VEP\VEP_PrepClean_Infomax';

%% Run the pipeline
for k = 1:18
    thisName = sprintf('%s_%02d', basename, k);
    fname = [indir filesep thisName '.set'];
    EEG = pop_loadset(fname);
    EEG = highPassAndPrepCleanICA(EEG, 'detrendCutoff', 1.0, ...
        'icatype', 'runica', 'extended', 0, 'fractionBad', 0.1);
    EEG.setname = [EEG.setname  'HP and PREP Clean then ICA Infomax'];
    fname = [outdir filesep thisName '.set'];
    pop_saveset(EEG, 'filename', [thisName '.set'], 'filepath', outdir, ...
                'version', '7.3');
end


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

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

% Last Modified by GUIDE v2.5 30-Nov-2017 13:55:03

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

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

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

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

% Update handles structure
guidata(hObject, handles);
global FilterType;
FilterType=0;
global std_rls;
global std_lms;
global std_fxlms;
global std_nlms;
global std_ap;
std_rls=0;
std_lms=0;
std_fxlms=0;
std_nlms=0;
std_ap=0;
global corr_rls;
global corr_lms;
global corr_fxlms;
global corr_nlms;
global corr_ap;
corr_rls=0;
corr_lms=0;
corr_fxlms=0;
corr_nlms=0;
corr_ap=0;

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

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

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global x;
global y;
global res;
global Fs;
global std_rls;
global std_lms;
global std_fxlms;
global std_nlms;
global std_ap;
global corr_rls;
global corr_lms;
global corr_fxlms;
global corr_nlms;
global corr_ap;
[x,Fs] = audioread('handel.wav');
[y,Fs]=audioread('handel_echo.wav');
length=get(handles.edit1,'String');
length=str2num(length);
ff=get(handles.edit2,'String');
ff=str2double(ff);
mu=get(handles.edit3,'String');
mu=str2double(mu);
global FilterType;
switch FilterType
    case 0
        ha=dsp.RLSFilter('Length',length,'ForgettingFactor',ff);
        [res,e] = ha(x,y);
        std_rls=std(e,1);
        corr_rls=corr(x,res);
    case 1
        ha=dsp.LMSFilter('Length',length,'StepSize',mu);
        [res,e] = ha(x,y);
        std_lms=std(e,1);
        corr_lms=corr(x,res);
    case 2
        ha=dsp.FilteredXLMSFilter('Length',length,'StepSize',mu);
        [res,e] = ha(x,y);
        std_fxlms=std(e,1);
        corr_fxlms=corr(x,res);
    case 3
        ha=dsp.LMSFilter('Length',length,'Method','Normalized LMS','StepSize',mu);
        [res,e] = ha(x,y);
        std_nlms=std(e,1);
        corr_nlms=corr(x,res);
    case 4
        ha=dsp.AffineProjectionFilter('Length',length,'StepSize',mu);
        [res,e] = ha(x,y);
        std_ap=std(e,1);
        corr_ap=corr(x,res);
end
audiowrite('handle Regenerated.wav',res,Fs);
set(handles.pushbutton4,'Enable','on');
set(handles.radiobutton1,'Enable','on');
set(handles.radiobutton1,'Value',0);
%axes(handles.axes1);
%spectrogram(x);
plot(handles.axes1,x);
title(handles.axes1,'Original Signal');
xlabel(handles.axes1,'Time Index'); ylabel(handles.axes1,'Signal Value');
plot(handles.axes2,y);
title(handles.axes2,'Echoed Signal');
xlabel(handles.axes2,'Time Index'); ylabel(handles.axes2,'Signal Value');
plot(handles.axes3,res);
title(handles.axes3,'Regenerated Signal');
xlabel(handles.axes3,'Time Index'); ylabel(handles.axes3,'Signal Value');
std_all=[std_rls,std_lms,std_nlms,std_fxlms,std_ap];
corr_all=[corr_rls,corr_lms,corr_nlms,corr_fxlms,corr_ap];
%bar(handles.axes4,mse_all);
bar(handles.axes4,std_all,0.4);
gap1=get(handles.axes4,'YTick');
ylength1=get(handles.axes4,'YLim');
ylim(handles.axes4,[0 ylength1(1,2)*1.1]);
if std_rls>0
    text(handles.axes4,1-0.3,std_rls+gap1(1,2)*0.3,'RLS');
end
if std_lms>0
    text(handles.axes4,2-0.3,std_lms+gap1(1,2)*0.3,'LMS');
end
if std_fxlms>0
    text(handles.axes4,4-0.3,std_fxlms+gap1(1,2)*0.3,'FX');
end
if std_nlms>0
    text(handles.axes4,3-0.4,std_nlms+gap1(1,2)*0.3,'NLMS');
end
if std_ap>0
    text(handles.axes4,5-0.3,std_ap+gap1(1,2)*0.3,'Affine');
end
title(handles.axes4,{'Standard deviation';'the smaller the better'});
xlabel(handles.axes4,'Filter type'); ylabel(handles.axes4,'Value');

bar(handles.axes5,corr_all,0.4);
gap2=get(handles.axes5,'YTick');
ylength2=get(handles.axes5,'YLim');
ylim(handles.axes5,[0 ylength2(1,2)*1.1]);
if corr_rls>0
    text(handles.axes5,1-0.3,corr_rls+gap2(1,2)*0.3,'RLS');
end
if corr_lms>0
    text(handles.axes5,2-0.3,corr_lms+gap2(1,2)*0.3,'LMS');
end
if corr_fxlms>0
    text(handles.axes5,4-0.3,corr_fxlms+gap2(1,2)*0.3,'FX');
end
if corr_nlms>0
    text(handles.axes5,3-0.5,corr_nlms+gap2(1,2)*0.3,'NLMS');
end
if corr_ap>0
    text(handles.axes5,5-0.3,corr_ap+gap2(1,2)*0.3,'Affine');
end
title(handles.axes5,{'Correlation coefficient';'the bigger the better'});
xlabel(handles.axes5,'Filter type'); ylabel(handles.axes5,'Value');

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global x;
global Fs;
sound(x,Fs);
pause(10);

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global y;
global Fs;
sound(y,Fs);
pause(10);

% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global res;
global Fs;
sound(res,Fs);
pause(10);

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

% Hint: get(hObject,'Value') returns toggle state of radiobutton1
global x;
global y;
global res;
if get(handles.radiobutton1,'Value')
    axes(handles.axes1);
    spectrogram(x);
    title('Original Signal');
    axes(handles.axes2);
    spectrogram(y);
    title('Echoed Signal');
    axes(handles.axes3);
    spectrogram(res);
    title('Regenerated Signal');
else
    plot(handles.axes1,x);
    title(handles.axes1,'Original Signal');
    xlabel(handles.axes1,'Time Index'); ylabel(handles.axes1,'Signal Value');
    plot(handles.axes2,y);
    title(handles.axes2,'Echoed Signal');
    xlabel(handles.axes2,'Time Index'); ylabel(handles.axes2,'Signal Value');
    plot(handles.axes3,res);
    title(handles.axes3,'Regenerated Signal');
    xlabel(handles.axes3,'Time Index'); ylabel(handles.axes3,'Signal Value');
end
guidata(hObject,handles)

% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% Determine the selected data set.
global FilterType;
set(handles.pushbutton4,'Enable','off');
set(handles.radiobutton1,'Enable','off');
str = get(hObject, 'String');
val = get(hObject,'Value');
% Set current data to the selected data set.
switch str{val}
    case 'RLS' % User selects peaks.
        FilterType=0;
        set(handles.edit1,'String','4');
        set(handles.edit2,'String','1');
        set(handles.edit2,'Enable','on');
        set(handles.edit3,'Enable','off');
    case 'LMS' % User selects membrane.
        FilterType=1;
        set(handles.edit1,'String','2');
        set(handles.edit3,'String','0.022');
        set(handles.edit2,'Enable','off');
        set(handles.edit3,'Enable','on');
    case 'FilteredXLMS' % User selects sinc.
        FilterType=2;
        set(handles.edit1,'String','2');
        set(handles.edit3,'String','0.002');
        set(handles.edit2,'Enable','off');
        set(handles.edit3,'Enable','on');
    case 'NLMS' % User selects membrane.
        FilterType=3;
        set(handles.edit1,'String','4');
        set(handles.edit3,'String','0.022');
        set(handles.edit2,'Enable','off');
        set(handles.edit3,'Enable','on');
    case 'AffineProjectionFilter' % User selects membrane.
        FilterType=4;
        set(handles.edit1,'String','2');
        set(handles.edit3,'String','0.022');
        set(handles.edit2,'Enable','off');
        set(handles.edit3,'Enable','on');
end
% Save the handles structure.
guidata(hObject,handles)

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

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

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

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

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double
value = str2double(get(handles.edit1,'String'));
flag = value > 0
if ~flag
   set(handles.edit1,'String','');
   warndlg('Value should be positive !! Please Enter Again');
% else
%    msgbox('Got the value, On it!');
end
set(handles.pushbutton4,'Enable','off');
set(handles.radiobutton1,'Enable','off');

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

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

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

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double
value = str2double(get(handles.edit2,'String'));
flag = value >= 0 && value <= 1
if ~flag
   set(handles.edit2,'String','');
   warndlg('Value should be between 0 and 1 !! Please Enter Again');
% else
%    msgbox('Got the value, On it!');
end
set(handles.pushbutton4,'Enable','off');
set(handles.radiobutton1,'Enable','off');

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

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

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

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double
value = str2double(get(handles.edit3,'String'));
flag = value > 0
if ~flag
   set(handles.edit3,'String','');
   warndlg('Value should be positive !! Please Enter Again');
% else
%    msgbox('Got the value, On it!');
end
set(handles.pushbutton4,'Enable','off');
set(handles.radiobutton1,'Enable','off');

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

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

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

% Hint: place code in OpeningFcn to populate axes1

% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
plot(handles.axes1,5);% To override colorbar of spectrogram
cla(handles.axes1);
reset(handles.axes1);
plot(handles.axes2,5);
cla(handles.axes2);
reset(handles.axes2);
plot(handles.axes3,5);
cla(handles.axes3);
reset(handles.axes3);
cla(handles.axes4);
reset(handles.axes4);
cla(handles.axes5);
reset(handles.axes5);
set(handles.popupmenu1,'Value',1);
set(handles.edit2,'Enable','on');
set(handles.edit3,'Enable','off');
set(handles.pushbutton4,'Enable','off');
set(handles.radiobutton1,'Enable','off');
global FilterType;
FilterType=0;
global std_rls;
global std_lms;
global std_fxlms;
global std_nlms;
global std_ap;
std_rls=0;
std_lms=0;
std_fxlms=0;
std_nlms=0;
std_ap=0;
global corr_rls;
global corr_lms;
global corr_fxlms;
global corr_nlms;
global corr_ap;
corr_rls=0;
corr_lms=0;
corr_fxlms=0;
corr_nlms=0;
corr_ap=0;
set(handles.edit1,'String','4');
set(handles.edit2,'String','1');
set(handles.edit3,'String','0.022');

% --- Executes during object deletion, before destroying properties.
function axes3_DeleteFcn(hObject, eventdata, handles)
% hObject    handle to axes3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


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

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

% Last Modified by GUIDE v2.5 17-Apr-2014 16:33:01

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

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

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

handles.Simuh=varargin{1};
% Load Pulse element list
try
    handles.MagElemListStruct=DoParseXML([handles.Simuh.MRiLabPath filesep 'Macro' filesep 'MagElem' filesep 'MagElem.xml']);
    guidata(hObject,handles);
    Root=DoConvStruct2Tree(handles.MagElemListStruct);
    handles.MagElemListTree=uitree('v0', 'Root',Root,'SelectionChangeFcn', {@ChkMagElemListTreeNode,handles});
    set(handles.MagElemListTree.getUIContainer,'Units','normalized');
    set(handles.MagElemListTree.getUIContainer,'Position',[0.0,0.4,0.2,0.58]);
    handles.Attrh1=[];
catch ME
    errordlg('Mag element list can not be loaded!');
    close(hObject);
    return;
end

%Load tabs for Mag Simulation
try
    handles.MagSimuAttrStruct=DoParseXML([handles.Simuh.MRiLabPath filesep 'Macro' filesep 'MagElem' filesep 'MagSimuAttr.xml']);
catch ME
    errordlg('MagSimuAttr.xml file is missing or can not be loaded!');
    close(hObject);
    return;
end

handles.Setting_tabgroup=uitabgroup(handles.Setting_uipanel);
guidata(handles.MagDesignPanel_figure,handles);
for i=1:length(handles.MagSimuAttrStruct.Children)
    eval(['handles.' handles.MagSimuAttrStruct.Children(i).Name '_tab=uitab( handles.Setting_tabgroup,' '''title'',' '''' handles.MagSimuAttrStruct.Children(i).Name ''',''Units'',''normalized'');']);
    eval(['DoEditValue(handles,handles.' handles.MagSimuAttrStruct.Children(i).Name '_tab,handles.MagSimuAttrStruct.Children(' num2str(i) ').Attributes,2,[0.2,0.15,0.0,0.15,0.15,0.05]);']);
    handles=guidata(handles.MagDesignPanel_figure);
end

% Create grid and display structure
VMmg.xdimres=str2num(get(handles.Attrh2.('XDimRes'),'String'));
VMmg.ydimres=str2num(get(handles.Attrh2.('YDimRes'),'String'));
VMmg.zdimres=str2num(get(handles.Attrh2.('ZDimRes'),'String'));

Mxdims=size(VObj.Rho);
[VMmg.xgrid,VMmg.ygrid,VMmg.zgrid]=meshgrid((-(Mxdims(2)-1)/2)*VObj.XDimRes:VMmg.xdimres:((Mxdims(2)-1)/2)*VObj.XDimRes,...
    (-(Mxdims(1)-1)/2)*VObj.YDimRes:VMmg.ydimres:((Mxdims(1)-1)/2)*VObj.YDimRes,...
    (-(Mxdims(3)-1)/2)*VObj.ZDimRes:VMmg.zdimres:((Mxdims(3)-1)/2)*VObj.ZDimRes);

VMmg.axes=handles.MagField_axes;
handles.IV=struct(...
    'xslice',(handles.Simuh.SV.Slice - (Mxdims(2)-1)/2)* VObj.XDimRes,...
    'yslice',(handles.Simuh.CV.Slice - (Mxdims(1)-1)/2)* VObj.YDimRes,...
    'zslice',(handles.Simuh.AV.Slice - (Mxdims(3)-1)/2)* VObj.ZDimRes ...
    );
view(handles.MagField_axes,3);

%Open current loaded Mag XML file
if isfield(handles.Simuh,'MagXMLFile')
    import javax.swing.*
    import javax.swing.tree.*;
    handles.MagStruct=DoParseXML(handles.Simuh.MagXMLFile);
    handles.MagXMLFile=handles.Simuh.MagXMLFile;
    DoWriteXML2m(handles.MagStruct,[handles.MagXMLFile(1:end-3) 'm']);
    %     guidata(hObject, handles);
    Root=DoConvStruct2Tree(handles.MagStruct);
    handles.MagTree=uitree('V0','Root',Root,'SelectionChangeFcn', {@ChkNode,handles});
    set(handles.MagTree.getUIContainer,'Units','normalized');
    set(handles.MagTree.getUIContainer,'Position',[0.205,0.4,0.2,0.58]);
    handles.MagTreeModel=DefaultTreeModel(Root);
    handles.MagTree.setModel(handles.MagTreeModel);
    try
        DoPlotMagFie(handles);
        set(handles.Forwards_pushbutton,'Enable','on');
        set(handles.Backwards_pushbutton,'Enable','on');
        set(handles.Display_pushbutton,'Enable','on');
        handles=guidata(hObject);
    catch me
        error_msg{1,1}='ERROR!!! Displaying dB0 field aborted.';
        error_msg{2,1}=me.message;
        errordlg(error_msg);
    end

end

% Choose default command line output for MagDesignPanel
handles.input=varargin;
handles.output=hObject;

% Update handles structure
guidata(hObject, handles);

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

function ChkMagElemListTreeNode(tree, value, handles)

handles=guidata(handles.MagDesignPanel_figure);
SelNode=tree.SelectedNodes;
SelNode=SelNode(1);
Level=SelNode.getValue;
if ~ischar(Level)
    LevelChg=diff(Level,1);
    Level([LevelChg; -1]==1)=[];
end

Node='handles.MagElemListStruct';
if Level=='0'
    eval(['handles.MagElemNode=' Node ';']);
else
    for i=1:length(Level)
        Node=[Node '.Children(' num2str(Level(i)) ')'];
    end
    eval(['handles.MagElemNode=' Node ';']);
end
guidata(handles.MagDesignPanel_figure, handles);

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

% Get default command line output from handles structure
varargout{1} = hObject;

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

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

import javax.swing.*
import javax.swing.tree.*;

[filename,pathname,filterindex]=uigetfile({'Mag*.xml','XML-files (*.xml)'},'MultiSelect','off');
if filename~=0
    if ~isempty(handles.Attrh1)
        Attrh1name=fieldnames(handles.Attrh1);
        for i=1:length(Attrh1name)
            delete(handles.Attrh1.(Attrh1name{i}));
        end
        handles.Attrh1=[];
    end
    handles.MagStruct=DoParseXML(fullfile(pathname,filename));
    handles.MagXMLFile=fullfile(pathname,filename);
    guidata(hObject, handles);
    Root=DoConvStruct2Tree(handles.MagStruct);
    handles.MagTree=uitree('v0', 'Root',Root,'SelectionChangeFcn', {@ChkNode,handles});
    set(handles.MagTree.getUIContainer,'Units','normalized');
    set(handles.MagTree.getUIContainer,'Position',[0.205,0.4,0.2,0.58]);
    handles.MagTreeModel=DefaultTreeModel(Root);
    handles.MagTree.setModel(handles.MagTreeModel);
    % Add searchig path
    path(path,pathname);
else
    errordlg('No Mag is loaded!');
    return;
end
guidata(hObject, handles);

function ChkNode(tree, value, handles)

handles=guidata(handles.MagDesignPanel_figure);
SelNode=tree.SelectedNodes;
SelNode=SelNode(1);
Level=SelNode.getValue;
if ~ischar(Level)
    LevelChg=diff(Level,1);
    Level([LevelChg; -1]==1)=[];
end

Node='handles.MagStruct';
if Level=='0'
    eval(['handles.MagNode=' Node ';']);
else
    for i=1:length(Level)
        Node=[Node '.Children(' num2str(Level(i)) ')'];
    end
    eval(['handles.MagNode=' Node ';']);
end
handles.MagNodeLvl=Node;
handles.SelNode=SelNode;

if ~isempty(handles.Attrh1)
    Attrh1name=fieldnames(handles.Attrh1);
    for i=1:length(Attrh1name)
        delete(handles.Attrh1.(Attrh1name{i}));
    end
    handles.Attrh1=[];
end

set(handles.MagAttri_uipanel,'Title',['''' char(SelNode.getName) ''' Mag Attribute'],'Unit','normalized');
if SelNode.isLeaf | SelNode.isRoot
    if strcmp(char(SelNode.getName),'Specials')
        DoEditValue(handles,handles.MagAttri_uipanel,handles.MagNode.Attributes,1,[0.25,0.25,0.0,0.1,0.1,0.05]);
    else
        DoEditValue(handles,handles.MagAttri_uipanel,handles.MagNode.Attributes,1,[0.25,0.25,0.0,0.1,0.1,0.05]);
    end
else
    guidata(handles.MagDesignPanel_figure, handles);
end

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

import javax.swing.*
import javax.swing.tree.*;

try
    switch handles.MagNode.Name
        case 'MRiLabMag'
            errordlg('MRiLabMag Root can not be deleted!');
            return;
    end

    eval([handles.MagNodeLvl '=[];']);
    nN=handles.SelNode.getNextSibling;
    while ~isempty(nN)
        Level=nN.getValue;
        Level(end)=[];
        nN.setValue(Level);
        nN=nN.getNextSibling;
    end
    guidata(hObject, handles);
    pause(0.1);

    % remove node
    handles.MagTree.setSelectedNode(handles.SelNode.getParent);
    handles.MagTreeModel.removeNodeFromParent(handles.SelNode);

    DoWriteXML(handles.MagStruct,handles.MagXMLFile);
catch me
    error_msg{1,1}='ERROR!!! Node operation aborted.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);

end

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

import javax.swing.*
import javax.swing.tree.*;

try
    ChkMagElemListTreeNode(handles.MagElemListTree, [], handles); % In case MagElem.xml updated
    handles=guidata(handles.MagDesignPanel_figure);
    switch handles.MagNode.Name
        case {'MRiLabMag'}
            % add node
            SelNode=handles.MagElemListTree.SelectedNodes;
            SelNode=SelNode(1);
            AddedNode=SelNode.clone;
            switch char(AddedNode.getName)
                case {'MagElem'}
                    errordlg([char(AddedNode.getName) ' can not be added!']);
                    return;
            end
            handles.MagTreeModel.insertNodeInto(AddedNode,handles.SelNode,handles.SelNode.getChildCount());
            handles.MagTree.setSelectedNode(AddedNode); % expand to show added child
            handles.MagTree.setSelectedNode(handles.SelNode); % insure additional nodes are added to parent

            nP=AddedNode.getPreviousSibling;
            if ~isempty(nP)
                Level=nP.getValue;
                AddedNode.setValue([Level; Level(end)+1]);
                eval([handles.MagNodeLvl '.Children(' num2str(Level(end)+1) ')=handles.MagElemNode;']);
                DoWriteXML(handles.MagStruct,handles.MagXMLFile);
            else
                nP=AddedNode.getParent;
                Level=nP.getValue;
                AddedNode.setValue([Level; 1]);
                eval([handles.MagNodeLvl '.Children=handles.MagElemNode;']);
                DoWriteXML(handles.MagStruct,handles.MagXMLFile);
            end
        otherwise
            errordlg(['Mag Element can not be added under ' handles.MagNode.Name '!']);
            return;
    end
    guidata(hObject, handles);
catch me
    error_msg{1,1}='ERROR!!! Node operation aborted.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);

end

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

% update Mag XML file
if ~isempty(handles.Attrh1)
    Attrh1name=fieldnames(handles.Attrh1);
    for i=1:2:length(Attrh1name)
        switch get(handles.Attrh1.(Attrh1name{i+1}),'Style')
            case 'edit'
                handles.MagNode.Attributes((i+1)/2).Value=get(handles.Attrh1.(Attrh1name{i+1}),'String');
            case 'checkbox'
                if get(handles.Attrh1.(Attrh1name{i+1}),'Value')
                    handles.MagNode.Attributes((i+1)/2).Value='^1';
                else
                    handles.MagNode.Attributes((i+1)/2).Value='^0';
                end
            case 'popupmenu'
                handles.MagNode.Attributes((i+1)/2).Value(2)=num2str(get(handles.Attrh1.(Attrh1name{i+1}),'Value'));
        end
    end
    eval([handles.MagNodeLvl '=handles.MagNode;']);
    DoWriteXML(handles.MagStruct,handles.MagXMLFile);
    % update associated m function
    DoWriteXML2m(handles.MagStruct,[handles.MagXMLFile(1:end-3) 'm']);
end

% update MagSimuAttr.xml
tabs=get(handles.Setting_tabgroup,'Children');
for j=1:length(handles.MagSimuAttrStruct.Children)
    Attrh2=get(tabs(j),'Children');
    for i=1:2:length(Attrh2)
        if ~iscell(get(Attrh2(end-i),'String'))
            handles.MagSimuAttrStruct.Children(j).Attributes((i+1)/2).Value=get(Attrh2(end-i),'String');
        else
            handles.MagSimuAttrStruct.Children(j).Attributes((i+1)/2).Value(2)=num2str(get(Attrh2(end-i),'Value'));
        end
    end
end
DoWriteXML(handles.MagSimuAttrStruct,[handles.Simuh.MRiLabPath filesep 'Macro' filesep 'MagElem' filesep 'MagSimuAttr.xml']);

guidata(hObject, handles);

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

import javax.swing.*
import javax.swing.tree.*;

try
    switch handles.MagNode.Name
        case 'MRiLabMag'
            errordlg('MRiLabMag Root can not be copied!');
            return;
    end
    handles.CopSelNode=handles.SelNode.clone;
    handles.CopMagNode=handles.MagNode;
    guidata(hObject, handles);
catch me
    error_msg{1,1}='ERROR!!! Node operation aborted.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);

end

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

import javax.swing.*
import javax.swing.tree.*;

try
    switch handles.MagNode.Name
        case {'MRiLabMag'}
            % paste node
            handles.MagTreeModel.insertNodeInto(handles.CopSelNode,handles.SelNode,handles.SelNode.getChildCount());
            handles.MagTree.setSelectedNode(handles.CopSelNode); % expand to show added child
            handles.MagTree.setSelectedNode(handles.SelNode); % insure additional nodes are added to parent

            nP=handles.CopSelNode.getPreviousSibling;
            if ~isempty(nP)
                Level=nP.getValue;
                handles.CopSelNode.setValue([Level; Level(end)+1]);
                eval([handles.MagNodeLvl '.Children(' num2str(Level(end)+1) ')=handles.CopMagNode;']);
                DoWriteXML(handles.MagStruct,handles.MagXMLFile);
            else
                nP=handles.CopSelNode.getParent;
                Level=nP.getValue;
                handles.CopSelNode.setValue([Level; 1]);
                eval([handles.MagNodeLvl '.Children=handles.CopMagNode;']);
                DoWriteXML(handles.MagStruct,handles.MagXMLFile);
            end
        otherwise
            errordlg(['Mag Element can not be added under ' handles.MagNode.Name '!']);
            return;
    end
    handles.CopSelNode=[];
    handles.CopMagNode=[];
    guidata(hObject, handles);
catch me
    error_msg{1,1}='ERROR!!! Node operation aborted.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);

end

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

set(hObject,'Enable','off');
set(hObject,'String','Calc...');
pause(0.01);
try
    DoPlotMagFie(handles);
    set(handles.Forwards_pushbutton,'Enable','on');
    set(handles.Backwards_pushbutton,'Enable','on');
    set(handles.Display_pushbutton,'Enable','on');
catch me
    error_msg{1,1}='Error occurred at displaying dB0 field.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);
end
set(hObject,'Enable','on');
set(hObject,'String','Execute');

% --------------------------------------------------------------------
function SavePanel_uipushtool_ClickedCallback(hObject, eventdata, handles)
% hObject    handle to SavePanel_uipushtool (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
DoSaveSnapshot(handles.MagDesignPanel_figure);

% --- Executes when user attempts to close MagDesignPanel_figure.
function MagDesignPanel_figure_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to MagDesignPanel_figure (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
delete(hObject);

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

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

global VObj;
TAttr=get(handles.Attrh2.('Plane'),'String');
switch TAttr{get(handles.Attrh2.('Plane'),'Value')}
    case 'XY'
        handles.IV.zslice=handles.IV.zslice+VObj.ZDimRes;
    case 'XZ'
        handles.IV.yslice=handles.IV.yslice+VObj.YDimRes;
    case 'YZ'
        handles.IV.xslice=handles.IV.xslice+VObj.XDimRes;
end
DoUpdateSlice(handles.MagField_axes,handles.dB0,handles.IV,'Mag');
guidata(hObject, handles);

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

global VObj;
TAttr=get(handles.Attrh2.('Plane'),'String');
switch TAttr{get(handles.Attrh2.('Plane'),'Value')}
    case 'XY'
        handles.IV.zslice=handles.IV.zslice-VObj.ZDimRes;
    case 'XZ'
        handles.IV.yslice=handles.IV.yslice-VObj.YDimRes;
    case 'YZ'
        handles.IV.xslice=handles.IV.xslice-VObj.XDimRes;
end
DoUpdateSlice(handles.MagField_axes,handles.dB0,handles.IV,'Mag');
guidata(hObject, handles);

% --------------------------------------------------------------------
function Cursor_uitoggletool_ClickedCallback(hObject, eventdata, handles)
% hObject    handle to Cursor_uitoggletool (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if ~isfield(handles,'dcm')
    handles.dcm=datacursormode(handles.MagDesignPanel_figure);
    datacursormode on
    set(handles.dcm,'updatefcn',{@Cursor_update,handles});
else
    if strcmp(get(handles.dcm,'Enable'),'on')
        set(handles.dcm,'Enable','off');
    else
        set(handles.dcm,'Enable','on');
    end
end
guidata(hObject, handles);

function output_txt = Cursor_update(obj,event_obj,handles)
% Display the position of the data cursor
% obj          Currently not used (empty)
% event_obj    Handle to event object
% output_txt   Data cursor text string (string or cell array of strings).

global VObj;
global VCtl;
global VMmg;

handles=guidata(handles.MagDesignPanel_figure);
pos = get(event_obj,'Position');
pos(1)=round((pos(1)+VCtl.ISO(1)*VObj.XDimRes)/VMmg.xdimres);
pos(2)=round((pos(2)+VCtl.ISO(2)*VObj.YDimRes)/VMmg.ydimres);
pos(3)=round((pos(3)+VCtl.ISO(3)*VObj.ZDimRes)/VMmg.zdimres);

output_txt = {['X: ',num2str(pos(1),4)],...
    ['Y: ',num2str(pos(2),4)],...
    ['Z: ',num2str(pos(3),4)],...
    ['Value: ',num2str(handles.dB0(pos(2),pos(1),pos(3)),4)]};

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

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

prompt = {'Enter NEW mag name:','Enter NEW mag note:'};
dlg_title = 'Input for creating new mag';
num_lines = 1;
def = {'Mag_CustomHead','Customized dB0 Field Head Magnet'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
if isempty(answer)
    warndlg('No new mag file is created!');
    return
end
if isempty(answer{1})
    warndlg('No new mag file is created!');
    return
end
if ~strcmp(answer{1}(1:4),'Mag_')
    warndlg('Mag name must have a prefix ''Mag_'', please rename your mag!');
    return
end
magpath=uigetdir(pwd,'Specify a saving path for new mag file.');
if magpath==0
    warndlg('You have to specify a saving path!');
    return;
end

% Create new mag file
mkdir([magpath filesep answer{1}]); % make folder
copyfile([handles.Simuh.MRiLabPath filesep 'Config' filesep 'Mag' filesep 'Head' filesep 'Mag_LinearHead' filesep 'Mag_LinearHead.xml'],...
    [magpath filesep answer{1} filesep answer{1} '.xml']); % copy mag temple
% Add searchig path
path(path,[magpath filesep answer{1}]);
% Load new mag file
import javax.swing.*;
import javax.swing.tree.*;
if ~isempty(handles.Attrh1)
    Attrh1name=fieldnames(handles.Attrh1);
    for i=1:length(Attrh1name)
        delete(handles.Attrh1.(Attrh1name{i}));
    end
    handles.Attrh1=[];
end
handles.MagStruct=DoParseXML([magpath filesep answer{1} filesep answer{1} '.xml']);
for i=1:length(handles.MagStruct.Attributes)
    if strcmp(handles.MagStruct.Attributes(i).Name,'Name')
        handles.MagStruct.Attributes(i).Value = answer{1};
    elseif strcmp(handles.MagStruct.Attributes(i).Name,'Notes')
        handles.MagStruct.Attributes(i).Value = answer{2};
    end
end
DoWriteXML(handles.MagStruct,[magpath filesep answer{1} filesep answer{1} '.xml']); %update new mag file
handles.MagXMLFile=[magpath filesep answer{1} filesep answer{1} '.xml'];
DoWriteXML2m(handles.MagStruct,[handles.MagXMLFile(1:end-3) 'm']);
guidata(hObject, handles);
Root=DoConvStruct2Tree(handles.MagStruct);
handles.MagTree=uitree('V0','Root',Root,'SelectionChangeFcn', {@ChkNode,handles});
set(handles.MagTree.getUIContainer,'Units','normalized');
set(handles.MagTree.getUIContainer,'Position',[0.205,0.4,0.2,0.58]);
handles.MagTreeModel=DefaultTreeModel(Root);
handles.MagTree.setModel(handles.MagTreeModel);
cla(handles.MagField_axes);
guidata(hObject, handles);

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

tempaxes = gca;
try
    if strcmp(get(gcf,'Selectiontype'),'alt')
        figure 			% Create a new figure
        ax_new = axes;
        copyaxes(tempaxes, ax_new);
    end
catch me
end

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

assignin('base', 'dB0', handles.dB0);
MU_Matrix_Display('dB0','Magnitude');