function dt6 = dtiMakeDt6FromFsl(b0FileName, t1FileName)
%
% dt6 = dtiMakeDt6FromFsl([b0FileName], [t1FileName])
%
% Takes a set of images from FSL's DTI image files and saves them out as
% in a dt6 matlab file. You should specify the FSL S0 (usually b=0) file as
% input (a file dialog will pop-up if you don't).
%
% The t1 file is optional- if it is omitted, then the b=0 will be used as
% the anatomical reference.
%
% HISTORY:
% 2005.08.04 RFD (bob@white.stanford.edu) wrote it (based on dtiMakeDt6)

slice = [0,0,0]; % slice to display for checking coregistration
bb = [-80,80; -120,90; -60,90]';
mmDt = [2 2 2];
mmAnat = [1 1 1];
autoAlign = false;
showFigs = true;

if ~exist('b0FileName','var') | isempty(b0FileName)
    [f, p] = uigetfile({'*.nii.gz','NIFTI gz';'*.*','All files'}, 'Select the FSL S0 file...');
    if(isnumeric(f)) error('Need an S0 file to continue...'); end
    b0FileName = fullfile(p, f);
    disp(b0FileName);
end
b0 = niftiRead(b0FileName);
% Fix ill-specified quaternion xforms so that they do something reasonable.
if(all(b0.qto_ijk(1:3,4) == [0 0 0]'))
    % *** HACK! [38 69 28] is the ac for one normalized data set- maybe it
    % works for many?
    sz = size(b0.data);
    origin = round(sz(1:3)./2.*[0.95 1.1 0.9]);
    b0.qto_ijk(1:3,4) = origin'+0.5;
    b0.qto_xyz = inv(b0.qto_ijk);
end
b0.data = double(b0.data);
% Clip vals <0 (these should be junk for a b=0 image)
b0.data(b0.data<0) = 0;

if ~exist('t1FileName','var')
    [f, p] = uigetfile({'*.nii.gz','NIFTI gz';'*.hdr','Analyze files (*.hdr)';'*.*','All files'},...
        'Select the T1 file...', b0FileName);
    if(isnumeric(f))
        t1FileName = [];
    else
        t1FileName = fullfile(p, f);
        disp(t1FileName);
    end
end
if(~isempty(t1FileName))
    t1 = niftiRead(t1FileName);
    % Fix ill-specified quaternion xforms so that they do something reasonable.
    if(all(t1.qto_ijk(1:3,4) == [0 0 0]'))
        sz = size(t1.data);
        origin = round(sz(1:3)./2.*[0.95 1.1 0.9]);
        t1.qto_ijk(1:3,4) = origin'+0.5;
        t1.qto_xyz = inv(t1.qto_ijk);
    end
    t1.data = double(t1.data);
    t1.data(t1.data<0) = 0;
else
    t1 = b0;
end

[datapath,basename] = fileparts(b0FileName);
us = strfind(basename,'_');
basename = basename(1:us(end));

if(~exist('outPathName','var') | isempty(outPathName))
    outPathName = fullfile(datapath, [basename 'dt6.mat']);
end
if(exist(outPathName,'file') | exist([outPathName '.mat'],'file'))
  disp('output file exists- please rename...');
  [f,p] = uiputfile('*.mat', 'Select output file...', outPathName);
  if(isnumeric(f)) error('User cancelled.'); end
  outPathName = fullfile(p,f);
end

disp(['Data will be saved in ' outPathName '...']);

% *** TO DO: fix this- here we assume that the data use a NIFTI-style
% header and this it's quaternion xform is specified correctly.
t1.acpcXform = t1.qto_xyz;
b0.acpcXform = b0.qto_xyz;
% reslicing introduces a 1/2 voxel (1mm shift. We correct for that here.
b0.acpcXform(1:3,4) = b0.acpcXform(1:3,4)-mmDt'./2;

h = figure;
showFigure(h, t1, b0, bb, slice);
%set(h,'Position', [10, 50, 1000, 1000]);
set(h, 'PaperPositionMode', 'auto');
print(h, '-dpng', '-r90', [outPathName,'_headerAlign.png']);
if(~showFigs) close(h); end

if(autoAlign)
    disp('Coregistering (using spm2 tools)...');
    img = t1.data;
    img = mrAnatHistogramClip(img, 0.50, 0.995);
    VG.uint8 = uint8(round(img*255));
    VG.mat = t1.acpcXform;

    img = b0.data;
    img = mrAnatHistogramClip(img,0.40, 0.99);
    VF.uint8 = uint8(round(img*255));
    VF.mat = b0.acpcXform;
    p = defaults.coreg.estimate;
    % NOTE: there seems to be a consistent 1mm (1/2 of B0 voxel) translation
    % between the t1 and B0.
    transRot = spm_coreg(VG,VF,p);
    transRot(1:3) = transRot(1:3)+mmDt/2;
    b0.acpcXform = inv(VF.mat\spm_matrix(transRot(:)'));
    fig = figure;
    showFigure(fig, t1, b0, bb, [0,0,0], ['auto aligned']);
    set(fig, 'PaperPositionMode', 'auto');
    print(fig, '-dpng', '-r90', [outPathName,'_autoAlign.png']);
end

% Now build and save the dt6 data
eigVal = zeros([size(b0.data) 3]);
eigVec = zeros([size(b0.data) 3 3]);
for(ii=1:3)
    tmp = niftiRead(fullfile(datapath, [basename 'L' num2str(ii) '.nii.gz']));
    eigVal(:,:,:,ii) = double(tmp.data);
end
for(ii=1:3)
    tmp = niftiRead(fullfile(datapath, [basename 'V' num2str(ii) '.nii.gz']));
    eigVec(:,:,:,:,ii) = double(tmp.data);
    eigVec(:,:,:,2,ii) = -eigVec(:,:,:,2,ii);
end

dt6 = dtiRebuildTensor(eigVec, eigVal);
clear eigVal eigVec;
%dt6_tmp = dtiLoadTensorElements(fullfile(fileparts(b0.baseFname), 'TensorElements.float.'));
%%dt6_tmp = permute(dt6_tmp,[2 1 3 4]);
%for(ii=1:6)
%    dt6(:,:,:,ii) = applyCannonicalXform(dt6_tmp(:,:,:,ii), b0.cannonical, b0.mmPerVox);
%end
%dt6 = permute(dt6,[2 1 3 4]);
%clear dt6_tmp;

% Reslice everything
disp('Interpolating tensors...');
%dt6A = dtiResliceTensorAffine(dt6, inv(b0.acpcXform), b0.cannonical_mmPerVox, bb, mmDt);
%dt6A = permute(dt6A,[2 1 3 4]);
dt6 = mrAnatResliceSpm(dt6, inv(b0.acpcXform), bb, mmDt, [7 7 7 0 0 0], showFigs);
dt6(isnan(dt6)) = 0;
% NOTE: we want to apply b0.acpcXform to the tensors, even though we
% resliced them with inv(b0.acpcXform). inv(b0.acpcXform) maps from
% the new space to the old- the correct mapping for the interpolation,
% since we interpolate by creating a grid in the new space and fill it by
% pulling data from the old space. But the tensor reorientation should be
% done using the old-to-new space mapping (b0.acpcXform).
rigidXform = dtiFiniteStrainDecompose(b0.acpcXform);
[t,r] = affineDecompose([rigidXform,[0 0 0]';[0 0 0 1]]);
if(all(all(rigidXform==eye(3))))
    disp('No PPD correction needed- rotation is zero.');
else
    fprintf('Applying PPD rotation [%0.4f %0.4f %0.4f]...\n',r);
    dt6 = dtiXformTensors(dt6, rigidXform);
end
%figure; imagesc(makeMontage(dt6_new(:,:,:,1))); axis equal; colormap gray

disp('Interpolating B0...');
[b0_img,newXform] = mrAnatResliceSpm(b0.data, inv(b0.acpcXform), bb, mmDt, [7 7 7 0 0 0], showFigs);
b0_img(b0_img<0) = 0;
b0_img(isnan(b0_img)) = 0;

% create and apply a brain mask to the dt6 data
brainMask = mrAnatHistogramClip(b0_img, 0.4, 0.99);
brainMask = brainMask > 0.1;
% [c,v] = mrAnatHistogramSmooth(b0_img,256,0.05);
% % derivative of the thresholded derivative gives us the locations where a
% % rising or falling trend begins. In general, we can just take the first
% % rising trend (ie. just after the background noise) to find the brain.
% % We then back off from that by 25% (an empirically determined heuristic).
% peakStart = find(diff(diff(c)>0)>0);
% thresh = v(peakStart(1)+2);
% thresh = thresh.*0.75;
% brainMask = b0_img > thresh;
brainMask = dtiCleanImageMask(brainMask, 9);
figure; imagesc(makeMontage(brainMask)); axis equal tight; colormap(gray);
title('Brain Mask (based on b=0 image)');
dt6(repmat(~brainMask, [1,1,1,6])) = 0;

disp('Interpolating T1...');
anat.img = mrAnatResliceSpm(t1.data, inv(t1.acpcXform), bb, mmAnat, [], showFigs);
anat.img(anat.img<0) = 0;
anat.img(isnan(anat.img)) = 0;
anat.img = int16(round(anat.img));

mmPerVox = mmDt;
notes = 'Built from FSL data';
b0 = int16(round(b0_img));
anat.mmPerVox = mmAnat;

origin = bb(1,[1,2,3])-mmDt./2;
xformToAnat = [diag(mmDt./mmAnat) [0 0 0]'; [0 0 0 1]];
xformToAcPc = [diag(mmDt) origin'; [0 0 0 1]]; %swapXY*[diag(mm) origin'; [0 0 0 1]];
anat.xformToAcPc = [diag(mmAnat) origin'; [0 0 0 1]];
% rp = t1.talairach.refPoints;
% % Why swap coords like this? Well, the real reason has to do with the
% % history of ComputeTalairach. We could figure this out in a more general
% % way using t1.talairach.refPoints.mat, which tells us how the coords were
% % transformed in ComputeTalairach. In the end, the following reordering
% % works for our data, since the pre-processing is consistent.
% mm = t1.cannonical_mmPerVox([2 3 1]);
anat.talScale.notes = ['Scale factors to go from subject mm to Talairach mm.' ...
                       'Eg. talCoord = anat.talScale.sac * imgCoord.' ...
                       'The scales are (in order) superior, inferior, left, right ' ...
                       'and anterior of AC, ac-to-pc and posterior of pc.'];
% anat.talScale.sac = 72./sqrt(sum(((rp.acXYZ-rp.sacXYZ).*mm).^2));
% anat.talScale.iac = 42./sqrt(sum(((rp.acXYZ-rp.iacXYZ).*mm).^2));
% anat.talScale.lac = 62./sqrt(sum(((rp.acXYZ-rp.lacXYZ).*mm).^2));
% anat.talScale.rac = 62./sqrt(sum(((rp.acXYZ-rp.racXYZ).*mm).^2));
% anat.talScale.aac = 68./sqrt(sum(((rp.acXYZ-rp.aacXYZ).*mm).^2));
% anat.talScale.acpc = 24./sqrt(sum(((rp.acXYZ-rp.pcXYZ).*mm).^2));
% % The PPC is referenced to the PC. It is at Talairach (0,-102,0) and the PC
% % is at (0,-24,0), so it is 78 mm beyond the PC.
% anat.talScale.ppc = 78./sqrt(sum(((rp.pcXYZ-rp.ppcXYZ).*mm).^2));
anat.talScale.sac = 1.0;
anat.talScale.iac = 1.0;
anat.talScale.lac = 1.0;
anat.talScale.rac = 1.0;
anat.talScale.aac = 1.0;
anat.talScale.acpc = 1.0;
anat.talScale.ppc = 1.0;

disp(['Saving to ' outPathName '...']);
l = license('inuse'); h = hostid;
created = ['Created at ' datestr(now,31) ' by ' l(1).user ' on ' h{1} '.'];
save(outPathName, 'dt6', 'mmPerVox', 'notes', 'xformToAnat', 'xformToAcPc', 'b0', 'anat', 'created');
if(nargout==0)
    clear dt6;
end
return;

function showFigure(fig, t1, b0, bb, slice, figName)
if(~exist('figName','var')) figName = 'Interpolated slices'; end
% Get X,Y and Z (L-R, A-P, S-I) slices from T1 and b0 volumes
[t1Xsl] = dtiGetSlice(t1.acpcXform,t1.data,3,slice(3),bb);
[t1Ysl] = dtiGetSlice(t1.acpcXform,t1.data,2,slice(2),bb);
[t1Zsl] = dtiGetSlice(t1.acpcXform,t1.data,1,slice(1),bb);
[b0Xsl] = dtiGetSlice(b0.acpcXform,b0.data,3,slice(3),bb);
[b0Ysl] = dtiGetSlice(b0.acpcXform,b0.data,2,slice(2),bb);
[b0Zsl] = dtiGetSlice(b0.acpcXform,b0.data,1,slice(1),bb);
% Max values for image scaling
t1mv = max([t1Xsl(:); t1Ysl(:); t1Zsl(:)])+0.000001;
b0mv = max([b0Xsl(:); b0Ysl(:); b0Zsl(:)])+0.000001;
% Create XxYx3 RGB images for each of the axis slices. The green and
% blue channels are from the T1, the red channel is an average of T1
% and b=0.
Xsl(:,:,1) = t1Xsl./t1mv.*.5 + b0Xsl./b0mv.*.5;
Xsl(:,:,2) = t1Xsl./t1mv.*.5; Xsl(:,:,3) = t1Xsl./t1mv.*.5;
Ysl(:,:,1) = t1Ysl./t1mv.*.5 + b0Ysl./b0mv.*.5;
Ysl(:,:,2) = t1Ysl./t1mv.*.5; Ysl(:,:,3) = t1Ysl./t1mv.*.5;
Zsl(:,:,1) = t1Zsl./t1mv.*.5 + b0Zsl./b0mv.*.5;
Zsl(:,:,2) = t1Zsl./t1mv.*.5; Zsl(:,:,3) = t1Zsl./t1mv.*.5;

% Show T1 slices
figure(fig); set(fig, 'NumberTitle', 'off', 'Name', figName);
figure(fig); subplot(3,3,1); imagesc(bb(:,1), bb(:,2), t1Xsl);
colormap(gray); axis equal tight xy;
figure(fig); subplot(3,3,2); imagesc(bb(:,3), bb(:,1), t1Ysl);
colormap(gray); axis equal tight xy;
figure(fig); subplot(3,3,3); imagesc(bb(:,3), bb(:,2), t1Zsl);
colormap(gray); axis equal tight xy;
axis equal tight;

% Show b=0 slices
figure(fig); subplot(3,3,4); imagesc(bb(:,1), bb(:,2), b0Xsl);
colormap(gray); axis equal tight xy;
figure(fig); subplot(3,3,5); imagesc(bb(:,3), bb(:,1), b0Ysl);
colormap(gray); axis equal tight xy;
figure(fig); subplot(3,3,6); imagesc(bb(:,3), bb(:,2), b0Zsl);
colormap(gray); axis equal tight xy;
axis equal tight;

% Show combined slices
figure(fig); subplot(3,3,7); imagesc(bb(:,1), bb(:,2), Xsl);
axis equal tight xy;
figure(fig); subplot(3,3,8); imagesc(bb(:,3), bb(:,1), Ysl);
axis equal tight xy;
figure(fig); subplot(3,3,9); imagesc(bb(:,3), bb(:,2), Zsl);
axis equal tight xy;
axis equal tight;

return;


function params = ReadParams(filename)

params = struct;
fid = fopen(filename,'r');
if fid < 0,
  error('Could not open parameter file %s for reading',filename);
end
while true,
  s = fgetl(fid);

  % end of file
  if ~ischar(s), break; end

  % comments
  if isempty(s) || ~isempty(regexp(s,'^\s*$','once')) || ...
        ~isempty(regexp(s,'^\s*#','once')),
    continue;
  end

  % split at first ,
  m = regexp(s,',','split','once');
  try
    name = m{1};
    if isempty(m{2}),
      val = {};
    else
      valcell = regexp(m{2},',','split');
      val = str2double(valcell);
      if any(isnan(val)),
        if numel(valcell) == 1,
          val = valcell{1};
        else
          val = valcell;
        end
      end
    end
    params.(name) = val;
  catch ME,
    warning('Unable to parse parameter line\n%s\nof %s:\n',s, ...
            filename,getReport(ME));
    continue;
  end

end

fclose(fid);


function title = p00_title ( problem )

%*****************************************************************************80
%
%% P00_TITLE returns a title for any problem.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer PROBLEM, the number of the problem.
%
%    Output, string TITLE, a title for the problem.
%
  if ( problem == 1 )
    title = p01_title ( );
  elseif ( problem == 2 )
    title = p02_title ( );
  elseif ( problem == 3 )
    title = p03_title ( );
  elseif ( problem == 4 )
    title = p04_title ( );
  elseif ( problem == 5 )
    title = p05_title ( );
  elseif ( problem == 6 )
    title = p06_title ( );
  elseif ( problem == 7 )
    title = p07_title ( );
  elseif ( problem == 8 )
    title = p08_title ( );
  elseif ( problem == 9 )
    title = p09_title ( );
  elseif ( problem == 10 )
    title = p10_title ( );
  elseif ( problem == 11 )
    title = p11_title ( );
  elseif ( problem == 12 )
    title = p12_title ( );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P00_TITLE - Fatal error!\n' );
    fprintf ( 1, '  Illegal value of PROBLEM =  %d\n', problem );
    error ( 'P00_TITLE - Fatal error!' );
  end

  return
end


function [ figformat ] = savefigure_pdf( name,varargin )

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Filippo Ferroni, 6/1/2015
% Revised, 2/15/2017
% Revised, 3/21/2018

% SAVEFIGURE_PDF: this function saves figures in .pdf format
% name: Name of the figure, example: 'figure1'
% type: Format of the figure, example: 'fig','espc'
% If no input is provided, figure saved twice with fig and espc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

set(gcf,'Units','Inches');
pos = get(gcf,'Position');
set(gcf,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)])
print(gcf,name,'-dpdf','-r0');
figformat=1;
end


clear all;
fprintf('Compiling perform_arithmetic_coding_mex and perform_arithmetic_coding_escape ... ');

% compile mex files
mex mex/perform_arithmetic_coding_mex.cpp mex/ac.cpp
mex mex/perform_arithmetic_coding_escape.cpp mex/coder/Arith.cpp mex/coder/BitIO.cpp mex/coder/IntCoding.cpp mex/coder/coder.cpp mex/coder/entropy.cpp mex/coder/global.cpp mex/coder/iHisto.cpp
mex mex/perform_arithmetic_coding_fixed.cpp mex/nr/arcmak.cpp mex/nr/arcode.cpp mex/nr/arcsum.cpp mex/nr/nrutil.cpp

disp('done.');


function substituteDefaultPropNamesWithCustomNamesInDepVarListbox(hDepVarListbox, propNames)
    vars = get(hDepVarListbox,'String');
%     propNames = maData.spacecraft.propellant.names;
    defaultNames = {'Liquid Fuel/Ox Mass','Monopropellant Mass','Xenon Mass'};
    propNames = sort(propNames);

    for(i=1:length(vars)) %#ok<*NO4LP>
        for(j=1:length(defaultNames))
            vars{i} = strrep(vars{i}, defaultNames{j}, [propNames{j}, ' Mass']);
        end
    end
    set(hDepVarListbox,'String',vars);
end


if( ishandle(UCP_struct.fig_hdl) )
    %classifier arguments
    aux_str = get(UCP_struct.recording_name, 'String');

    %Check if reprocessing is needed
    if( ~strcmpi(recording_name, aux_str) )
        bRecordingChanged = true;
    end
    recording_name = aux_str;

    recording_format = cKnownFormats{get(UCP_struct.recording_fmt, 'Value')};
    tmp_path = get(UCP_struct.tmp_path, 'String');
    op_mode = cKnownModesOfOperation{get(UCP_struct.op_mode, 'Value')};

    %Labeling options
    aux_str = cellstr(get(UCP_struct.labelings, 'String'));
    aux_val = get(UCP_struct.labelings, 'value');

    %Check if reprocessing is needed
    if( ~strcmpi(class_labeling, aux_str{aux_val}) )
        bLabelingChanged = true;
    end
    class_labeling = aux_str{aux_val};

    aux_str = cellstr(get(UCP_struct.class_filter, 'string'));
    aux_val = get(UCP_struct.class_filter, 'value');

    class_filter = char(aux_str(aux_val));

    %clustering options
    CantClusters = get(UCP_struct.CantClusters, 'Value');
    iter_times = get(UCP_struct.iter_times, 'Value');
    cluster_presence = get(UCP_struct.cluster_presence, 'Value');

    %User interface options
    CantSamplesClose = str2double(get(UCP_struct.CantSamplesClose, 'String'));
    CantSamplesFar = str2double(get(UCP_struct.CantSamplesFar, 'String'));
end


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

% Last Modified by GUIDE v2.5 07-Apr-2012 12:55:04

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

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = myloadnii3_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 gg gc;

h=guidata(gcbo);
% set(h.message_text,'String','');  % Clear Messages
gg=gg+2;
h.image_filename=1;
h.image_pathname=1;
[filename, pathname] = uigetfile({'*.nii'},'Pick a file'); % Load Image file and path names
    if filename~=0
        gg=1;
        h.gg=1;
        h.image_filename=filename;  % Image file name
        h.image_pathname=pathname;  % Image path name
%         set(h.Showaxes,'visible','off');
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
        image_1=load_untouch_nii([pathname filename]); % Load Image
%         image_1=load_nii([pathname filename]); % Load Image
        imshow(image_1.img(:,:,10),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);
    end

% --- 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)
h=guidata(gcbo);
image_1 = h.image_1;
slice_no = str2num(get(h.edit1,'String'))+1;
set(h.edit1,'String',num2str(slice_no));
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
        imshow(image_1.img(:,:,slice_no),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);

% --- 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)
h=guidata(gcbo);
image_1 = h.image_1;
slice_no = str2num(get(h.edit1,'String'));
slice_no = slice_no - 1 ;
set(h.edit1,'String',num2str(slice_no));
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
        imshow(image_1.img(:,:,slice_no),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);

% --- 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)

h=guidata(gcbo);
image_1 = h.image_1;
slice_no = str2num(get(h.edit1,'String'));
% slices = h.slices;
figure,imshow(image_1.img(:,:,slice_no),[])

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

% --- 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

% --- 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)
h=guidata(gcbo);
image_1 = h.image_1;
% image_2 = image_1.img;
for i = 1:size(image_1.img,3)
    image_1.img(:,:,i) = imrotate(image_1.img(:,:,i),90);
end
    h.image_1.img = image_1.img;
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
slice_no = str2num(get(h.edit1,'String'));
        imshow(image_1.img(:,:,slice_no),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);


function lipidMask = op_CSICreateLipidMask(MRSIStruct)
    checkArguments(MRSIStruct);
    dimensionIndexes = checkDimensions(MRSIStruct);

end

function checkArguments(MRSIStruct)
    checkSpatialFT(MRSIStuct);
    checkSpectralFT(MRSIStuct);
end

function [dimensionIndexs] = checkDimensions(MRSIStruct)
    dataSize = getSize(MRSIStruct);
    dims = getDimension(MRSIStruct);

end


function res = conditions(this, varargin)
% Method for getting condition labels, over trials
% FORMAT res = conditions(this, ind, conditionlabels)
% _______________________________________________________________________
% Copyright (C) 2008-2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: conditions.m 5025 2012-10-31 14:44:13Z vladimir $

res = getset(this, 'trials', 'label', varargin{:});

if nargin == 1 && ~iscell(res)
    res = {res};
end


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

% Copyright 2002-2003 The MathWorks, Inc.

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

% Last Modified by GUIDE v2.5 07-Feb-2007 22:44:47

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

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

handles.folder=[pwd '/Visual_Data/'];
d = dir([handles.folder '*.mat']);
handles.datalist=char(d.name);

if isempty(handles.datalist)==1
    set(handles.select_data,'String','Visual_Data - Folder is Empty')
else
    set(handles.select_data,'String',handles.datalist)
end

handles.cbar=0;
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = Visualization_4d_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 rotate.
function rotate_Callback(hObject, eventdata, handles)
% hObject    handle to rotate (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 rotate

handles=guidata(gcbo);

if get(hObject,'Value')==get(hObject,'Max')
    rotate3d on
else
    rotate3d off
end

guidata(gcbo,handles)

% --- Executes on button press in boundary_slices.
function boundary_slices_Callback(hObject, eventdata, handles)
% hObject    handle to boundary_slices (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 boundary_slices
handles=guidata(gcbo);

if get(hObject,'Value')==get(hObject,'Max')
    set(handles.boundary,'Visible','on')
else
    set(handles.boundary,'Visible','off')
end

guidata(gcbo,handles)

% --- Executes on button press in grid_on_slice.
function grid_on_slice_Callback(hObject, eventdata, handles)
% hObject    handle to grid_on_slice (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 grid_on_slice

handles=guidata(gcbo);

if get(hObject,'Value')==get(hObject,'Max')
    set(handles.boundary,'EdgeColor','k')
    set(handles.sliceplane_x,'EdgeColor','k')
    set(handles.sliceplane_y,'EdgeColor','k')
    set(handles.sliceplane_z,'EdgeColor','k')

else
    set(handles.boundary,'EdgeColor','none')
    set(handles.sliceplane_x,'EdgeColor','none')
    set(handles.sliceplane_y,'EdgeColor','none')
    set(handles.sliceplane_z,'EdgeColor','none')
end

guidata(gcbo,handles)

% --- Executes on button press in grid_on.
function grid_on_Callback(hObject, eventdata, handles)
% hObject    handle to grid_on (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 grid_on

handles=guidata(gcbo);

if get(hObject,'Value')==get(hObject,'Max')
    grid on
else
    grid off
end

guidata(gcbo,handles)

% --- Executes on slider movement.
function x_slider_Callback(hObject, eventdata, handles)
% hObject    handle to x_slider (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

handles=guidata(gcbo);

i=get(hObject,'Value');

axes(handles.axes1)
delete(handles.sliceplane_x)
handles.sliceplane_x=slice(handles.X,handles.Y,handles.Z,handles.V,i,[],[]);

if get(handles.grid_on_slice,'Value')==0

    delete(handles.sliceplane_x_boundary)
    handles.sliceplane_x_boundary=plot3([i i i i i],[handles.ymin handles.ymax handles.ymax handles.ymin handles.ymin],...
        [handles.zmin handles.zmin handles.zmax handles.zmax handles.zmin],'k');
end

set(handles.sliceplane_x,'FaceColor','interp')

% set(handles.sliceplane_x,'Visible','off')
% set(handles.sliceplane_x(i),'Visible','on')

if get(handles.grid_on_slice,'Value')==get(handles.grid_on_slice,'Min')
    set(handles.sliceplane_x,'EdgeColor','none')
end
set(handles.sliceplane_x,'Visible','on')

set(handles.x_slice,'Value',1,'Enable','on')

guidata(gcbo,handles)

% --- Executes on slider movement.
function y_slider_Callback(hObject, eventdata, handles)
% hObject    handle to y_slider (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles=guidata(gcbo);

i=get(hObject,'Value');

axes(handles.axes1)
delete(handles.sliceplane_y)
handles.sliceplane_y=slice(handles.X,handles.Y,handles.Z,handles.V,[],i,[]);

if get(handles.grid_on_slice,'Value')==0

    delete(handles.sliceplane_y_boundary)
    handles.sliceplane_y_boundary=plot3([handles.xmin handles.xmax handles.xmax handles.xmin handles.xmin ],[i i i i i],...
        [handles.zmin handles.zmin handles.zmax handles.zmax handles.zmin],'k');
end

set(handles.sliceplane_y,'FaceColor','interp')

if get(handles.grid_on_slice,'Value')==get(handles.grid_on_slice,'Min')
    set(handles.sliceplane_y,'EdgeColor','none')
end
set(handles.sliceplane_y,'Visible','on')
set(handles.y_slice,'Value',1,'Enable','on')
guidata(gcbo,handles)

% --- Executes on slider movement.
function z_slider_Callback(hObject, eventdata, handles)
% hObject    handle to wf (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles=guidata(gcbo);

i=get(hObject,'Value');
axes(handles.axes1)
delete(handles.sliceplane_z)
handles.sliceplane_z=slice(handles.X,handles.Y,handles.Z,handles.V,[],[],i);

if get(handles.grid_on_slice,'Value')==0
    delete(handles.sliceplane_z_boundary)
    handles.sliceplane_z_boundary=plot3([handles.xmin handles.xmax handles.xmax handles.xmin handles.xmin ],...
        [handles.ymin handles.ymin handles.ymax handles.ymax handles.ymin],[i i i i i],'k');
end

set(handles.sliceplane_z,'FaceColor','interp')

if get(handles.grid_on_slice,'Value')==get(handles.grid_on_slice,'Min')
    set(handles.sliceplane_z,'EdgeColor','none')
end

set(handles.sliceplane_z,'Visible','on')
set(handles.z_slice,'Value',1,'Enable','on')

guidata(gcbo,handles)

% --- Executes on button press in x_slice.
function x_slice_Callback(hObject, eventdata, handles)
% hObject    handle to x_slice (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 x_slice
handles=guidata(gcbo);

if get(hObject,'Value')==get(hObject,'Max')
    set(handles.sliceplane_x,'Visible','on')
    if get(handles.grid_on_slice,'Value')==0
        set(handles.sliceplane_x_boundary,'Visible','on')
    end
else
    set(handles.sliceplane_x,'Visible','off')
    set(handles.sliceplane_x_boundary,'Visible','off')
end

guidata(gcbo,handles)

% --- Executes on button press in y_slice.
function y_slice_Callback(hObject, eventdata, handles)
% hObject    handle to y_slice (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 y_slice
handles=guidata(gcbo);

if get(hObject,'Value')==get(hObject,'Max')
    set(handles.sliceplane_y,'Visible','on')
    if get(handles.grid_on_slice,'Value')==0
        set(handles.sliceplane_y_boundary,'Visible','on')
    end
else
    set(handles.sliceplane_y,'Visible','off')
    set(handles.sliceplane_y_boundary,'Visible','off')
end

guidata(gcbo,handles)

% --- Executes on button press in z_slice.
function z_slice_Callback(hObject, eventdata, handles)
% hObject    handle to z_slice (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 z_slice
handles=guidata(gcbo);

if get(hObject,'Value')==get(hObject,'Max')
    set(handles.sliceplane_z,'Visible','on')
    if get(handles.grid_on_slice,'Value')==0
        set(handles.sliceplane_z_boundary,'Visible','on')
    end

else
    set(handles.sliceplane_z,'Visible','off')
    set(handles.sliceplane_z_boundary,'Visible','off')
end

guidata(gcbo,handles)

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

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

handles=guidata(gcbo);

selected=get(hObject,'Value');
aaa=handles.datalist(selected,:);

eval(['load Visual_Data/' aaa])
cla

set([handles.x_slice handles.z_slice],'Value',0)
set(handles.y_slice,'Value',1)

set(handles.boundary_slices,'Value',0)
handles.X=X;
handles.Y=Y;
handles.Z=Z;
handles.V=V;

xmin=(min(min(min(X))));
ymin=(min(min(min(Y))));
zmin=(min(min(min(Z))));

xmax=(max(max(max(X))));
ymax=(max(max(max(Y))));
zmax=(max(max(max(Z))));

xmid=(xmax+xmin)/2;
ymid=(ymax+ymin)/2;
zmid=(zmax+zmin)/2;

handles.xmin=xmin;
handles.ymin=ymin;
handles.zmin=zmin;

handles.xmax=xmax;
handles.ymax=ymax;
handles.zmax=zmax;

alengthx=xmax-xmin;
alengthy=ymax-ymin;
alengthz=zmax-zmin;

xslice=xmin;
yslice=ymin;
zslice=zmin;

cen=[0.5*(xmax+xmin),0.5*(ymax+ymin),0.5*(zmax+zmin)];

[xx,yy,zz]=sphere(10);

xx=xx*(xmax-xmin)/2;
yy=yy*(ymax-ymin)/2;
zz=zz*(zmax-zmin)/2;

xx=xx+cen(1);
yy=yy+cen(2);
zz=zz+cen(3);

axes(handles.axes1)

outer_sphere=mesh(xx,yy,zz);
set(outer_sphere,'Visible','off')
hold on

set(handles.x_slider,'Min',xmin,'Max',xmax,'Value',xmid)%,'SliderStep',[0.01*alengthx 0.1*alengthx])
set(handles.y_slider,'Min',ymin,'Max',ymax,'Value',ymid)%,'SliderStep',[0.01*alengthy 0.1*alengthy])
set(handles.z_slider,'Min',zmin,'Max',zmax,'Value',zmid)%,'SliderStep',[0.01*alengthz 0.1*alengthz])

% qqq
% return

handles.boundary=slice(X,Y,Z,V,xslice,yslice,zslice);
set(handles.boundary,'FaceColor','interp')

if get(handles.boundary_slices,'Value')==0
    set(handles.boundary,'Visible','off')
else
    set(handles.boundary,'Visible','on')
end

hold on

if get(handles.color_bar,'Value')==1

    if handles.cbar==0
        handles.cbar=colorbar('Location','EastOutside');
    else
        delete(handles.cbar)
        handles.cbar=colorbar('Location','EastOutside');
    end
end

box on
axis tight
view(125,20)

% handles.sliceplane_x=slice(X,Y,Z,V,(xmax+xmin)/2,[],[]);
handles.sliceplane_x=slice(X,Y,Z,V,xmid,[],[]);
% handles.sliceplane_x_boundary=plot3([0 0 0 0 0],[ymin ymax ymax ymin ymin],[zmin zmin zmax zmax zmin],'k');
handles.sliceplane_x_boundary=plot3([xmid xmid xmid xmid xmid],[ymin ymax ymax ymin ymin],[zmin zmin zmax zmax zmin],'k');

% handles.sliceplane_y=slice(X,Y,Z,V,[],(ymax+ymin)/2,[]);
handles.sliceplane_y=slice(X,Y,Z,V,[],ymid,[]);
handles.sliceplane_y_boundary=plot3([xmin xmax xmax xmin xmin ],[ymid ymid ymid ymid ymid],[zmin zmin zmax zmax zmin],'k');

% handles.sliceplane_z=slice(X,Y,Z,V,[],[],(zmax+zmin)/2);
handles.sliceplane_z=slice(X,Y,Z,V,[],[],zmid);
handles.sliceplane_z_boundary=plot3([xmin xmax xmax xmin xmin ],[ymin ymin ymax ymax ymin],[zmid zmid zmid zmid zmid],'k');

set([handles.sliceplane_z handles.sliceplane_y handles.sliceplane_z],'FaceColor','interp')
% qqq

if get(handles.grid_on_slice,'Value')==1
    set([ handles.sliceplane_x_boundary handles.sliceplane_y_boundary handles.sliceplane_z_boundary ],'Visible','off')
else
    set(handles.boundary,'EdgeColor','none')
    set([ handles.sliceplane_x handles.sliceplane_y handles.sliceplane_z],'Edgecolor','none')
end

if get(handles.x_slice,'Value')==0
    set(handles.sliceplane_x_boundary ,'Visible','off')
    set(handles.sliceplane_x,'Visible','off')
end

if get(handles.y_slice,'Value')==0
    set(handles.sliceplane_y_boundary ,'Visible','off')
    set(handles.sliceplane_y,'Visible','off')
end

if get(handles.z_slice,'Value')==0
    set(handles.sliceplane_z_boundary ,'Visible','off')
    set(handles.sliceplane_z,'Visible','off')
end

camlookat(outer_sphere)

set([handles.boundary_slices handles.grid_on_slice handles.grid_on handles.x_slider handles.y_slider, ...
    handles.z_slider,handles.capture_image, handles.rotate  handles.x_slice handles.y_slice handles.z_slice, ...
    handles.color_bar, handles.x_label_txt, handles.y_label_txt,handles.z_label_txt,handles.Plot_title],'Enable','on')

set(handles.axes1,'PlotBoxAspectRatio',[1 1 1]);

ttt=title('Variation of \Omega with \alpha , \beta & \gamma');
set(ttt,'FontSize',12)

xlabel('\alpha')
ylabel('\beta')
zlabel('\gamma')

guidata(gcbo,handles)

function x_label_txt_Callback(hObject, eventdata, handles)
% hObject    handle to x_label_txt (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 x_label_txt as text
%        str2double(get(hObject,'String')) returns contents of x_label_txt as a double

handles=guidata(gcbo);

x_label=get(hObject,'String');
xl=xlabel(x_label);

guidata(gcbo,handles)

function z_label_txt_Callback(hObject, eventdata, handles)
% hObject    handle to z_label_txt (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 z_label_txt as text
%        str2double(get(hObject,'String')) returns contents of z_label_txt as a double

handles=guidata(gcbo);

z_label=get(hObject,'String');
% set(handles.z_text,'String',z_label)
zl=zlabel(z_label);

guidata(gcbo,handles)

function y_label_txt_Callback(hObject, eventdata, handles)
% hObject    handle to y_label_txt (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 y_label_txt as text
%        str2double(get(hObject,'String')) returns contents of y_label_txt as a double

handles=guidata(gcbo);

y_label=get(hObject,'String');
% set(handles.y_text,'String',y_label)
yl=ylabel(y_label);

guidata(gcbo,handles)

function Plot_title_Callback(hObject, eventdata, handles)
% hObject    handle to Plot_title (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 Plot_title as text
%        str2double(get(hObject,'String')) returns contents of Plot_title
%        as a double

handles=guidata(gcbo);

plot_title=get(hObject,'String');
% set(handles.Plot_title_static_txt,'String',plot_title)
ttt=title(plot_title)
set(ttt,'FontSize',12)

guidata(gcbo,handles)

% --- Executes on button press in color_bar.
function color_bar_Callback(hObject, eventdata, handles)
% hObject    handle to color_bar (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 color_bar

handles=guidata(gcbo);

if get(handles.color_bar,'Value')==1

    if handles.cbar==0
        handles.cbar=colorbar('Location','EastOutside');
    else
        delete(handles.cbar)
        handles.cbar=colorbar('Location','EastOutside');
    end
elseif handles.cbar~=0
    delete(handles.cbar)
    handles.cbar=0;
end

guidata(gcbo,handles)

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

handles=guidata(gcbo);
[file,path] = uiputfile('4D_Plot.jpg',['Capture as Image'])
filename=[path,file]

if file~=0
    set([ handles.select_data, handles.color_bar, handles.boundary_slices, handles.grid_on_slice,...
        handles.set_label_txt, handles.grid_on, handles.x_slice, handles.y_slice, handles.z_slice,...
        handles.rotate, handles.capture_image, handles.x_label_txt, handles.y_label_txt, handles.z_label_txt,...
        handles.Plot_title, handles.x_slider, handles.y_slider, handles.z_slider, handles.text1,...
        handles.set_title_txt, handles.text2, handles.text3,handles.uipanel1],'Visible','off')

    saveas(gca,filename)

    set([ handles.select_data, handles.color_bar, handles.boundary_slices, handles.grid_on_slice,...
        handles.set_label_txt,handles.grid_on, handles.x_slice, handles.y_slice, handles.z_slice,...
        handles.rotate, handles.capture_image, handles.x_label_txt, handles.y_label_txt, handles.z_label_txt,...
        handles.Plot_title, handles.x_slider, handles.y_slider, handles.z_slider, handles.text1,...
        handles.set_title_txt, handles.text2, handles.text3,handles.uipanel1],'Visible','on')
end

guidata(gcbo,handles)

function exit_Callback(hObject, eventdata, handles)
% hObject    handle to file_exit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles = guidata(gcbo);
delete(handles.figure1);
% clc
a=0;
save Extra.dat a
delete('Extra.dat')
clear
closereq
load alltools
msg=['                                                                    ';...
     '     j.divahar@yahoo.com                                            '];

button = msgbox(msg,'Thank you For Trying !','custom',Tvanakam,Tcolormap);


clear all; close all; clc;
%% TO PERFORM SPEECH ENHANCEMENT:
%
%% 1. Place the noisy speech files in 'set/test_noisy_speech'.
%
%% 2. Run this script.
%
%% 3. The enhanced speech outputs will be in 'out'.
%
%% Note: the script will finish with 'Inference complete.'.
%

if isunix
	matlab_bin = [matlabroot, '/bin/glnxa64'];
	command = ['sudo mv ', matlab_bin, '/libexpat.so.1 ', matlab_bin, '/libexpat.so.1.NOFIND'];
	system(command);
end

gpu_flag = lower(input('Use a GPU? (y/n):', 's'));
if ismember(gpu_flag, {'y', 'yes'})
    gpu_flag = true;
elseif ismember(gpu_flag, {'n', 'no'})
    gpu_flag = false;
else
    error('Please enter either ''y'' or ''n''.')
end

if gpu_flag
    system('source ~/venv/DeepXi/bin/activate; ./run.sh VER=resnet-1.1n INFER=1 GAIN=mmse-lsa');
else
    system('source ~/venv/DeepXi/bin/activate; ./run.sh VER=resnet-1.1n INFER=1 GAIN=mmse-lsa GPU=9999');
end


matlabbatch{1}.spm.tools.physio.save_dir = {'physio_out'};
matlabbatch{1}.spm.tools.physio.log_files.vendor = 'Siemens_HCP';
matlabbatch{1}.spm.tools.physio.log_files.cardiac = {'tfMRI_MOTOR_LR_Physio_log.txt'};
matlabbatch{1}.spm.tools.physio.log_files.respiration = {'tfMRI_MOTOR_LR_Physio_log.txt'};
matlabbatch{1}.spm.tools.physio.log_files.scan_timing = {''};
matlabbatch{1}.spm.tools.physio.log_files.sampling_interval = [];
matlabbatch{1}.spm.tools.physio.log_files.relative_start_acquisition = 0;
matlabbatch{1}.spm.tools.physio.log_files.align_scan = 'last';
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.Nslices = 91;
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.NslicesPerBeat = [];
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.TR = 0.72;
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.Ndummies = 0;
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.Nscans = 284;
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.onset_slice = 46;
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.time_slice_to_slice = [];
matlabbatch{1}.spm.tools.physio.scan_timing.sqpar.Nprep = [];
matlabbatch{1}.spm.tools.physio.scan_timing.sync.nominal = struct([]);
matlabbatch{1}.spm.tools.physio.preproc.cardiac.modality = 'PPU';
matlabbatch{1}.spm.tools.physio.preproc.cardiac.filter.no = struct([]);
matlabbatch{1}.spm.tools.physio.preproc.cardiac.initial_cpulse_select.auto_matched.min = 0.4;
matlabbatch{1}.spm.tools.physio.preproc.cardiac.initial_cpulse_select.auto_matched.file = 'initial_cpulse_kRpeakfile.mat';
matlabbatch{1}.spm.tools.physio.preproc.cardiac.initial_cpulse_select.auto_matched.max_heart_rate_bpm = 90;
matlabbatch{1}.spm.tools.physio.preproc.cardiac.posthoc_cpulse_select.off = struct([]);
matlabbatch{1}.spm.tools.physio.preproc.respiratory.filter.passband = [0.01 2];
matlabbatch{1}.spm.tools.physio.preproc.respiratory.despike = false;
matlabbatch{1}.spm.tools.physio.model.output_multiple_regressors = 'multiple_regressors.txt';
matlabbatch{1}.spm.tools.physio.model.output_physio = 'physio.mat';
matlabbatch{1}.spm.tools.physio.model.orthogonalise = 'none';
matlabbatch{1}.spm.tools.physio.model.censor_unreliable_recording_intervals = false;
matlabbatch{1}.spm.tools.physio.model.retroicor.yes.order.c = 3;
matlabbatch{1}.spm.tools.physio.model.retroicor.yes.order.r = 4;
matlabbatch{1}.spm.tools.physio.model.retroicor.yes.order.cr = 1;
matlabbatch{1}.spm.tools.physio.model.rvt.no = struct([]);
matlabbatch{1}.spm.tools.physio.model.hrv.no = struct([]);
matlabbatch{1}.spm.tools.physio.model.noise_rois.no = struct([]);
matlabbatch{1}.spm.tools.physio.model.movement.no = struct([]);
matlabbatch{1}.spm.tools.physio.model.other.no = struct([]);
matlabbatch{1}.spm.tools.physio.verbose.level = 2;
matlabbatch{1}.spm.tools.physio.verbose.fig_output_file = '';
matlabbatch{1}.spm.tools.physio.verbose.use_tabs = false;


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

% Last Modified by GUIDE v2.5 01-Mar-2012 11:00:16

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

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

% Update handles structure
guidata(hObject, handles);

initialize_gui(hObject, handles, false);

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

% --- Outputs from this function are returned to the command line.
function varargout = ui_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 during object creation, after setting all properties.
function density_CreateFcn(hObject, eventdata, handles)
% hObject    handle to density (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 density_Callback(hObject, eventdata, handles)
% hObject    handle to density (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 density as text
%        str2double(get(hObject,'String')) returns contents of density as a double
density = str2double(get(hObject, 'String'));
if isnan(density)
    set(hObject, 'String', 0);
    errordlg('Input must be a number','Error');
end

% Save the new density value
handles.metricdata.density = density;
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function volume_CreateFcn(hObject, eventdata, handles)
% hObject    handle to volume (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 volume_Callback(hObject, eventdata, handles)
% hObject    handle to volume (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 volume as text
%        str2double(get(hObject,'String')) returns contents of volume as a double
volume = str2double(get(hObject, 'String'));
if isnan(volume)
    set(hObject, 'String', 0);
    errordlg('Input must be a number','Error');
end

% Save the new volume value
handles.metricdata.volume = volume;
guidata(hObject,handles)

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

mass = handles.metricdata.density * handles.metricdata.volume;
set(handles.mass, 'String', mass);

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

initialize_gui(gcbf, handles, true);

% --- Executes when selected object changed in unitgroup.
function unitgroup_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in unitgroup
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if (hObject == handles.english)
    set(handles.text4, 'String', 'lb/cu.in');
    set(handles.text5, 'String', 'cu.in');
    set(handles.text6, 'String', 'lb');
else
    set(handles.text4, 'String', 'kg/cu.m');
    set(handles.text5, 'String', 'cu.m');
    set(handles.text6, 'String', 'kg');
end

% --------------------------------------------------------------------
function initialize_gui(fig_handle, handles, isreset)
% If the metricdata field is present and the reset flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to reset the data.
if isfield(handles, 'metricdata') && ~isreset
    return;
end

handles.metricdata.density = 0;
handles.metricdata.volume  = 0;

set(handles.density, 'String', handles.metricdata.density);
set(handles.volume,  'String', handles.metricdata.volume);
set(handles.mass, 'String', 0);

set(handles.unitgroup, 'SelectedObject', handles.english);

set(handles.text4, 'String', 'lb/cu.in');
set(handles.text5, 'String', 'cu.in');
set(handles.text6, 'String', 'lb');

% Update handles structure
guidata(handles.figure1, handles);


function [varargout] = istable(varargin)

% ISTABLE is a drop-in replacement for the same function that was
% introduced in MATLAB R2013b.
%
% In all MATLAB versions prior to 2013b this function returns false.

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

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

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

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is where the actual replacement code starts
% function tf = istable(input)

tf = false;

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

varargout = {tf};


function model = assignSubSystems(model,gpraFile)
% Assigns each reaction a subsystem in the model structure
%
% USAGE:
%
%    model = assignSubSystems(model, gpraFile)
%
% INPUTS:
%    model:       COBRA model structure
%    gpraFile:    SimPheny GPRA file
%
% OUTPUT:
%    model:       COBRA model structure with subsystem assignment
%
% .. Author: - Markus Herrgard

gpraModel = parseSimPhenyGPRA(gpraFile);

[isInList,rxnInd] = ismember(model.rxns,gpraModel.rxns);

for i = 1:length(model.rxns)
    if (isInList(i))
        model.subSystems{i} = gpraModel.subSystems{rxnInd(i)};
    else
        model.subSystems{i} = 'Exchange';
    end
end

model.subSystems = model.subSystems';


function [bads] = fiff_read_bad_channels(fid,node,ch_rename)
%
% [bads] = fiff_read_bad_channels(fid,node[,ch_rename])
%
% Reas the bad channel list from a node if it exists
%
% fid       - The file id
% node      - The node of interes
% ch_rename - Short-to-long channel name mapping
%

%
%
%   Author : Matti Hamalainen, MGH Martinos Center
%   License : BSD 3-clause
%
%   Revision 1.5  2006/05/03 18:53:04  msh
%   Approaching Matlab 6.5 backward compatibility
%
%   Revision 1.4  2006/05/03 15:51:17  msh
%   Re-added fiff_read_bad_channels
%
%   Revision 1.2  2006/04/23 15:29:40  msh
%   Added MGH to the copyright
%
%   Revision 1.1  2006/04/12 17:09:28  msh
%   Added routines for reading noise-covariance matrices
%
%

me='MNE:fiff_read_bad_channels';

if nargin == 2
    ch_rename = {};
elseif nargin ~= 3
    error(me,'Incorrect number of arguments');
end

global FIFF;
if isempty(FIFF)
    FIFF = fiff_define_constants();
end

node = fiff_dir_tree_find(node,FIFF.FIFFB_MNE_BAD_CHANNELS);

bads = [];
if ~isempty(node)
    tag = find_tag(node,FIFF.FIFF_MNE_CH_NAME_LIST);
    if ~isempty(tag)
        bads = fiff_split_name_list(tag.data);
    end
end
bads = fiff_rename_list(bads, ch_rename);

return;

    function [tag] = find_tag(node,findkind)

        for p = 1:node.nent
            kind = node.dir(p).kind;
            pos  = node.dir(p).pos;
            if kind == findkind
                tag = fiff_read_tag(fid,pos);
                return;
            end
        end
        tag = [];
        return
    end

end


function saveSameSize(h, varargin)
%SAVESAMESIZE print/export figure h at same size as on screen.
%   SAVESAMESIZE will adjust printing/exporting related properties so the
%   figure (h) will print/export the same size as the onscreen display. It
%   will print/export the figure and then restore the changed properties to
%   the original values
%
%   saveSameSize accepts some optional parameter-value pairs. If used you must
%   specify BOTH the parameter name (e.g. 'format') AND the parameter value
%   (e.g. 'png'):
%       parameter      value/meaning
%       ----------     --------------------------------------
%        'format'      output format to generate.
%                      Must be one of the formats supported by the print command
%
%                      If not specified, jpeg is used as the default
%
%        'file'        path/name of output file to create
%
%                      If not specified, 'figure<N>.<ext>' will be used
%                      where  <N> is the figure handle and ext
%                             <ext> is the extension corresponding to the
%                                   output format chosen
%
%        'renderer'    Renderer to use when creating the output.
%                      Must be one renderers supported by MATLAB
%
%                      If not specified, the figure's current renderer will be used
%
%   Example usage:
%       save current figure to jpeg file named figure<n>.jpg using the
%       figure's current renderer
%           saveSameSize(gcf);
%
%       save current figure to png file named test.png using the
%       OpenGL renderer
%           saveSameSize(gcf, 'format', 'png', 'renderer', 'opengl',...
%                          'file', 'test.png');
%
% See also PRINT

%   Copyright 2007 The MathWorks, Inc.

if ishandle(h)
    setprops = {'PaperType', 'PaperSize', 'PaperUnits', 'PaperPosition', 'PaperPositionMode'};
    try
        settings = get(h, setprops);
    catch
        error('saveSameSize unable to get figure properties');
    end

    oldSettings = cell2struct(settings, setprops, 2); % to use when resetting values
    set(h, 'PaperPositionMode', 'auto');

    paramSettings = processArgs(h, varargin{:});
    if isstruct(paramSettings)
        try
            print(h, '-r0', ...
                 paramSettings.renderer, ...
                 paramSettings.device, ...
                 paramSettings.outfile);
        catch ex
            % print had a problem - restore settings and rethrow
            set(h, oldSettings);
            rethrow(ex);
        end
        set(h, oldSettings);
    end
else
    error('saveSameSize requires a handle to a figure');
end
end

% helper function to deal with parsing command line arguments
%   expecting   ..., 'format', ['jpeg', 'eps', 'png', ...]
%                    'file', 'pathToOutputFileToCreate'
%                    'renderer', 'opengl|painters|zbuffer'
function param_settings = processArgs(h, varargin)

    if mod(length(varargin),2) ~= 0
       error('saveSameSize:InvalidOptionalParameters', ...
             'saveSameSize optional parameters must be specified as parameter-value pairs');
    end
    %setup defaults
    param_settings.outfile = '';
    ext = 'jpg';
    param_settings.device = '-djpeg';
    param_settings.renderer = lower(['-' get(h, 'renderer')]);

    for i = 1 : 2 : length(varargin)-1
        param_arg = varargin{i};
        % caller specified output device to use
        if ischar(param_arg) && strcmpi(param_arg, 'format')
           val_arg = varargin{i+1};
           % remove '-d' if caller specified it
           if length(val_arg) >= 3 && strcmpi(val_arg(1:2),'-d')
               val_arg = val_arg(3:end);
           end
           % check device against list of supported devices
           [device, ext] = localIsGoodDevice(val_arg);
           param_settings.device = ['-d' device];
        end

        % caller specified output file to use
        if ischar(param_arg) && strcmpi(param_arg, 'file')
           val_arg = varargin{i+1};
           if ischar(val_arg)
    		  param_settings.outfile = val_arg;
           else
              error('saveSameSize:InvalidOutputFile', ...
                     'saveSameSize invalid output file specified');
           end
        end

        % caller specified renderer to use
        if ischar(param_arg) && strcmpi(param_arg, 'renderer')
           val_arg = varargin{i+1};
           if ischar(val_arg)
              if strcmpi(val_arg, 'OpenGL')
                 renderer = 'opengl';
              elseif strcmpi(val_arg, 'painters')
                 renderer = 'painters';
              elseif strcmpi(val_arg, 'zbuffer')
                 renderer = 'zbuffer';
              else
                 error('saveSameSize:InvalidRenderer', ...
                     'saveSameSize invalid renderer <%s> specified', val_arg);
              end
              param_settings.renderer = ['-' renderer];
           elseif isnumeric(val_arg)
               error('saveSameSize:InvalidRenderer', ...
                     'saveSameSize invalid renderer <%s> specified', num2str(val_arg));
           else
               error('saveSameSize:InvalidRenderer', ...
                     'saveSameSize invalid renderer specified');
           end
        end
    end
    if isempty(param_settings.outfile)
       param_settings.outfile = ['figure' num2str(h) '.' ext];
    end
end

% helper function to check specified device (dev) against the list of
% supported devices.
% Returns device/format string for the supported device and the extension
% that corresponds to output of that format.
function [device, ext] = localIsGoodDevice(dev)
  pj = printjob; %#ok
  device = '';
  [options, devices, extensions ] = printtables( pj ); %#ok
  devIndex = strmatch( dev, devices, 'exact' );
  if length(devIndex) == 1 % one exact match
     device = dev;
  elseif length(devIndex) > 1
     devIndex = strmatch( dev, devices);
     if length(devIndex) == 1 % one partial match
        device = devices{devIndex};
     end
  end
  if isempty(device)
    error('saveSameSize:InvalidFormat', ...
          'saveSameSize invalid format specified ');
  end
  ext = extensions{devIndex};
  if isempty(ext)
    error('saveSameSize:NotFileFormat', ...
          'saveSameSize format specified does not support exporting to a file ');
  end
end


function bool = is_array(x)
    % Check if x is regular dense array.
    bool = isa(x, 'double') || isa(x, 'single') || isa(x, 'gpuArray');
end


function f = previewfig(h,varargin)
    %PREVIEWFIG  Preview a figure to be exported using EXPORTFIG.
    %   F = PREVIEWFIG(H) creates a preview of H with the default
    %   EXPORTFIG options and returns the preview's figure handle in F.
    %   F = PREVIEWFIG(H,OPTIONS) creates a preview with OPTIONS as
    %   described in EXPORTFIG.
    %   PREVIEWFIG(...,PARAM1,VAL1,PARAM2,VAL2,...) creates a preview
    %   with the specified parameter-value pairs to H as described in
    %   EXPORTFIG.
    %
    %   See also EXPORTFIG, APPLYTOFIG, RESTOREFIG.

    %  Copyright 2000 Ben Hinkle
    %  Email bug reports and comments to bhinkle@mathworks.com

    filename = [tempname, '.png'];
    args = {'resolution',0,'format','png'};
    if nargin > 1
        exportfig(h, filename, varargin{:}, args{:});
    else
        exportfig(h, filename, args{:});
    end

    X = imread(filename,'png');
    height = size(X,1);
    width = size(X,2);
    delete(filename);
    f = figure_w_normalized_uicontrolunits( 'Name', 'Preview', ...
        'Menubar', 'none', ...
        'NumberTitle', 'off', ...
        'Visible', 'off');
    image(X);
    axis image;
    ax = findobj(f, 'type', 'axes');
    axesPos = [0 0 width height];
    set(ax, 'Units', 'pixels', ...
        'Position', axesPos, ...
        'Visible', 'off');
    figPos = get(f,'Position');
    rootSize = get(groot,'ScreenSize');
    figPos(3:4) = axesPos(3:4);
    if figPos(1) + figPos(3) > rootSize(3)
        figPos(1) = rootSize(3) - figPos(3) - 50;
    end
    if figPos(2) + figPos(4) > rootSize(4)
        figPos(2) = rootSize(4) - figPos(4) - 50;
    end
    set(f, 'Position',figPos, ...
        'Visible', 'on');


function model = VGG16_for_Fast_RCNN_VOC2007(model)
% VGG 16layers (only finetuned from conv3_1)

model.solver_def_file        = fullfile(pwd, 'models', 'fast_rcnn_prototxts', 'vgg_16layers_conv3_1', 'solver_30k40k.prototxt');
model.test_net_def_file      = fullfile(pwd, 'models', 'fast_rcnn_prototxts', 'vgg_16layers_conv3_1', 'test.prototxt');

model.net_file               = fullfile(pwd, 'models', 'pre_trained_models', 'vgg_16layers', 'vgg16.caffemodel');
model.mean_image             = fullfile(pwd, 'models', 'pre_trained_models', 'vgg_16layers', 'mean_image');

end


function EEG = hlp_importConnData(varargin)
% Convert/Import connectivity matrices and (optionally) source locations
% into SIFT data structures and store in an EEGLAB data structure
% This can be used to visualize, in SIFT, connectivity data computed
% using another toolbox, such as SPM, GCCA, or Fieldtrip.

% Author: Tim Mullen, 2012, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% 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, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

g= arg_define(varargin,...
    arg({'connDataStruct','ConnectivityDataStructure'},[],mandatory,'Connectivity data structure. This is a structure where each field ConnDataStruct.(<MethodName>) = [vars_to x vars_from x freqs x times] contains a 2D, 3D, or 4D connectivity matrix for a given MethodName. All matrices must be of equal size and first two dimensions must be equal size (num_vars_to==num_vars_from). If this describes an asymmetric (directed) graph, edges in the graph point from columns (vars_from) to rows (vars_to). If there is no frequency information, the 3rd dimension is a singleton (matrix is still 4-D), if there is no time information then the matrix is 3-dimensional (matlab always squeezes out trailing singleton dimensions). If there is neither frequency nor time information, matrix is 2D.'), ...
    arg({'winCenterTimes','WinCenterTimes'},[],[],'Time-stamps (sec). This is a vector of time-stamps for corresponding time-varying connectivity (winCenterTimes=[], if no time-varying connectivity)','shape','row'), ...
    arg({'erWinCenterTimes','EventRelatedWinCenterTimes'},[],[],'Event-related time-stamps (sec). This is a vector of "event-related" time-stamps for event-related analysis. Time t=0 is an event to which trials have been locked, t>0 is post-event and t<0 is pre-event. If empty (default), value is same as winCenterTimes.','shape','row'), ...
    arg({'freqs','Frequencies'},0,[],'Frequencies (Hz). This is a vector of frequencies for corresponding frequency-varying connectivity (freqs=0, if no frequency information)','shape','row'), ...
    arg({'winlen','SlidingWindowLength'},0,[],'Sliding Window Length (sec). This is the length of the sliding window (in sec) if you used a sliding-window analysis to get time-varying connectivity. Default is 0 (no sliding window used)'), ...
    arg({'variableNames','VariableNames','curComponentNames'},{},[],'Variable IDs. This is a cell array of ''user-friendly'' names for each variable -- e.g. anatomical names for each source, or channel names for each channel','type','cellstr','shape','row'), ...
    arg('MNI_XYZ',[],[],'MNI Coords (X,Y,Z) for each variable. An EEGLAB dipfit structure can also be provided. Otherwise, this is an optional matrix of size [num_vars x 3] where each column contains, respectively, X,Y,Z MNI coordinates for the variables (e.g. channels or sources). Subject-specific coordinates can also be provided, but then a subject-specific head model will need to be provided when rendering a brainmovie. This goes into the .posxyz field of a new EEGLAB dipfit structure','shape','matrix'), ...
    arg('EEG',[],[],'EEGLAB data structure. Optional EEGLAB data struct. SIFT data objects will be stored in here. If ommitted, an empty EEGLAB dataset will be created.') ...
    );

% Input checks and conversions
% -------------------------------------------------------------------------
fnames = fieldnames(g.connDataStruct);
if isempty(g.connDataStruct)
    error('Input argument ''ConnectivityDataStructure'' cannot be empty');
end

% get connectivity matrix dimensions
% and check that all connectivity matrices are of equal size
[numVars numVars numFreqs numTimes] = size(g.connDataStruct.(fnames{1}));
for k=2:length(fnames)
    if        ndims(g.connDataStruct.(fnames{k})) ~= ndims(g.connDataStruct.(fnames{1})) ...
       || any( size(g.connDataStruct.(fnames{k})) ~=  size(g.connDataStruct.(fnames{1})) )
        error('All connectivity matrices in ConnectivityDataStructure must be of equal size');
    end
end

% check time-stamp vectors
if isempty(g.winCenterTimes)
    g.winCenterTimes = 0;
end
if isempty(g.erWinCenterTimes)
    g.erWinCenterTimes = g.winCenterTimes;
end
if length(g.winCenterTimes)~=numTimes
    error('The number of time-stamps (length of ''WinCenterTimes'') does not agree with the corresponding dimension (dim 4) of the connectivity matrices');
end
if length(g.erWinCenterTimes)~=length(g.winCenterTimes)
    error('The number of event-related time-stamps (length of ''EventRelatedWinCenterTimes'') must equal the length of WinCenterTimes.');
end

% check frequency vector
if length(g.freqs)~=numFreqs
    error('The number of frequencies (length of ''Frequencies'') does not agree with the corresponding dimension (dim 3) of the connectivity matrices');
end

% check variable names
variableInds = 1:numVars;
if isempty(g.variableNames)
    g.variableNames = cellstr(num2str(variableInds'))';
elseif length(g.variableNames) ~= length(variableInds)
    error('The length of VariableNames must equal the number of variables');
end

% check MNI coords matrix
if ~isempty(g.MNI_XYZ) && ~isstruct(g.MNI_XYZ)
    if size(g.MNI_XYZ,1)~=numVars || size(g.MNI_XYZ,2) ~=3
        error('''MNI_XYZ'' must be either a dipfit structure or a matrix of size [num_vars x 3]');
    end
end

% Make Conn object
% -------------------------------------------------------------------------
Conn = struct(...
    'winCenterTimes'        , g.winCenterTimes     , ... % vector of time-stamps for corresponding time-varying connectivity (g.winCenterTimes=0, if no time-varying connectivity)
    'erWinCenterTimes'      , g.erWinCenterTimes   , ... % vector of "event-related" time-stamps for event-related analysis. Time t=0 is an event to which trials have been locked, t>0 is post-event and t<0 is pre-event. Otherwise, can be the same as g.winCenterTimes
    'freqs'                 , g.freqs                ... % vector of frequencies (Hz) for corresponding frequency-varying connectivity (g.freqs=0, if no frequency information)
    );
Conn = catstruct(Conn,g.connDataStruct);

% Make (abbreviated) model object
% -------------------------------------------------------------------------
MODEL = struct(...
    'winlen', 0 ...     % this is the only field you need from MODEL. It contains the length of the sliding window (in sec) if you used a sliding-window analysis to get time-varying connectivity. Otherwise, just set to 0
    );

% Make (abbreviated) SIFT data structure.
% -------------------------------------------------------------------------
CAT = hlp_sift_emptyset(...
    'curComps'          ,   variableInds    , ... % numbers for variables (e.g. channels or sources) here
    'curComponentNames' ,   g.variableNames   , ... % 'user-friendly' name for each variable -- e.g. anatomical names
    'nbchan'            ,   numVars         , ... % number of variables (e.g. numVars above)
    'Conn'              ,   Conn            , ... % Connectivity structure (see above)
    'MODEL'             ,   MODEL             ... % Model structure (see above)
    );

% Make EEGLAB data structure
% -------------------------------------------------------------------------
if isempty(g.EEG)
    % if g.EEG dataset not provided, create an empty one
    g.EEG = eeg_emptyset;
end
g.EEG.CAT = CAT; % add the the SIFT ('CAT') structure

% Make dipfit structure with source/channel coordinates
% -------------------------------------------------------------------------

% These coordinates are typically (although not necessarily) in MNI space.
% If you are working with channels and have a locations file, you can also
% import the channel locations using EEGLAB routines (c.f. pop_chanedit or
% pop_readlocs). You can then convert the channel locations to a dipfit
% structure using SIFT routine hlp_chanlocs2dipfit(). This will allow you
% to render a 'channel-level' BrainMovie
%
% Below is an example of a super-basic dipfit structure which contains MNI
% source coordinates [X Y Z] copied from X, Y, Z coordinate vectors
%
% See http://sccn.ucsd.edu/wiki/A08:_DIPFIT#DIPFIT_structure_and_functions
% for details on the fields in dipfit structure.
%
% NOTE: SIFT by default uses the freesurfer segmentations of the standard
%       (Colins) MNI brain for surface visualization. If you use your own
%       head model, you will need to supply this surface file via the
%       'Layers' option of vis_causalBrainMovie3D().
%       Also, if using default MNI brain and the network looks rotated
%       90 deg, try changing dipfit.coordformat to 'mni'

if ~isempty(g.MNI_XYZ)

    if isstruct(g.MNI_XYZ)
        % just copy the provided dipfit struct
        g.EEG.dipfit = g.MNI_XYZ;
    else
        % build a new dipfit struct
        dipfit.hdmfile  = '';
        dipfit.mrifile  = fullfile(fileparts(utl_whichfile('eeglab')),'plugins','dipfit2.2','standard_BEM','standard_mri.mat');
        dipfit.chanfile = '';
        dipfit.chansel  = 1:numVars;
        dipfit.coordformat = 'MNI';
        dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];

        for i=1:numVars
            dipfit.model(i).posxyz      = g.MNI_XYZ(i,:);
            dipfit.model(i).momxyz      = [0 0 0];
            dipfit.model(i).rv          = 0;
            dipfit.model(i).select      = 1;
            dipfit.model(i).diffmap     = [];
            dipfit.model(i).sourcepot   = [];
            dipfit.model(i).datapot     = [];
        end
        g.EEG.dipfit = dipfit;
    end
end

EEG = g.EEG;