Home > rest_20090422 > rest_sliceviewer.m

rest_sliceviewer

PURPOSE ^

Show a brain's slice. "rest_sliceviewer" can be opened more than one instance like MRIcro, and supports multi-slice, overlay and so on. by Xiao-Wei Song

SYNOPSIS ^

function [varargout]=rest_sliceviewer(AOperation, varargin)

DESCRIPTION ^

 Show a brain's slice. "rest_sliceviewer" can be opened more than one instance like MRIcro, and supports multi-slice, overlay and so on. by Xiao-Wei Song
Usage: hFig =rest_sliceviewer('ShowImage', AFilename, CallBack);
           rest_sliceviewer('Delete', AFigHandle);
Detailed usage is the code file "rest_sliceviewer.m"
------------------------------------------------------------------------------------------------------------------------------
    Copyright(c) 2007~2010
    State Key Laboratory of Cognitive Neuroscience and Learning in Beijing Normal University
    Written by Xiao-Wei Song 
    http://resting-fmri.sourceforge.net
     Mail to Authors:  <a href="Dawnwei.Song@gmail.com">Xiaowei Song</a>; <a href="ycg.yan@gmail.com">Chaogan Yan</a> 
    Version=1.3;
    Release=20090401;
   Modified by SONG Xiao-Wei 20071101: change Position 
   Modified by Yan Chao-Gan 080808: also support NIFTI (.img/.hdr) images.
   Modified by Yan Chao-Gan 080903: also support NIFTI (.nii) images.
   Modified by YAN Chao-Gan 090101: added "save image as" function; change the display mode of transverse multislices as similar to AFNI; fixed the bug of cluster size threshold.
   Last Modified by YAN Chao-Gan 090401: added "Correction Thresholds by AlphaSim" (under Misc menu); Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version which caused by the revision of imresize funtion in Matlab R2007a.
------------------------------------------------------------------------------------------------------------------------------

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

DOWNLOAD ^

rest_sliceviewer.m

SOURCE CODE ^

0001 function [varargout]=rest_sliceviewer(AOperation, varargin)
0002 % Show a brain's slice. "rest_sliceviewer" can be opened more than one instance like MRIcro, and supports multi-slice, overlay and so on. by Xiao-Wei Song
0003 %Usage: hFig =rest_sliceviewer('ShowImage', AFilename, CallBack);
0004 %           rest_sliceviewer('Delete', AFigHandle);
0005 %Detailed usage is the code file "rest_sliceviewer.m"
0006 %------------------------------------------------------------------------------------------------------------------------------
0007 %    Copyright(c) 2007~2010
0008 %    State Key Laboratory of Cognitive Neuroscience and Learning in Beijing Normal University
0009 %    Written by Xiao-Wei Song
0010 %    http://resting-fmri.sourceforge.net
0011 %     Mail to Authors:  <a href="Dawnwei.Song@gmail.com">Xiaowei Song</a>; <a href="ycg.yan@gmail.com">Chaogan Yan</a>
0012 %    Version=1.3;
0013 %    Release=20090401;
0014 %   Modified by SONG Xiao-Wei 20071101: change Position
0015 %   Modified by Yan Chao-Gan 080808: also support NIFTI (.img/.hdr) images.
0016 %   Modified by Yan Chao-Gan 080903: also support NIFTI (.nii) images.
0017 %   Modified by YAN Chao-Gan 090101: added "save image as" function; change the display mode of transverse multislices as similar to AFNI; fixed the bug of cluster size threshold.
0018 %   Last Modified by YAN Chao-Gan 090401: added "Correction Thresholds by AlphaSim" (under Misc menu); Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version which caused by the revision of imresize funtion in Matlab R2007a.
0019 %------------------------------------------------------------------------------------------------------------------------------
0020 
0021 if nargin<1, %No param Launch, 20070918
0022     help(mfilename);
0023     if nargout>=1,
0024         varargout{1}=rest_sliceviewer('ShowImage','');    %by Default, I show a black brain image
0025     else
0026         rest_sliceviewer('ShowImage','');    %by Default, I show a black brain image
0027     end
0028     return; 
0029 end
0030 
0031 %Initializitation
0032 persistent REST_SliceViewer_Cfg; % run-time persistent config
0033 %if isempty(REST_SliceViewer_Cfg), disp('ko'); end
0034 if ~mislocked(mfilename),mlock; end
0035 %For further Debug, 20070915, to make sure the Config variable exist
0036 % if isempty(REST_SliceViewer_Cfg),
0037     % REST_SliceViewer_Cfg =getappdata(0, 'REST_SliceViewer_Cfg');
0038 % else
0039     % setappdata(0, 'REST_SliceViewer_Cfg', REST_SliceViewer_Cfg);
0040 % end
0041 
0042 try
0043     switch upper(AOperation),
0044     case 'SHOWIMAGE',    %ShowImage
0045         if nargin==2,
0046             %rest_sliceviewer('ShowImage', theBrainMap); %reho_gui.m 989
0047             AFilename =varargin{1};
0048             ACallback ='';        
0049         elseif nargin==3,
0050             %rest_sliceviewer('ShowImage', theBrainMap, [theCallback cmdClearVar], 'Power Spectrum');%reho_gui.m 1010
0051             AFilename =varargin{1};
0052             ACallback =varargin{2};        
0053         else
0054             error(sprintf('Usage: hFig =rest_sliceviewer(''ShowImage'', AFilename); \n\t hFig =rest_sliceviewer(''ShowImage'', AFilename, ACallback);')); 
0055         end
0056         
0057         %Let current handle of the figure be a GUID for the current SliceViewer
0058         % theFig =ExistDisplayFigure(REST_SliceViewer_Cfg, AFilename);
0059         % isExistFig =rest_misc( 'ForceCheckExistFigure' , theFig);    %Force check whether the figure exist
0060         % if ~isExistFig
0061             %the specific image didn't exist, so I create one
0062             REST_SliceViewer_Cfg.Config(1+GetDisplayCount(REST_SliceViewer_Cfg)) =InitControls(AFilename, ACallback);
0063             %To Force display following the end of this if-clause
0064             theFig =REST_SliceViewer_Cfg.Config(GetDisplayCount(REST_SliceViewer_Cfg)).hFig;
0065             
0066             %I don't display the information defaultly
0067             ToggleInfoDisplay(REST_SliceViewer_Cfg.Config(GetDisplayCount(REST_SliceViewer_Cfg)));
0068         % end
0069         figure(theFig);    
0070         varargout{1} =theFig;
0071             
0072     case 'UPDATECALLBACK',         %UpdateCallback
0073         if nargin==2, 
0074             AFigHandle =varargin{1};
0075             ACallback ='';    
0076             ACallbackCaption='';
0077         elseif nargin==3, 
0078             AFigHandle =varargin{1};
0079             ACallback =varargin{2};    
0080             ACallbackCaption='';
0081         elseif nargin==4, 
0082             AFigHandle =varargin{1};
0083             ACallback =varargin{2};    
0084             ACallbackCaption=varargin{3};    
0085         else
0086             error('Usage: rest_sliceviewer(''UpdateCallback'', AFigureHandle, ACallback, ACallbackCaption);'); 
0087         end
0088         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0089         if theCardinal>0,
0090             REST_SliceViewer_Cfg.Config(theCardinal) =UpdateCallback(REST_SliceViewer_Cfg.Config(theCardinal), ACallback, ACallbackCaption);
0091             ResizeFigure(REST_SliceViewer_Cfg.Config(theCardinal));
0092         end
0093         
0094         
0095     case 'DELETE', % Delete specific figure
0096         if nargin~=2, error('Usage: rest_sliceviewer(''Delete'', AFigHandle);'); end
0097         AFigHandle =varargin{1};
0098         REST_SliceViewer_Cfg =DeleteFigure(REST_SliceViewer_Cfg, AFigHandle);
0099         
0100         if ~GetDisplayCount(REST_SliceViewer_Cfg),
0101             rest_sliceviewer('QuitAllSliceViewer');
0102         end
0103         
0104     case {'CLICKPOSITION', 'SETPOSITION'},        %ClickPosition    %SetPosition
0105         if nargin~=2, error('Usage: rest_sliceviewer(''ClickPosition'', AFigHandle); or rest_sliceviewer(''SetPosition'', AFigHandle);'); end
0106         AFigHandle =varargin{1};
0107         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0108         if theCardinal>0
0109             if strcmpi(AOperation, 'ClickPosition'),    % for Mouse click
0110                 if strcmpi(REST_SliceViewer_Cfg.Config(theCardinal).ViewMode, 'Orthogonal'),
0111                     REST_SliceViewer_Cfg.Config(theCardinal) =ClickPositionCrossHair(REST_SliceViewer_Cfg.Config(theCardinal));        
0112                 elseif strcmpi(REST_SliceViewer_Cfg.Config(theCardinal).ViewMode, 'Sagittal'),
0113                     REST_SliceViewer_Cfg.Config(theCardinal) =ClickPositionInSagittalMode(REST_SliceViewer_Cfg.Config(theCardinal));
0114                 elseif strcmpi(REST_SliceViewer_Cfg.Config(theCardinal).ViewMode, 'Coronal'),
0115                     REST_SliceViewer_Cfg.Config(theCardinal) =ClickPositionInCoronalMode(REST_SliceViewer_Cfg.Config(theCardinal));
0116                 elseif strcmpi(REST_SliceViewer_Cfg.Config(theCardinal).ViewMode, 'Transverse'),
0117                     REST_SliceViewer_Cfg.Config(theCardinal) =ClickPositionInTransverseMode(REST_SliceViewer_Cfg.Config(theCardinal));
0118                 end
0119             elseif strcmpi(AOperation, 'SetPosition'), % for [x y z] manual input
0120                 REST_SliceViewer_Cfg.Config(theCardinal) =SetPositionCrossHair(REST_SliceViewer_Cfg.Config(theCardinal));
0121             end        
0122                     
0123             
0124             %If yoke, then update all yoked image
0125             isSelfYoked =get(REST_SliceViewer_Cfg.Config(theCardinal).hYoke, 'Value');
0126             if isSelfYoked ,
0127                 theDistanceFromOrigin =(REST_SliceViewer_Cfg.Config(theCardinal).LastPosition -REST_SliceViewer_Cfg.Config(theCardinal).Origin) .* REST_SliceViewer_Cfg.Config(theCardinal).VoxelSize;
0128                 %Dawnsong 20071102 Revise to make sure the left image/Right brain is +
0129                 theDistanceFromOrigin =[-1, 1, 1].* theDistanceFromOrigin;
0130                 
0131                 for x=1:GetDisplayCount(REST_SliceViewer_Cfg), 
0132                     if x~=theCardinal ,
0133                         isYoked =get(REST_SliceViewer_Cfg.Config(x).hYoke, 'Value');
0134                         if isYoked,                             
0135                             rest_sliceviewer('SetPhysicalPosition', REST_SliceViewer_Cfg.Config(x).hFig, theDistanceFromOrigin);
0136                         end
0137                     end
0138                 end
0139             end    
0140             
0141             %Execute the Callback
0142             rest_sliceviewer('RunCallback', AFigHandle);            
0143         end
0144         
0145     case 'SETPHYSICALPOSITION',        %SetPhysicalPosition, for Yoke, the physical position(mm) from the origin
0146         if nargin~=3, error('Usage: rest_sliceviewer(''SetPhysicalPosition'', AFigHandle, ADistanceFromOrigin);'); end
0147         AFigHandle =varargin{1};
0148         ADistanceFromOrigin =varargin{2};
0149         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0150         if theCardinal>0,
0151             %Dawnsong 20071102 Revise to make sure the left image/Right brain is +
0152             ADistanceFromOrigin =[-1, 1, 1].* ADistanceFromOrigin;
0153 
0154             REST_SliceViewer_Cfg.Config(theCardinal) =SetDistanceFromOrigin(REST_SliceViewer_Cfg.Config(theCardinal), ADistanceFromOrigin);
0155             
0156             %Execute the Callback
0157             rest_sliceviewer('RunCallback', AFigHandle);    
0158         end        
0159     case 'RUNCALLBACK',             %RunCallback    , 20070625
0160         if nargin~=2, error('Usage: rest_sliceviewer(''RunCallback'', AFigHandle);'); end
0161         AFigHandle =varargin{1};    
0162         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0163         if theCardinal>0        
0164             % Run the Callback
0165             if ~isempty(REST_SliceViewer_Cfg.Config(theCardinal).Callback) 
0166                 if ischar(REST_SliceViewer_Cfg.Config(theCardinal).Callback),
0167                     eval(REST_SliceViewer_Cfg.Config(theCardinal).Callback); %run callback for caller
0168                 elseif isa(REST_SliceViewer_Cfg.Config(theCardinal).Callback, 'function_handle')
0169                     %I give 2 parameters, 20070624
0170                     %1) position: X, Y , Z,
0171                     %2) and 3-dim: XSize, YSize, ZSize
0172                     thePos =REST_SliceViewer_Cfg.Config(theCardinal).LastPosition;
0173                     theSize=size(REST_SliceViewer_Cfg.Config(theCardinal).Volume);
0174                     REST_SliceViewer_Cfg.Config(theCardinal).Callback(thePos, theSize);
0175                 end
0176             end        
0177         end
0178         
0179         
0180     case 'GETPOSITION',         %GetPosition, return Absolute    position where current cross-hair stay
0181         if nargin~=2, error('Usage: Position =rest_sliceviewer(''GetPosition'', AFigHandle);'); end
0182         AFigHandle =varargin{1};
0183         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0184         if theCardinal>0
0185             varargout{1}=REST_SliceViewer_Cfg.Config(theCardinal).LastPosition;     
0186         end
0187         
0188     case 'GETPHYSICALPOSITION',         %GetPhysicalPosition return Coordinate .* VoxelSize    (mm)
0189         if nargin~=2, error('Usage: DistanceFromOrigin =rest_sliceviewer(''GetPhysicalPosition'', AFigHandle);'); end
0190         AFigHandle =varargin{1};
0191         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0192         if theCardinal>0
0193             thePosition =REST_SliceViewer_Cfg.Config(theCardinal).LastPosition;     
0194             theOrigin      =REST_SliceViewer_Cfg.Config(theCardinal).Origin;
0195             theVoxelSize=REST_SliceViewer_Cfg.Config(theCardinal).VoxelSize;
0196             varargout{1} =(thePosition - theOrigin) * theVoxelSize;
0197         end    
0198 
0199     case 'SETMESSAGE',            %SetMessage, update the Message, I don't contain the Copyright any more , 20070915
0200         if nargin~=3, error('Usage: rest_sliceviewer(''SetMessage'', AFigHandle, AMessage);'); end
0201         AFigHandle     =varargin{1};
0202         AMessage    =varargin{2};
0203         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0204         if theCardinal>0
0205             REST_SliceViewer_Cfg.Config(theCardinal).Message =AMessage;
0206             SetMessage(REST_SliceViewer_Cfg.Config(theCardinal));
0207             ResizeFigure(REST_SliceViewer_Cfg.Config(theCardinal));
0208         end    
0209         
0210     case 'MAGNIFY',         %Magnify, x0.5 -x1 -x2 -x3 -x4 -x5 -x6
0211         if nargin~=2, error('Usage: rest_sliceviewer(''Magnify'', AFigHandle);'); end
0212         AFigHandle     =varargin{1};    
0213         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0214         if theCardinal>0
0215             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));            
0216         end    
0217         
0218     case 'QUITALLSLICEVIEWER',        %QuitAllSliceViewer
0219         if nargin~=1, error('Usage: rest_sliceviewer(''QuitAllSliceViewer'');'); end
0220         for x=GetDisplayCount(REST_SliceViewer_Cfg):-1:1, % DawnSong, revised 20070625
0221             rest_sliceviewer('DELETE', REST_SliceViewer_Cfg.Config(x).Filename);
0222         end
0223         if mislocked(mfilename),munlock; end
0224         clear REST_SliceViewer_Cfg;
0225         
0226     case 'MONTAGE',         %Montage
0227         if nargin~=2, error('Usage: rest_sliceviewer(''Montage'', AFigHandle);'); end
0228         AFigHandle     =varargin{1};    
0229         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0230         if theCardinal>0,
0231             prompt ={'Across: (i.e. the number of columns)', 'Down: (i.e. the number of rows)', 'Spacing(voxels): ', 'Whether to show coordinate''s label: (1=yes and 0=no.)'};
0232             def    ={    int2str(REST_SliceViewer_Cfg.Config(theCardinal).Montage.Across), ...
0233                     int2str(REST_SliceViewer_Cfg.Config(theCardinal).Montage.Down), ...
0234                     int2str(REST_SliceViewer_Cfg.Config(theCardinal).Montage.Spacing), ...
0235                     int2str(REST_SliceViewer_Cfg.Config(theCardinal).Montage.WantLabel)};
0236             answer =inputdlg(prompt, 'Montage Set', 1, def);
0237             if numel(answer)==4,
0238                 theVal =abs(round(str2num(answer{1})));
0239                 if theVal==0, theVal=1; end
0240                 REST_SliceViewer_Cfg.Config(theCardinal).Montage.Across = theVal;
0241                 theVal =abs(round(str2num(answer{2})));
0242                 if theVal==0, theVal=1; end
0243                 REST_SliceViewer_Cfg.Config(theCardinal).Montage.Down =theVal;
0244                 
0245                 REST_SliceViewer_Cfg.Config(theCardinal).Montage.Spacing = abs(round(str2num(answer{3})));
0246                 REST_SliceViewer_Cfg.Config(theCardinal).Montage.WantLabel = abs(round(str2num(answer{4})));
0247                 %Update Image Display
0248                 REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0249             end
0250         end;
0251 
0252     case 'ORTHOGONALVIEW',         %OrthogonalView
0253         if nargin~=2, error('Usage: rest_sliceviewer(''OrthogonalView'', AFigHandle);'); end
0254         AFigHandle     =varargin{1};    
0255         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0256         if theCardinal>0,
0257             REST_SliceViewer_Cfg.Config(theCardinal).ViewMode ='Orthogonal';
0258             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0259         end;    
0260         
0261     case 'TRANSVERSEVIEW',         %TransverseView
0262         if nargin~=2, error('Usage: rest_sliceviewer(''TransverseView'', AFigHandle);'); end
0263         AFigHandle     =varargin{1};    
0264         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0265         if theCardinal>0,
0266             REST_SliceViewer_Cfg.Config(theCardinal).ViewMode ='Transverse';
0267             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0268         end;
0269             
0270     case 'SAGITTALVIEW',         %SagittalView
0271         if nargin~=2, error('Usage: rest_sliceviewer(''SagittalView'', AFigHandle);'); end
0272         AFigHandle     =varargin{1};    
0273         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0274         if theCardinal>0,
0275             REST_SliceViewer_Cfg.Config(theCardinal).ViewMode ='Sagittal';
0276             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0277         end;
0278 
0279     case 'CORONALVIEW',         %CoronalView
0280         if nargin~=2, error('Usage: rest_sliceviewer(''CoronalView'', AFigHandle);'); end
0281         AFigHandle     =varargin{1};    
0282         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0283         if theCardinal>0,
0284             REST_SliceViewer_Cfg.Config(theCardinal).ViewMode ='Coronal';
0285             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0286         end;
0287 
0288     case 'REPAINT',        %Repaint
0289         if nargin~=2, error('Usage: rest_sliceviewer(''Repaint'', AFigHandle);'); end
0290         AFigHandle     =varargin{1};    
0291         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0292         if theCardinal>0,        
0293             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0294         end;
0295     case 'MNI/TALAIRACH',        %MNI/Talairach
0296         if nargin~=2, error('Usage: rest_sliceviewer(''Repaint'', AFigHandle);'); end
0297         AFigHandle     =varargin{1};    
0298         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0299         if theCardinal>0,        
0300             Transforming_MNI_Talairach(REST_SliceViewer_Cfg.Config(theCardinal));
0301             rest_sliceviewer('SetPosition', AFigHandle);
0302         end;
0303         
0304     case 'CHANGEUNDERLAY',         %ChangeUnderlay
0305         if nargin~=2, error('Usage: rest_sliceviewer(''ChangeUnderlay'', AFigHandle);'); end
0306         AFigHandle     =varargin{1};
0307         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0308         if theCardinal>0,
0309             %Get the changed Underlay file
0310             theNewUnderlay =get(REST_SliceViewer_Cfg.Config(theCardinal).hUnderlayFile, 'String');
0311             % if exist(theNewUnderlay,'file')==2,
0312             % if ~all(isspace(theNewUnderlay)),    %20070918
0313                 %Set the current underlay
0314                 REST_SliceViewer_Cfg.Config(theCardinal).Filename =theNewUnderlay;
0315                 REST_SliceViewer_Cfg.Config(theCardinal) =InitUnderlay(REST_SliceViewer_Cfg.Config(theCardinal));
0316                 REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0317                 set(REST_SliceViewer_Cfg.Config(theCardinal).hUnderlayFile, 'String', theNewUnderlay, 'TooltipString', theNewUnderlay);
0318             % end
0319         end;
0320         
0321     case 'UNDERLAYSELECTION',         %UnderlaySelection
0322         if nargin~=2, error('Usage: rest_sliceviewer(''UnderlaySelection'', AFigHandle);'); end
0323         AFigHandle     =varargin{1};    
0324         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0325         if theCardinal>0,            
0326             [filename, pathname] = uigetfile({'*.img', 'ANALYZE or NIFTI files (*.img)';'*.nii','NIFTI files (*.nii)'}, ...
0327                                                             'Pick one brain map');
0328             if any(filename~=0) && ischar(filename) && length(filename)>4 ,    % not canceled and legal
0329                 if ~strcmpi(pathname(end), filesep)%revise pathname to add \ or /
0330                     pathname = [pathname filesep];
0331                 end
0332                 theBrainMap =[pathname filename];
0333                 set(REST_SliceViewer_Cfg.Config(theCardinal).hUnderlayFile, 'String', theBrainMap);
0334                 rest_sliceviewer('ChangeUnderlay', AFigHandle);
0335             end            
0336         end;
0337     case 'CLICKRECENTUNDERLAY',     %ClickRecentUnderlay
0338         if nargin~=2, error('Usage: rest_sliceviewer(''ClickRecentUnderlay'', AFigHandle);'); end
0339         AFigHandle     =varargin{1};    
0340         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0341         if theCardinal>0,            
0342             theIndex =get(REST_SliceViewer_Cfg.Config(theCardinal).hUnderlayRecent, 'Value');
0343             if theIndex>1,
0344                 theBrainMap =REST_SliceViewer_Cfg.Config(theCardinal).Recent.Underlay{theIndex-1};
0345                 set(REST_SliceViewer_Cfg.Config(theCardinal).hUnderlayFile, 'String', theBrainMap);
0346                 set(REST_SliceViewer_Cfg.Config(theCardinal).hUnderlayRecent, 'Value', 1);
0347                 rest_sliceviewer('ChangeUnderlay', AFigHandle);                
0348             end
0349         end;
0350         
0351     case 'CHANGEOVERLAY',         %ChangeOverlay
0352         if nargin~=2, error('Usage: rest_sliceviewer(''ChangeOverlay'', AFigHandle);'); end
0353         AFigHandle     =varargin{1};
0354         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0355         if theCardinal>0,
0356             %Get the changed Overlay file
0357             theNewOverlay =get(REST_SliceViewer_Cfg.Config(theCardinal).hOverlayFile, 'String');
0358             % if exist(theNewOverlay,'file')==2,
0359             % if ~all(isspace(theNewOverlay)),
0360                 %Set the current Overlay
0361                 REST_SliceViewer_Cfg.Config(theCardinal) =LoadOverlay(REST_SliceViewer_Cfg.Config(theCardinal), theNewOverlay);
0362                 set(REST_SliceViewer_Cfg.Config(theCardinal).hSeeOverlay, 'Value', 1);
0363                 REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0364                 set(REST_SliceViewer_Cfg.Config(theCardinal).hOverlayFile, 'String', theNewOverlay, 'TooltipString', theNewOverlay);
0365             % end
0366         end;
0367         
0368     case 'OVERLAYSELECTION',         %OverlaySelection
0369         if nargin~=2, error('Usage: rest_sliceviewer(''UnderlaySelection'', AFigHandle);'); end
0370         AFigHandle     =varargin{1};    
0371         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0372         if theCardinal>0,        
0373             [filename, pathname] = uigetfile({'*.img', 'ANALYZE or NIFTI files (*.img)';'*.nii','NIFTI files (*.nii)'}, ...
0374                                                             'Pick one brain map');
0375             if any(filename~=0) && ischar(filename) && length(filename)>4 ,    % not canceled and legal
0376                 if ~strcmpi(pathname(end), filesep)%revise pathname to add \ or /
0377                     pathname = [pathname filesep];
0378                 end
0379                 theBrainMap =[pathname filename];
0380                 set(REST_SliceViewer_Cfg.Config(theCardinal).hOverlayFile, 'String', theBrainMap);
0381                 rest_sliceviewer('ChangeOverlay', AFigHandle);
0382             end        
0383         end;
0384     case 'CLICKRECENTOVERLAY',     %ClickRecentOverlay
0385         if nargin~=2, error('Usage: rest_sliceviewer(''ClickRecentOverlay'', AFigHandle);'); end
0386         AFigHandle     =varargin{1};    
0387         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0388         if theCardinal>0,            
0389             theIndex =get(REST_SliceViewer_Cfg.Config(theCardinal).hOverlayRecent, 'Value');
0390             if theIndex>1,
0391                 theBrainMap =REST_SliceViewer_Cfg.Config(theCardinal).Recent.Overlay{theIndex-1};
0392                 set(REST_SliceViewer_Cfg.Config(theCardinal).hOverlayFile, 'String', theBrainMap);
0393                 set(REST_SliceViewer_Cfg.Config(theCardinal).hOverlayRecent, 'Value', 1);
0394                 rest_sliceviewer('ChangeOverlay', AFigHandle);
0395             end
0396         end;
0397         
0398     case 'OVERLAY_SETTHRDABSVALUE',        %Overlay_SetThrdAbsValue, %Change from the Absolute value Edit control
0399         if nargin~=2, error('Usage: rest_sliceviewer(''Overlay_SetThrdAbsValue'', AFigHandle);'); end
0400         AFigHandle     =varargin{1};    
0401         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0402         if theCardinal>0,
0403             REST_SliceViewer_Cfg.Config(theCardinal).Overlay.ValueThrdAbsolute =SetThrdAbsValue(REST_SliceViewer_Cfg.Config(theCardinal));
0404             REST_SliceViewer_Cfg.Config(theCardinal) =ThresholdOverlayVolume(REST_SliceViewer_Cfg.Config(theCardinal));
0405             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));            
0406         end    
0407     case 'OVERLAY_SETTHRDCLUSTERSIZE',         %Overlay_SetThrdClusterSize
0408         if nargin~=2, error('Usage: rest_sliceviewer(''Overlay_SetThrdClusterSize'', AFigHandle);'); end
0409         AFigHandle     =varargin{1};    
0410         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0411         if theCardinal>0,
0412             theConfig =REST_SliceViewer_Cfg.Config(theCardinal);
0413             prompt ={'Set Cluster Size(voxel) must be GREATER than: ', 'Set Cluster Raidus(mm) must be GREATER than: (this value would be transformed to Cluster Size according to the Overlay''s size and its voxel''s size)'};
0414             def    ={num2str(theConfig.Overlay.ClusterSizeThrd) ,...
0415                   num2str(theConfig.Overlay.ClusterRadiusThrd)};
0416             answer =inputdlg(prompt, 'Threshold by cluster size ', 1, def);
0417             if numel(answer)==2,
0418                 theVal =abs(str2num(answer{1}));                
0419                 theConfig.Overlay.ClusterSizeThrd =round(theVal);
0420                 
0421                 theVal =abs(str2num(answer{2}));
0422                 theConfig.Overlay.ClusterRadiusThrd =round(theVal);
0423                 
0424                 REST_SliceViewer_Cfg.Config(theCardinal) =theConfig;
0425                 REST_SliceViewer_Cfg.Config(theCardinal) =ThresholdOverlayVolume(REST_SliceViewer_Cfg.Config(theCardinal));
0426                 REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0427             end            
0428         end    
0429     case 'OVERLAY_MISC',         %Overlay_Misc
0430         if nargin~=2, error('Usage: rest_sliceviewer(''Overlay_Misc'', AFigHandle);'); end
0431         AFigHandle     =varargin{1};    
0432         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0433         if theCardinal>0,
0434             REST_SliceViewer_Cfg.Config(theCardinal) =Overlay_Misc(REST_SliceViewer_Cfg.Config(theCardinal));
0435             rest_sliceviewer('Repaint', AFigHandle);
0436         end    
0437     case 'OPEN_TEMPLATE',         %Open_Template
0438         if nargin~=2, error('Usage: rest_sliceviewer(''Overlay_Misc'', AFigHandle);'); end
0439         AFigHandle     =varargin{1};    
0440         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0441         if theCardinal>0,
0442             REST_SliceViewer_Cfg.Config(theCardinal) =Open_Template(REST_SliceViewer_Cfg.Config(theCardinal));            
0443             rest_sliceviewer('Repaint', AFigHandle);    
0444         end    
0445     
0446     case 'CURRENTCLUSTER2MASK',            %CurrentCluster2Mask
0447         if nargin~=2, error('Usage: rest_sliceviewer(''CurrentCluster2Mask'', AFigHandle);'); end
0448         AFigHandle     =varargin{1};    
0449         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0450         if theCardinal>0,
0451             theConfig =REST_SliceViewer_Cfg.Config(theCardinal);
0452             theMask =CurrentCluster2Mask(REST_SliceViewer_Cfg.Config(theCardinal));
0453             if ~isempty(theMask),
0454                 [filename, pathname] = uiputfile('*.img','Save current point''s cluster: ');
0455                 if isequal(filename,0) | isequal(pathname,0),
0456                 else
0457                     if length(filename)>4,                        
0458                         if strcmpi(filename(end-3:end), '.img')
0459                           filename = filename(1:end-4);
0460                         end
0461                     end
0462                     theMaskFile =fullfile(pathname, filename);    
0463                     theConfig.Overlay.Header.Origin=theConfig.Overlay.Origin; %%Yan 080610
0464                     rest_writefile(theMask, theMaskFile, size(theConfig.Overlay.Volume), ...
0465                                 theConfig.Overlay.VoxelSize, theConfig.Overlay.Header,'int16'); %%Yan 080610
0466                     theConfig.LastSavedMask =[theMaskFile ,'.img'];
0467                     if ~isempty(theConfig.Callback.Save2Mask),
0468                         eval(theConfig.Callback.Save2Mask);
0469                     end
0470                 end                
0471                 rest_sliceviewer('Repaint', AFigHandle);
0472             else
0473                 errordlg(sprintf('No cluster found at (%s)', ...
0474                     num2str(Pos_Underlay2Overlay(theConfig, theConfig.LastPosition) -theConfig.Overlay.Origin)));
0475             end
0476             
0477             REST_SliceViewer_Cfg.Config(theCardinal) =theConfig;
0478         end    
0479     
0480     case 'SAVERECENT',        %SaveRecent
0481         if nargin~=2, error('Usage: rest_sliceviewer(''SaveRecent'', AFigHandle);'); end
0482         AFigHandle     =varargin{1};    
0483         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0484         if theCardinal>0,
0485             SaveRecent(REST_SliceViewer_Cfg.Config(theCardinal), 'RecentOverlay');
0486             SaveRecent(REST_SliceViewer_Cfg.Config(theCardinal), 'RecentUnderlay');
0487         end
0488         
0489     case 'CHANGECOLORELEMENT',         %ChangeColorElement
0490         if nargin~=2, error('Usage: rest_sliceviewer(''ChangeColorElement'', AFigHandle);'); end
0491         AFigHandle     =varargin{1};    
0492         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0493         if theCardinal>0,
0494             REST_SliceViewer_Cfg.Config(theCardinal) =SetColorElements(REST_SliceViewer_Cfg.Config(theCardinal));
0495             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0496         end
0497         
0498     case 'TOGGLEINFODISPLAY',         %ToggleInfoDisplay
0499         if nargin~=2, error('Usage: rest_sliceviewer(''ToggleInfoDisplay'', AFigHandle);'); end
0500         AFigHandle     =varargin{1};    
0501         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0502         if theCardinal>0,
0503             ToggleInfoDisplay(REST_SliceViewer_Cfg.Config(theCardinal));
0504         end
0505     
0506     case 'UPDATECALLBACK_SAVE2MASK',    %UpdateCallback_Save2Mask
0507         if nargin~=3, error('Usage: rest_sliceviewer(''UpdateCallback_Save2Mask'', AFigHandle, ACallback);'); end
0508         AFigHandle     =varargin{1};    
0509         ACallback   =varargin{2};    
0510         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0511         if theCardinal>0,
0512             REST_SliceViewer_Cfg.Config(theCardinal).Callback.Save2Mask =ACallback;            
0513         end
0514     case 'GETSAVEDMASKFILENAME',        %GetSavedMaskFilename
0515         if nargin~=2, error('Usage: rest_sliceviewer(''GetSavedMaskFilename'', AFigHandle);'); end
0516         AFigHandle     =varargin{1};            
0517         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0518         if theCardinal>0,
0519             varargout{1} =REST_SliceViewer_Cfg.Config(theCardinal).LastSavedMask;
0520         else
0521             varargout{1} ='';
0522         end
0523         
0524     case 'SHOWOVERLAY',    %ShowOverlay
0525         if nargin>3, error('Usage: rest_sliceviewer(''ShowOverlay'', AOverlay); or rest_sliceviewer(''ShowOverlay'', AFigHandle, AOverlay);'); end
0526         AFigHandle     =varargin{1};
0527         if ~ischar(AFigHandle),
0528             AOverlay    =varargin{2};
0529             theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0530             if theCardinal>0,
0531                 set(REST_SliceViewer_Cfg.Config(theCardinal).hOverlayFile, 'String', AOverlay);
0532                 rest_sliceviewer('ChangeOverlay', AFigHandle);
0533             end
0534         else    %I will create a new slice-viewer
0535             AOverlay    =varargin{1};
0536             theFig = rest_sliceviewer; %I can't write "()" considering Matlab 6.5 compatiable
0537             rest_sliceviewer('ShowOverlay', theFig, AOverlay);
0538             varargout{1} =theFig;
0539         end
0540     
0541     case 'ONKEYPRESS',        %OnKeyPress
0542         if nargin~=2, error('Usage: rest_sliceviewer(''OnKeyPress'', AFigHandle);'); end
0543         AFigHandle     =varargin{1};    
0544         theCardinal =ExistViewer(REST_SliceViewer_Cfg, AFigHandle);
0545         if theCardinal>0,
0546             REST_SliceViewer_Cfg.Config(theCardinal) =OnKeyPress(REST_SliceViewer_Cfg.Config(theCardinal));
0547             %For Updating
0548             REST_SliceViewer_Cfg.Config(theCardinal) =SetImage(REST_SliceViewer_Cfg.Config(theCardinal));
0549             %For Yoke
0550             rest_sliceviewer('SetPosition', AFigHandle);
0551         end
0552         
0553     otherwise
0554     end
0555 catch
0556     rest_misc( 'DisplayLastException');
0557 end    
0558 
0559 function Result =InitControls(AFilename, ACallback)    
0560     %Initialization 20070525
0561     theFig =figure('Units', 'pixel', 'Toolbar', 'none', 'MenuBar', 'none', ...
0562                 'NumberTitle', 'off', 'Name', AFilename, 'DoubleBuffer', 'on');
0563     set(theFig, 'DeleteFcn', sprintf('rest_sliceviewer(''Delete'', %g);', theFig)  );
0564     set(theFig, 'KeyPressFcn', sprintf('rest_sliceviewer(''OnKeyPress'', %g);', theFig)  );
0565     
0566     MarginX =10; MarginY =10;
0567     OffsetX =MarginX;
0568     OffsetY =MarginY +200;            
0569     
0570     %Create Slice View options
0571     %Create uicontrols to config Yoke or [X Y Z] position to set current cross-hair to locate the voxel
0572     theLeft =OffsetX; theBottom =OffsetY;
0573     hFrameSetPos=uicontrol(theFig, 'Style','Frame', 'Units','pixels', ...
0574                             'BackgroundColor', get(theFig,'Color'), ...
0575                             'Position', [theLeft,theBottom,150,180]);    
0576     uicontrol(theFig, 'Style','pushbutton', 'Units','pixels', ...
0577             'String', 'Slice Viewer', ... %'BackgroundColor', get(theFig,'Color'), ...
0578             'Callback', 'rest_sliceviewer', ...
0579             'Position', [theLeft+35,theBottom+172,80,18]);    
0580     
0581     theLeft =OffsetX+MarginX; theBottom =OffsetY+MarginY+20 +20+MarginY/2 +10 +MarginY;
0582     hYoke =uicontrol(theFig, 'Style','checkbox', 'Units','pixels', ...
0583                     'String', 'Yoke', ...
0584                     'BackgroundColor', get(theFig,'Color'), ...
0585                     'Position',[theLeft, theBottom+75, 80,15]);
0586     theLeft =OffsetX+MarginX+56+MarginX; theBottom =OffsetY+MarginY+20 +20+MarginY/2 +10 +MarginY;    
0587     hCrosshair =uicontrol(theFig, 'Style','checkbox', 'Units','pixels', ...
0588                     'String', 'Crosshair', 'Value', 1,...
0589                     'Callback', sprintf('rest_sliceviewer(''Repaint'', %g);',theFig) , ...
0590                     'BackgroundColor', get(theFig,'Color'), ...
0591                     'Position',[theLeft, theBottom+75, 70,15]);
0592     
0593     
0594     theEditCallbackFcn =sprintf('rest_sliceviewer(''SetPosition'', %g);', theFig);
0595     theLeft =OffsetX+MarginX-5; theBottom =OffsetY+MarginY+35+MarginY/2;
0596     uicontrol(theFig, 'Style','text', 'Units','pixels', ...
0597               'String', 'X(mm)', ...
0598               'BackgroundColor', get(theFig,'Color'), ...              
0599               'Position',[theLeft, theBottom+85, 46,15]);
0600     theLeft =OffsetX+MarginX-5; theBottom =OffsetY+MarginY+20;          
0601     hEditPositionX =uicontrol(theFig, 'Style','edit', 'Units','pixels', ...
0602                               'String', '0', ...
0603                               'BackgroundColor', 'white', ...
0604                               'Callback', theEditCallbackFcn, ...
0605                               'Position',[theLeft, theBottom+85, 46,20]);
0606           
0607     theLeft =OffsetX+MarginX+36+MarginX-5; theBottom =OffsetY+MarginY+35+MarginY/2;                      
0608     uicontrol(theFig, 'Style','text', 'Units','pixels', ...
0609               'String', 'Y(mm)', ...
0610               'BackgroundColor', get(theFig,'Color'), ...
0611               'Position',[theLeft, theBottom+85, 46,15]);
0612     theLeft =OffsetX+MarginX+36+MarginX-5; theBottom =OffsetY+MarginY+20;              
0613     hEditPositionY =uicontrol(theFig, 'Style','edit', 'Units','pixels', ...
0614                               'String', '0', ...
0615                               'BackgroundColor', 'white', ...
0616                               'Callback', theEditCallbackFcn, ...
0617                               'Position',[theLeft, theBottom+85, 46,20]);
0618             
0619     theLeft =OffsetX+MarginX+36+MarginX+36+MarginX-5; theBottom =OffsetY+MarginY+35+MarginY/2;        
0620     uicontrol(theFig, 'Style','text', 'Units','pixels', ...
0621               'String', 'Z(mm)', ...
0622               'BackgroundColor', get(theFig,'Color'), ...
0623               'Position',[theLeft, theBottom+85, 46,15]);
0624     theLeft =OffsetX+MarginX+36+MarginX+36+MarginX-5; theBottom =OffsetY+MarginY+20;          
0625     hEditPositionZ =uicontrol(theFig, 'Style','edit', 'Units','pixels', ...
0626                               'String', '0', ...
0627                               'BackgroundColor', 'white', ...
0628                               'Callback', theEditCallbackFcn, ...
0629                               'Position',[theLeft, theBottom+85, 46,20]);
0630     
0631     theLeft =OffsetX+MarginX-5; theBottom =OffsetY+MarginY+20;
0632     hMagnify =uicontrol(theFig, 'Style','popupmenu', 'Units','pixels', ...
0633                         'String', {'x0.5', 'x1', 'x2', 'x3'}, ...
0634                         'Value', 2, ...
0635                         'BackgroundColor', get(theFig,'Color'), ...
0636                         'Enable', 'off', ...
0637                         'Callback', sprintf('rest_sliceviewer(''Magnify'', %g);',theFig), ...
0638                         'Position',[theLeft, theBottom+70, 70,10]);
0639     if license('test','image_toolbox')
0640         set(hMagnify, 'Enable', 'on');
0641     else
0642         warning('image_toolbox not valid');
0643     end
0644     
0645     theLeft =OffsetX+MarginX+60+MarginX-5; theBottom =OffsetY+MarginY+20;
0646     hMniTal =uicontrol(theFig, 'Style','popupmenu', 'Units','pixels', ...
0647                         'String', {'MNI/Talairach Coordinates', 'From Talairach to MNI', 'From MNI to Talairach'}, ...
0648                         'Value', 1, ...
0649                         'BackgroundColor', get(theFig,'Color'), ...
0650                         'Enable', 'on', ...
0651                         'Callback', sprintf('rest_sliceviewer(''MNI/Talairach'', %g);',theFig), ...
0652                         'Position',[theLeft, theBottom+70, 68,10]);
0653     
0654     
0655     %OffsetY =OffsetY +30;%20070911, for complete information display
0656     theLeft =OffsetX+MarginX; theBottom =OffsetY+MarginY;
0657     hVoxelIntensity=uicontrol(theFig, 'Style','text', 'Units','pixels', ...
0658                           'String', '', 'TooltipString', 'Intensity of the current point', ...
0659                           'BackgroundColor', get(theFig,'Color'), ...
0660                           'HorizontalAlignment', 'left', ...  % 'Visible', 'off', ...                          
0661                           'Position',[theLeft-5, theBottom+42, 110,32]);
0662               
0663     %Create a Message label to display some specific message, dawnsong 20070526
0664     theLeft =OffsetX+MarginX; theBottom =OffsetY +100 +MarginY;
0665     hMsgLabel =uicontrol(theFig, 'Style','text', 'Units','pixels', ...
0666               'String', sprintf('Dawnwei.Song Copyright 2007-2010, all rights reserved'), ...
0667               'BackgroundColor', get(theFig,'Color'), ...
0668               'HorizontalAlignment', 'left', 'Enable', 'inactive',...
0669               'ButtonDownFcn', sprintf('rest_sliceviewer(''ToggleInfoDisplay'', %g);',theFig), ...
0670               'Position',[theLeft, theBottom, 130,10]);    
0671               
0672     % Create a Callback Button to do sth.
0673     theLeft =OffsetX+MarginX; theBottom =OffsetY +100 +MarginY +10;
0674     % hDoCallbackBtn =-1;
0675     % if ~isempty(ACallback) && ischar(ACallback)
0676         % hDoCallbackBtn =uicontrol(theFig, 'Style','pushbutton',  ...
0677                               % 'Units','pixels', 'String', 'Do sth.', ...
0678                               % 'Callback', ACallback, ...
0679                               % 'Position',[theLeft, theBottom, 130,10]);
0680     % end
0681     %View Buttons
0682     theLeft =OffsetX+MarginX-4; theBottom =OffsetY +MarginY-2;
0683     theIcon =imread(fullfile(rest_misc( 'WhereIsREST'), 'icoTransverse.jpg'));
0684     hViewTransverse =uicontrol(theFig, 'Style','pushbutton',  ...
0685                               'Units','pixels', ...
0686                               'Callback', sprintf('rest_sliceviewer(''TransverseView'', %g);',theFig) , ...
0687                               'CData', theIcon,...
0688                               'Position',[theLeft, theBottom, 34,36]);
0689     theLeft =OffsetX+MarginX+30; theBottom =OffsetY +MarginY-2;
0690     theIcon =imread(fullfile(rest_misc( 'WhereIsREST'), 'icoSagittal.jpg'));
0691     hViewSagittal =uicontrol(theFig, 'Style','pushbutton',  ...
0692                               'Units','pixels', ...
0693                               'Callback', sprintf('rest_sliceviewer(''SagittalView'', %g);',theFig) , ...
0694                               'CData', theIcon,...
0695                               'Position',[theLeft, theBottom, 34,36]);
0696     theLeft =OffsetX+MarginX+34+30; theBottom =OffsetY +MarginY-2;
0697     theIcon =imread(fullfile(rest_misc( 'WhereIsREST'), 'icoCoronal.jpg'));
0698     hViewCoronal =uicontrol(theFig, 'Style','pushbutton',  ...
0699                               'Units','pixels', ...
0700                               'Callback', sprintf('rest_sliceviewer(''CoronalView'', %g);',theFig) , ...
0701                               'CData', theIcon,...
0702                               'Position',[theLeft, theBottom, 34,36]);
0703     theLeft =OffsetX+MarginX+34+34+30; theBottom =OffsetY +MarginY-2;
0704     theIcon =imread(fullfile(rest_misc( 'WhereIsREST'), 'icoOrthogonal.jpg'));
0705     hViewOrthogonal =uicontrol(theFig, 'Style','pushbutton',  ...
0706                               'Units','pixels', ...
0707                               'Callback', sprintf('rest_sliceviewer(''OrthogonalView'', %g);',theFig) , ...
0708                               'CData', theIcon,...
0709                               'Position',[theLeft, theBottom, 34,36]);
0710     theLeft =OffsetX+MarginX+34+30; theBottom =OffsetY +MarginY+34;    
0711     hViewMontage =uicontrol(theFig, 'Style','pushbutton',  ...
0712                               'Units','pixels', ...
0713                               'Callback', sprintf('rest_sliceviewer(''Montage'', %g);',theFig) , ...
0714                               'String', 'Montage','TooltipString', 'Montage: Multislice',...
0715                               'Position',[theLeft, theBottom, 68,24]);
0716                               
0717     
0718     
0719     %Add Underlay file selection directly
0720     theLeft =OffsetX; theBottom =MarginY+180;
0721     hUnderlayRecent =uicontrol(theFig, 'Style','popupmenu', 'Units','pixels', ...
0722               'String', {'Underlay: '}, 'Value', 1, ...
0723               'Callback', sprintf('rest_sliceviewer(''ClickRecentUnderlay'', %g);',theFig), ...
0724               'BackgroundColor', get(theFig,'Color'), ...              
0725               'Position',[theLeft, theBottom, 75,20]);     
0726     theLeft =OffsetX; theBottom =MarginY+160;
0727     hUnderlayFile =uicontrol(theFig, 'Style','edit', 'Units','pixels', ...
0728                               'String', '', ...
0729                               'BackgroundColor', 'white', ...
0730                               'Callback', sprintf('rest_sliceviewer(''ChangeUnderlay'', %g);',theFig), ...
0731                               'Position',[theLeft, theBottom, 150,20]);
0732     theLeft =OffsetX+116; theBottom =MarginY+180;
0733     uicontrol(theFig, 'Style','pushbutton', 'Units','pixels', ...
0734           'Callback', sprintf('rest_sliceviewer(''UnderlaySelection'', %g);',theFig) , ...
0735           'String', '...', 'FontWeight', 'bold', ...
0736           'Position',[theLeft, theBottom, 34,15]);
0737     %Add Overlay file selection directly
0738     theLeft =OffsetX; theBottom =MarginY+140;
0739     hOverlayRecent =uicontrol(theFig, 'Style','popupmenu', 'Units','pixels', ...
0740               'String', {'Overlay: '}, 'Value', 1, ...
0741               'Callback', sprintf('rest_sliceviewer(''ClickRecentOverlay'', %g);',theFig), ...
0742               'BackgroundColor', get(theFig,'Color'), ...              
0743               'Position',[theLeft, theBottom, 75,20]);     
0744     theLeft =OffsetX; theBottom =MarginY+120;
0745     hOverlayFile =uicontrol(theFig, 'Style','edit', 'Units','pixels', ...
0746                       'String', '', ...                      
0747                       'BackgroundColor', 'white', ...
0748                       'Callback', sprintf('rest_sliceviewer(''ChangeOverlay'', %g);',theFig), ...
0749                       'Position',[theLeft, theBottom, 150,20]);
0750     theLeft =OffsetX+116; theBottom =MarginY+140;
0751     uicontrol(theFig, 'Style','pushbutton', 'Units','pixels', ...
0752           'Callback', sprintf('rest_sliceviewer(''OverlaySelection'', %g);',theFig) , ...
0753           'String', '...','FontWeight', 'bold', ...
0754           'Position',[theLeft, theBottom, 34,15]); 
0755     %Add Overlay  Options, 20070913
0756     theLeft =OffsetX; theBottom =MarginY;
0757     hFrameOverlay=uicontrol(theFig, 'Style','Frame', 'Units','pixels', ...
0758                             'BackgroundColor', get(theFig,'Color'), ...
0759                             'Position', [theLeft,theBottom,150,100]);    
0760     hSeeOverlay =uicontrol(theFig, 'Style','checkbox', 'Units','pixels', ...
0761                     'String', 'See Overlay', ...
0762                     'Callback', sprintf('rest_sliceviewer(''Repaint'', %g);',theFig), ...
0763                     'BackgroundColor', get(theFig,'Color'), ...
0764                     'Position',[theLeft+35, theBottom+95, 80,15]);
0765     uicontrol(theFig, 'Style','text', 'Units','pixels', ...
0766             'String', 'Threshold', ...                                
0767              'BackgroundColor', get(theFig,'Color'), ...
0768             'Position',[theLeft+5, theBottom+75, 50,18]);
0769     hEdtThrdValue =uicontrol(theFig, 'Style','edit', 'Units','pixels', ...
0770                     'String', '', ...                    
0771                     'Callback', sprintf('rest_sliceviewer(''Overlay_SetThrdAbsValue'', %g);',theFig), ...    
0772                      'BackgroundColor', 'white', ...
0773                     'Position',[theLeft+75, theBottom+75, 70,18]);    
0774     
0775     hSliderThrdValue =uicontrol(theFig, 'Style','slider', 'Units','pixels', ...
0776                     'TooltipString', 'Absolute Value for thresholding the overlay', ...
0777                     'Callback', sprintf('rest_sliceviewer(''Overlay_SetThrdAbsValue'', %g);',theFig), ...
0778                     'BackgroundColor', get(theFig,'Color'), ...
0779                     'Position',[theLeft+5, theBottom+56, 140,15]);    
0780     uicontrol(theFig, 'Style','pushbutton', 'Units','pixels', ...
0781             'String', 'Cluster Size', ...
0782             'Callback', sprintf('rest_sliceviewer(''Overlay_SetThrdClusterSize'', %g);',theFig),...            
0783             'Position',[theLeft+75, theBottom+30, 70,24]);
0784     hOverlayMisc =uicontrol(theFig, 'Style','popupmenu', 'Units','pixels', ...
0785                     'String', {'Misc', 'Set Overlay''s Opacity', ...
0786                     'Set Range of Threshold', 'Set Label Color', 'Set Overlay''s Color bar','Save Image As','Correction Thresholds by AlphaSim'}, ... %YAN Chao-Gan 081223: add "save image as" function %YAN CHao-Gan 090401: add "Correction Thresholds by AlphaSim"
0787                     'Value', 1, ...
0788                     'BackgroundColor', get(theFig,'Color'), ...
0789                     'Enable', 'on', ...
0790                     'Callback', sprintf('rest_sliceviewer(''Overlay_Misc'', %g);',theFig), ...
0791                     'Position',[theLeft+5, theBottom+30, 70,24]);
0792     hTemplate =uicontrol(theFig, 'Style','popupmenu', 'Units','pixels', ...
0793                     'String', {'Template', 'Open AAL', 'Open Brodmann','Open Ch2'}, ...
0794                     'Value', 1, ...
0795                     'BackgroundColor', get(theFig,'Color'), ...
0796                     'Enable', 'on', ...
0797                     'Callback', sprintf('rest_sliceviewer(''Open_Template'', %g);',theFig), ...
0798                     'Position',[theLeft+5, theBottom+5, 70,24]);
0799     uicontrol(theFig, 'Style','pushbutton', 'Units','pixels', ...
0800             'String', 'Save2Mask', ...
0801             'Callback', sprintf('rest_sliceviewer(''CurrentCluster2Mask'', %g);',theFig),...            
0802             'Position',[theLeft+75, theBottom+5, 70,24]);
0803     % uicontrol(theFig, 'Style','pushbutton', 'Units','pixels', ...
0804             % 'String', 'Thrd2Mask', ...
0805             % 'Callback', sprintf('rest_sliceviewer(''Overlay_SetThrdClusterSize'', %g);',theFig),...
0806             % 'Position',[theLeft+75, theBottom+5, 70,24]);
0807             
0808     %Colorbar for overlay, do as AFNI, 20070921
0809     theAxesButtonDownFcn =sprintf('rest_sliceviewer(''ChangeColorElement'', %g);',theFig);
0810     hAxesColorbar =axes('Parent', theFig, 'Box', 'on', ...
0811                   'Units', 'pixel', 'DrawMode','fast', 'Visible', 'off', ...
0812                   'Position', [1 1 1 1], ...
0813                   'YDir','normal', 'XTickLabel',[],'XTick',[], ...
0814                   'YTickLabel',[],'YTick',[], ...
0815                   'ButtonDownFcn', theAxesButtonDownFcn);
0816     hImageColorbar =image('Tag','OverlayColorbar',  'Parent', hAxesColorbar);
0817     set(hAxesColorbar,'YDir','normal','ButtonDownFcn', theAxesButtonDownFcn, 'XTickLabel',[],'XTick',[], 'YTickLabel',[],'YTick',[]);
0818     
0819     clear theLeft theBottom;
0820         
0821     %Save to config
0822     AConfig.hFig            =theFig;            %handle of the config
0823     
0824     %Save parameters handles
0825     AConfig.hFrameSetPos   =hFrameSetPos;
0826     AConfig.hYoke            =hYoke;
0827     AConfig.hCrosshair       =hCrosshair;
0828     AConfig.hMagnify       =hMagnify;
0829     AConfig.hMniTal           =hMniTal;    
0830     AConfig.hEditPositionX =hEditPositionX;
0831     AConfig.hEditPositionY =hEditPositionY;
0832     AConfig.hEditPositionZ =hEditPositionZ;
0833     %Save Voxel intensity label handle
0834     AConfig.hVoxelIntensity=hVoxelIntensity;
0835     %Save message handle
0836     AConfig.hMsgLabel =hMsgLabel;
0837     AConfig.Message     ='';
0838     %Save Do Callback button's handle
0839     % AConfig.hDoCallbackBtn =hDoCallbackBtn;
0840             
0841     %Save important variables
0842     AConfig.Filename =AFilename;    %Default for underlay
0843     %AConfig.Callback =ACallback;    %Default for click callback
0844     %Callback define series, 20070924
0845     AConfig.Callback.ChangingPosition =ACallback;
0846     AConfig.Callback.Save2Mask ='';
0847     
0848     %View Mode, 20070911
0849     AConfig.ViewMode ='Orthogonal';    %Default View mode
0850     AConfig.ViewSeries =[];            %Default no any view series
0851     AConfig.Montage.Across =1;
0852     AConfig.Montage.Down   =1;
0853     AConfig.Montage.Spacing=3;
0854     AConfig.Montage.WantLabel=1;    
0855     
0856     %Underlay and Overlay, handles
0857     AConfig.hUnderlayFile =hUnderlayFile;
0858     AConfig.hUnderlayRecent =hUnderlayRecent;
0859     AConfig.hOverlayFile  =hOverlayFile;
0860     AConfig.hOverlayRecent =hOverlayRecent;
0861     
0862     AConfig.hSeeOverlay =hSeeOverlay;
0863     AConfig.hSliderThrdValue =hSliderThrdValue;
0864     AConfig.hEdtThrdValue =hEdtThrdValue;    
0865     AConfig.hOverlayMisc =hOverlayMisc;
0866     AConfig.hTemplate =hTemplate;    
0867     AConfig.hFrameOverlay  =hFrameOverlay;
0868     
0869     AConfig.hAxesColorbar  =hAxesColorbar;
0870     AConfig.hImageColorbar =hImageColorbar;    
0871     
0872     %Overlay Configuration
0873     %Data for Overlay
0874     AConfig.Overlay.Filename ='';
0875     AConfig.Overlay.Volume     =zeros(61, 73, 61);
0876     AConfig.Overlay.VolumeThrd =AConfig.Overlay.Volume;%Volume Thresholded by Cluster Size
0877     AConfig.Overlay.VoxelSize=[3 3 3];
0878     AConfig.Overlay.Origin     =[31 43 25];
0879     %Overlay's Info - statistics
0880     Result.Overlay.MinNegative =-Inf;
0881     Result.Overlay.MaxNegative =0;
0882     Result.Overlay.MinPositive =0;
0883     Result.Overlay.MaxPositive =Inf;
0884     Result.Overlay.AbsMin =0;
0885     Result.Overlay.AbsMax =Inf;
0886     %Options for Overlay
0887     AConfig.Overlay.Colormap    =jet(64);
0888     AConfig.Overlay.ColorbarCmd    ='jet(64)';    
0889     %[0 0 1;1 0 0];    %Pure Blue and Pure Red
0890     %[0 0 0.5625;0 0 0.875;0 0 1;1 0 0;0.875 0 0;0.5 0 0];
0891     AConfig.Overlay.Opacity  =1;    %Default, 50% Opacity
0892     AConfig.Overlay.LabelColor ='white';
0893     AConfig.Overlay.ValueThrdAbsolute =0; %Default, show all
0894     AConfig.Overlay.ValueThrdMin = -Inf; %Default, show all, not absolute, may be negative
0895     AConfig.Overlay.ValueThrdMax = Inf; %Default, show all, not absolute , may be negative, this allows me to set a range such as showing negative values only or positives only
0896     AConfig.Overlay.ValueThrdSeries = NaN; %Default, show all
0897     AConfig.Overlay.ClusterSizeThrd =0; %Default, 0 voxels, for not confining cluster-size
0898     AConfig.Overlay.ClusterRadiusThrd =0; %Default radius(mm) for Cluster size definition
0899     AConfig.Overlay.InfoAal='None';    %AAL descriptions
0900         
0901     %Load Recent Images/brains
0902     AConfig =InitRecent(AConfig);
0903     
0904     %Save Axes's handles
0905     AConfig.hAxesSagittal     =-1;
0906     AConfig.hAxesCoronal     =-1;
0907     AConfig.hAxesTransverse =-1;
0908     %Save Images' handles
0909     AConfig.hImageSagittal     =-1;
0910     AConfig.hImageCoronal      =-1;
0911     AConfig.hImageTransverse =-1;
0912     %Save Lines' handles
0913     AConfig.hXLineSagittal   =-1;        %x
0914     AConfig.hYLineSagittal   =-1;        %y
0915     AConfig.hXLineCoronal     =-1;        %x
0916     AConfig.hYLineCoronal     =-1;        %y
0917     AConfig.hXLineTransverse =-1;        %x
0918     AConfig.hYLineTransverse =-1;        %y
0919     AConfig.LastPosition =[90 126 72];    %Default
0920     AConfig.LastAxes     ='Transverse';    %For slice previous/next by pressing up/down left/right j/k ... on keyboard
0921     AConfig.LastSavedMask ='';            %For ROI define callback
0922     
0923     AConfig =InitUnderlay(AConfig);
0924     
0925     
0926     %Move Auto-Balance out of initialization just for speeding up for starting this slice-viewer
0927     %Save Maping Image parameters, Auto balance 20070911 revised
0928     % theSatMin=0; theSatMax =0; nBins=2^16;    %Satuation Min/Max
0929     % theMaxVal=max(AConfig.Volume(:));
0930     % if theMaxVal<257,
0931         % nBins =256;
0932     % else
0933         % nBins =theMaxVal;
0934     % end
0935     % theSum =histc(AConfig.Volume(:), [1:nBins]);
0936     % theSum =cumsum(theSum);
0937     % theCdf =theSum/theSum(end);
0938     % if rest_misc('GetMatlabVersion')>=7.3
0939         % idxSatMin =find(theCdf>0.01, 1, 'first');
0940         % idxSatMax =find(theCdf>=0.99, 1, 'first');
0941     % else
0942         % idxSatMin =find(theCdf>0.01);
0943         % idxSatMin =idxSatMin(1);
0944         % idxSatMax =find(theCdf>=0.99);
0945         % idxSatMax =idxSatMax(1);
0946     % end
0947     % idxSatMin =find(theCdf>0.01, 1, 'first');
0948     % idxSatMax =find(theCdf>=0.99, 1, 'first');
0949     % theSatMin =(idxSatMin-1)/(nBins-1) *theMaxVal;
0950     % theSatMax =(idxSatMax-1)/(nBins-1) *theMaxVal;
0951     % AConfig.Contrast.GrayDepth =256;
0952     % AConfig.Contrast.SatMax =theSatMax;
0953     % AConfig.Contrast.SatMin =theSatMin;
0954     %20070911, AutoBalance for contrast
0955     % AConfig.Contrast.WindowWidth =theSatMax -theSatMin;
0956     % AConfig.Contrast.WindowCenter=(theSatMax +theSatMin)/2;
0957     %For debugging, 20070911
0958     % disp(AConfig.Contrast);
0959     
0960         
0961     %%Update the figure, the follow function called order shouldn't change
0962     %Display Images
0963     AConfig =SetImage(AConfig);
0964     
0965     Result =AConfig;    
0966     return;
0967 
0968 function Result =DeleteFigure(AGlobalConfig, AFigHandle)
0969     x =ExistViewer(AGlobalConfig, AFigHandle);
0970     if x>0,            
0971         theDisplayCount =GetDisplayCount(AGlobalConfig);
0972         isExistFig =rest_misc( 'ForceCheckExistFigure' , AGlobalConfig.Config(x).hFig);
0973         if isExistFig,
0974             %Save the recent menu
0975             rest_sliceviewer('SaveRecent', AFigHandle);
0976             
0977             %Delete the figure and rearrange the queue
0978             delete(AGlobalConfig.Config(x).hFig);
0979             if theDisplayCount>x
0980                 for y=x:theDisplayCount-1
0981                     AGlobalConfig.Config(x) =AGlobalConfig.Config(x+1);
0982                 end
0983             end    
0984             AGlobalConfig.Config(theDisplayCount)=[];
0985         end    
0986     end
0987     Result =AGlobalConfig;
0988     
0989 function Result =GetDisplayCount(AGlobalConfig)
0990 %Get the Count of display, this program allow multi-view of brain like MRIcro
0991     if isempty(AGlobalConfig) || isempty(AGlobalConfig.Config),
0992         Result =0;        
0993     else
0994         Result =length(AGlobalConfig.Config);
0995     end
0996     return;
0997     
0998 function Result =ListViewerFigure(AGlobalConfig, AFilename)
0999     Result =[];
1000     if (isstruct(AGlobalConfig) && isstruct(AGlobalConfig.Config))
1001         for x=1:length(AGlobalConfig.Config)
1002             if strcmpi( AGlobalConfig.Config(x).Filename, AFilename)
1003                 Result =[Result; AGlobalConfig.Config(x).hFig];
1004             end
1005         end        
1006     else
1007         return;
1008     end    
1009     
1010 function Result =ExistViewer(AGlobalConfig, AFigureHandle)
1011     Result =0;
1012     if (isstruct(AGlobalConfig) && isstruct(AGlobalConfig.Config))
1013         for x=1:length(AGlobalConfig.Config)
1014             if AGlobalConfig.Config(x).hFig==AFigureHandle,
1015                 Result =x;
1016                 return;
1017             end
1018         end        
1019     else                
1020         return;
1021     end    
1022 
1023 function Result =SetImage(AConfig)
1024     if strcmpi(AConfig.ViewMode, 'Orthogonal'),
1025         Result =SetView_Orthogonal(AConfig);
1026     elseif strcmpi(AConfig.ViewMode, 'Transverse'),
1027         Result =SetView_Transverse(AConfig);
1028     elseif strcmpi(AConfig.ViewMode, 'Sagittal'),
1029         Result =SetView_Sagittal(AConfig);
1030     elseif strcmpi(AConfig.ViewMode, 'Coronal'),
1031         Result =SetView_Coronal(AConfig);
1032     end
1033     
1034     %Draw the color bar
1035     Result =DrawColorbar(Result);
1036     
1037     set(AConfig.hFig, 'Name', sprintf('Slice Viewer -- REST %s',rest_misc( 'GetRestVersion')));
1038     %Display Underlay Filename
1039     set(AConfig.hUnderlayFile, 'String', sprintf('%s', AConfig.Filename));
1040     %Display Overlay Filename
1041     set(AConfig.hOverlayFile, 'String', sprintf('%s', AConfig.Overlay.Filename));
1042     
1043     %Show Voxel's position [x y z]
1044     ShowPositionInEdit(AConfig);    
1045     %Update the message
1046     SetMessage(AConfig);    
1047     %Resize figure width and height
1048     ResizeFigure(AConfig);
1049     
1050     
1051 function Result =SetView_Orthogonal(AConfig)    
1052     %Underlay Image manuplication, 20070913
1053     theSagittalImg =GetGrayImage('Sagittal', AConfig.Volume, AConfig.LastPosition(1));    %x
1054     theCoronalImg =GetGrayImage('Coronal', AConfig.Volume, AConfig.LastPosition(2));        %y
1055     theTransverseImg =GetGrayImage('Transverse', AConfig.Volume, AConfig.LastPosition(3));%z
1056     
1057     %Auto balance
1058     theSagittalImg =SaturateContrast(theSagittalImg, AConfig.Contrast.SatMin, AConfig.Contrast.SatMax);
1059     theCoronalImg =SaturateContrast(theCoronalImg, AConfig.Contrast.SatMin, AConfig.Contrast.SatMax);
1060     theTransverseImg =SaturateContrast(theTransverseImg, AConfig.Contrast.SatMin, AConfig.Contrast.SatMax);
1061     
1062     %Calculate the Result Image after Magnifying
1063     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);
1064     if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1, 
1065         if rest_misc('GetMatlabVersion')>=7.4   %YAN Chao-Gan 090401: The imresize function has been completely rewritten in Matlab R2007a. Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version.
1066             theSagittalImg    =imresize_old(theSagittalImg, theMagnifyCoefficient);
1067             theCoronalImg    =imresize_old(theCoronalImg, theMagnifyCoefficient);
1068             theTransverseImg=imresize_old(theTransverseImg, theMagnifyCoefficient);
1069         else
1070             theSagittalImg    =imresize(theSagittalImg, theMagnifyCoefficient);
1071             theCoronalImg    =imresize(theCoronalImg, theMagnifyCoefficient);
1072             theTransverseImg=imresize(theTransverseImg, theMagnifyCoefficient);
1073         end
1074     end    
1075     
1076     % Revise the Axes position to make it comfort to Magnify
1077     theFramePosParamSet =get(AConfig.hFrameSetPos, 'Position');
1078     theLeft     =theFramePosParamSet(1) +theFramePosParamSet(3) +5;
1079     theBottom     =10; %theFramePosParamSet(2);
1080     theLeftTransverse =theLeft;
1081     theLeftCoronal       =theLeftTransverse;
1082     theLeftSagittal   =theLeftCoronal  +size(theCoronalImg,2)+    2;
1083     theBottomTransverse =theBottom;
1084     theBottomCoronal    =theBottomTransverse +size(theTransverseImg,1) +2;
1085     theBottomSagittal    =theBottomCoronal;
1086     
1087     thePosTransverse     =[theLeftTransverse, theBottomTransverse, size(theTransverseImg,2), size(theTransverseImg,1)];
1088     thePosCoronal        =[theLeftCoronal, theBottomCoronal, size(theCoronalImg,2), size(theCoronalImg,1)];
1089     thePosSagittal        =[theLeftSagittal, theBottomSagittal, size(theSagittalImg,2), size(theSagittalImg,1)];
1090     clear theFramePosParamSet theLeft theBottom 
1091     clear theLeftTransverse theLeftCoronal theLeftSagittal
1092     clear theBottomTransverse theBottomCoronal theBottomSagittal
1093     
1094     % Show Images
1095     %Clear Text labels first
1096     ClearTextLabels(AConfig);    
1097     
1098     %Set Default color map for only Underlay
1099     %colormap(gray(AConfig.Contrast.GrayDepth));
1100     %Map images to true color
1101     theSagittalImg =repmat(theSagittalImg, [1 1 3]);
1102     theCoronalImg =repmat(theCoronalImg, [1 1 3]);
1103     theTransverseImg =repmat(theTransverseImg, [1 1 3]);
1104     
1105     %Add Overlay Images
1106     if SeeOverlay(AConfig),
1107         theSagittalImg =AddOverlay('Sagittal' ,AConfig, theSagittalImg);
1108         theCoronalImg =AddOverlay('Coronal', AConfig, theCoronalImg);
1109         theTransverseImg =AddOverlay('Transverse', AConfig, theTransverseImg);
1110     end
1111     
1112     %Sagittal
1113     set(AConfig.hImageSagittal, 'CData', (theSagittalImg), 'HitTest', 'off','Visible', 'on');    
1114     set(AConfig.hAxesSagittal,'Visible', 'on', ...
1115         'XLim', [1 size(theSagittalImg,2)], ...
1116         'YLim', [1 size(theSagittalImg,1)] , ...
1117         'Position', thePosSagittal);
1118     set(AConfig.hXLineSagittal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1119         'XData', [1 size(theSagittalImg,2)] , ...
1120         'YData', [1 1]*AConfig.LastPosition(3) * theMagnifyCoefficient);%Parallel to X-axis
1121     set(AConfig.hYLineSagittal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1122         'XData', [1 1]*AConfig.LastPosition(2) * theMagnifyCoefficient, ...
1123         'YData', [1 size(theSagittalImg,1)] );%Parallel to Y-axis
1124     
1125     %Coronal
1126     set(AConfig.hImageCoronal, 'CData', (theCoronalImg), 'HitTest', 'off','Visible', 'on');
1127     %colormap(gray(AConfig.Contrast.GrayDepth));
1128     set(AConfig.hAxesCoronal, 'Visible', 'on',...
1129         'XLim', [1 size(theCoronalImg,1)], ...
1130         'YLim', [1 size(theCoronalImg,2)], ...
1131         'Position', thePosCoronal);
1132     set(AConfig.hXLineCoronal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1133         'XData', [1 size(theCoronalImg,2)] , ...
1134         'YData', [1 1]*AConfig.LastPosition(3) * theMagnifyCoefficient );%Parallel to X-axis
1135     set(AConfig.hYLineCoronal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1136         'XData', [1 1]*AConfig.LastPosition(1) * theMagnifyCoefficient , ...
1137         'YData', [1 size(theCoronalImg,1)] );%Parallel to Y-axis
1138     
1139     %Transverse
1140     set(AConfig.hImageTransverse, 'CData', (theTransverseImg), 'HitTest', 'off','Visible', 'on');
1141     % colormap(gray(AConfig.Contrast.GrayDepth));
1142     set(AConfig.hAxesTransverse,'Visible', 'on', ...
1143         'XLim', [1 size(theTransverseImg,2)], ...
1144         'YLim', [1 size(theTransverseImg,1)], ...
1145         'Position', thePosTransverse);
1146     set(AConfig.hXLineTransverse, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1147         'XData', [1 size(theTransverseImg,2)] , ...
1148         'YData', [1 1]*AConfig.LastPosition(2) * theMagnifyCoefficient );%Parallel to X-axis
1149     set(AConfig.hYLineTransverse, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1150         'XData', [1 1]*AConfig.LastPosition(1) * theMagnifyCoefficient , ...
1151         'YData', [1 size(theTransverseImg,1)] );%Parallel to Y-axis
1152     
1153     %Reset View Series
1154     AConfig.ViewSeries =[];
1155     Result =AConfig;
1156 
1157 function Result =SetView_Transverse(AConfig)
1158     [nDim1 nDim2 nDim3] =size(AConfig.Volume);
1159     theCenterZ =AConfig.LastPosition(3);
1160     theCount   =AConfig.Montage.Across *AConfig.Montage.Down ;
1161     
1162     theZSeries =theCenterZ -([(floor(theCount/2)) : -1 :(ceil(-theCount/2))]) *AConfig.Montage.Spacing;
1163     while ~isempty(find(theZSeries<=0)),
1164         theZSeries(find(theZSeries<=0)) = theZSeries(find(theZSeries<=0)) +nDim3;
1165     end
1166     while ~isempty(find(theZSeries>nDim3)),
1167         theZSeries(find(theZSeries>nDim3)) = theZSeries(find(theZSeries>nDim3)) -nDim3;
1168     end
1169     
1170     theTransverseImg = zeros(nDim2 * AConfig.Montage.Down, nDim1 *AConfig.Montage.Across);
1171     for theRow=AConfig.Montage.Down:-1:1,
1172         for theCol=1:AConfig.Montage.Across,
1173             %I don't draw the last image because it is used to indicate the positions
1174             theZIndex = theZSeries((theRow-1)*AConfig.Montage.Across +theCol);
1175             theTransverseImg((AConfig.Montage.Down-theRow)*nDim2 +(1:nDim2), (theCol-1)*nDim1+(1:nDim1)) =GetGrayImage('Transverse', AConfig.Volume, theZIndex);
1176             %YAN Chao-Gan 081229 theTransverseImg((theRow-1)*nDim2 +(1:nDim2), (theCol-1)*nDim1+(1:nDim1)) =GetGrayImage('Transverse', AConfig.Volume, theZIndex);
1177             %Write the Z Coordinates to the left-down corner
1178             %I have to move this code to the end of Setting Axis by using TEXT function
1179             
1180             %Save the Center image's Row and Col for CrossHair-line displaying
1181             if theZIndex==theCenterZ,
1182                 theCenterZ_Row =theRow;
1183                 theCenterZ_Col =theCol;
1184             end
1185         end
1186     end        
1187 
1188     %Save View Series
1189     AConfig.ViewSeries = theZSeries;
1190     %Auto balance
1191     theTransverseImg =SaturateContrast(theTransverseImg, AConfig.Contrast.SatMin, AConfig.Contrast.SatMax);
1192     
1193     %Calculate the Result Image after Magnifying
1194     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);
1195     if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1,         
1196         if rest_misc('GetMatlabVersion')>=7.4   %YAN Chao-Gan 090401: The imresize function has been completely rewritten in Matlab R2007a. Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version.
1197             theTransverseImg=imresize_old(theTransverseImg, theMagnifyCoefficient);
1198         else
1199             theTransverseImg=imresize(theTransverseImg, theMagnifyCoefficient);
1200         end
1201     end
1202     
1203     % Revise the Axes position to make it comfort to Magnify
1204     theFramePosParamSet =get(AConfig.hFrameSetPos, 'Position');
1205     theLeft     =theFramePosParamSet(1) +theFramePosParamSet(3) +5;
1206     theBottom     =10; %theFramePosParamSet(2);
1207     thePosTransverse     =[theLeft, theBottom, size(theTransverseImg,2), size(theTransverseImg,1)];
1208     
1209     %Map images to true color
1210     theTransverseImg =repmat(theTransverseImg, [1 1 3]);
1211     
1212     %Add overlay
1213     if SeeOverlay(AConfig),
1214         theTransverseImg =AddOverlaySeries(AConfig, theTransverseImg);
1215     end
1216     
1217     % Show Images
1218     %Sagittal
1219     set(AConfig.hAxesSagittal, 'Visible','off');
1220     set(AConfig.hImageSagittal,'Visible','off');
1221     set(AConfig.hXLineSagittal, 'Visible','off');
1222     set(AConfig.hYLineSagittal, 'Visible','off');    
1223     %Coronal
1224     set(AConfig.hAxesCoronal, 'Visible','off');
1225     set(AConfig.hImageCoronal,'Visible','off');
1226     set(AConfig.hXLineCoronal, 'Visible','off');
1227     set(AConfig.hYLineCoronal, 'Visible','off');    
1228     
1229     %Transverse
1230     %theTransverseImg =repmat(theTransverseImg, [1, 1, 3])/AConfig.Contrast.GrayDepth; % For true color display
1231     set(AConfig.hImageTransverse, 'CData', (theTransverseImg), 'HitTest', 'off', 'Visible','on');
1232     %colormap(gray(AConfig.Contrast.GrayDepth));
1233     set(AConfig.hAxesTransverse, 'Visible','on', ...
1234         'XLim', [1 size(theTransverseImg,2)], ...
1235         'YLim', [1 size(theTransverseImg,1)], ...
1236         'Position', thePosTransverse);    
1237     set(AConfig.hXLineTransverse, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1238         'XData', ([1 nDim1] +(theCenterZ_Col-1)*nDim1 )* theMagnifyCoefficient, ...
1239         'YData', ([1 1]*AConfig.LastPosition(2) + (theCenterZ_Row-1)*nDim2) *theMagnifyCoefficient);%Parallel to X-axis
1240     set(AConfig.hYLineTransverse, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1241         'XData', ([1 1]*AConfig.LastPosition(1)+(theCenterZ_Col-1)*nDim1) * theMagnifyCoefficient , ...
1242         'YData', ([1 nDim2]+(theCenterZ_Row-1)*nDim2)* theMagnifyCoefficient );%Parallel to Y-axis
1243     
1244     
1245     %Clear Text labels first
1246     ClearTextLabels(AConfig);
1247     
1248     %Write text label to indicate the Z value
1249     if AConfig.Montage.WantLabel,
1250         for theRow=AConfig.Montage.Down:-1:1,
1251             for theCol=1:AConfig.Montage.Across,
1252                 %I don't draw the last image because it is used to indicate the positions
1253                 theZIndex = theZSeries((theRow-1)*AConfig.Montage.Across +theCol);
1254                 theZIndex = theZIndex -AConfig.Origin(3);
1255                                                 
1256                 %Transform to Physical distance 20071102
1257                 theZIndex = AConfig.VoxelSize(3) *theZIndex;
1258                         
1259                 
1260                 theY =(AConfig.Montage.Down-theRow+1)*nDim2* theMagnifyCoefficient;
1261                 %YAN Chao-Gan 081229 theY =(theRow)*nDim2* theMagnifyCoefficient;
1262                 theX =(theCol-1)*nDim1* theMagnifyCoefficient;
1263                 
1264                 text( theX,theY,sprintf('%+gmm',theZIndex), 'Parent', AConfig.hAxesTransverse, 'Color', AConfig.Overlay.LabelColor, 'HitTest', 'off', 'VerticalAlignment', 'top', 'Units', 'pixels');            
1265             end
1266         end    
1267     end
1268     
1269     Result =AConfig;
1270     
1271 function Result =SetView_Sagittal(AConfig)
1272     [nDim1 nDim2 nDim3] =size(AConfig.Volume);
1273     theCenterX =AConfig.LastPosition(1);
1274     theCount   =AConfig.Montage.Across *AConfig.Montage.Down ;
1275     
1276     theXSeries =theCenterX -([floor(theCount/2) : -1 :ceil(-theCount/2)]) *AConfig.Montage.Spacing;    
1277     while ~isempty(find(theXSeries<=0)),
1278         theXSeries(find(theXSeries<=0)) = theXSeries(find(theXSeries<=0)) +nDim1;
1279     end
1280     while ~isempty(find(theXSeries>nDim1)),
1281         theXSeries(find(theXSeries>nDim1)) = theXSeries(find(theXSeries>nDim1)) -nDim1;
1282     end
1283     
1284     theSagittalImg = zeros(nDim3 * AConfig.Montage.Down, nDim2 *AConfig.Montage.Across);
1285     for theRow=AConfig.Montage.Down:-1:1,
1286         for theCol=1:AConfig.Montage.Across,
1287             %I don't draw the last image because it is used to indicate the positions
1288             theXIndex = theXSeries((theRow-1)*AConfig.Montage.Across +theCol);
1289             theSagittalImg((theRow-1)*nDim3 +(1:nDim3), (theCol-1)*nDim2+(1:nDim2)) =GetGrayImage('Sagittal', AConfig.Volume, theXIndex);
1290             %Write the X Coordinates to the left-down corner
1291             %I have to move this code to the end of Setting Axis by using TEXT function
1292             
1293             %Save the Center image's Row and Col for CrossHair-line displaying
1294             if theXIndex==theCenterX,
1295                 theCenterX_Row =theRow;
1296                 theCenterX_Col =theCol;
1297             end
1298         end
1299     end        
1300     %Save View Series
1301     AConfig.ViewSeries = theXSeries;
1302     %Auto balance
1303     theSagittalImg =SaturateContrast(theSagittalImg, AConfig.Contrast.SatMin, AConfig.Contrast.SatMax);
1304     
1305     %Calculate the Result Image after Magnifying
1306     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);
1307     if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1,         
1308         if rest_misc('GetMatlabVersion')>=7.4   %YAN Chao-Gan 090401: The imresize function has been completely rewritten in Matlab R2007a. Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version.
1309             theSagittalImg=imresize_old(theSagittalImg, theMagnifyCoefficient);
1310         else
1311             theSagittalImg=imresize(theSagittalImg, theMagnifyCoefficient);
1312         end
1313     end
1314     
1315     % Revise the Axes position to make it comfort to Magnify
1316     theFramePosParamSet =get(AConfig.hFrameSetPos, 'Position');
1317     theLeft     =theFramePosParamSet(1) +theFramePosParamSet(3) +5;
1318     theBottom     =10; %theFramePosParamSet(2);
1319     thePosSagittal     =[theLeft, theBottom, size(theSagittalImg,2), size(theSagittalImg,1)];
1320     
1321     %Map images to true color
1322     theSagittalImg =repmat(theSagittalImg, [1 1 3]);
1323     
1324     %Add overlay
1325     if SeeOverlay(AConfig),
1326         theSagittalImg =AddOverlaySeries(AConfig, theSagittalImg);    
1327     end
1328     
1329     % Show Images
1330     %Transverse
1331     set(AConfig.hAxesTransverse, 'Visible','off');
1332     set(AConfig.hImageTransverse,'Visible','off');
1333     set(AConfig.hXLineTransverse, 'Visible','off');
1334     set(AConfig.hYLineTransverse, 'Visible','off');
1335     %Coronal
1336     set(AConfig.hAxesCoronal, 'Visible','off');
1337     set(AConfig.hImageCoronal,'Visible','off');
1338     set(AConfig.hXLineCoronal, 'Visible','off');
1339     set(AConfig.hYLineCoronal, 'Visible','off');    
1340     
1341     %Transverse
1342     %theTransverseImg =repmat(theTransverseImg, [1, 1, 3])/AConfig.Contrast.GrayDepth; % For true color display
1343     set(AConfig.hImageSagittal, 'CData', (theSagittalImg), 'HitTest', 'off', 'Visible','on');
1344     %colormap(gray(AConfig.Contrast.GrayDepth));
1345     set(AConfig.hAxesSagittal, 'Visible','on', ...
1346         'XLim', [1 size(theSagittalImg,2)], ...
1347         'YLim', [1 size(theSagittalImg,1)], ...
1348         'Position', thePosSagittal);    
1349     set(AConfig.hXLineSagittal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1350         'XData', ([1 nDim2] +(theCenterX_Col-1)*nDim2 )* theMagnifyCoefficient, ...
1351         'YData', ([1 1]*AConfig.LastPosition(3) + (theCenterX_Row-1)*nDim3) *theMagnifyCoefficient);%Parallel to X-axis
1352     set(AConfig.hYLineSagittal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1353         'XData', ([1 1]*AConfig.LastPosition(2)+(theCenterX_Col-1)*nDim2) * theMagnifyCoefficient , ...
1354         'YData', ([1 nDim3]+(theCenterX_Row-1)*nDim3)* theMagnifyCoefficient );%Parallel to Y-axis
1355         
1356     %Clear Text labels first
1357     ClearTextLabels(AConfig);    
1358     %Write text label to indicate the Z value
1359     if AConfig.Montage.WantLabel,
1360         for theRow=AConfig.Montage.Down:-1:1,
1361             for theCol=1:AConfig.Montage.Across,                            
1362                 theXIndex = theXSeries((theRow-1)*AConfig.Montage.Across +theCol);
1363                 theXIndex = theXIndex -AConfig.Origin(1);
1364                 
1365                 %Transform to Physical distance 20071102
1366                 theXIndex = AConfig.VoxelSize(1) *theXIndex;
1367                 %Dawnsong 20071102 Revise to make sure the left image/Right brain is +
1368                 theXIndex =(-1) *theXIndex;
1369                             
1370                 
1371                 theY =(theRow)*nDim3* theMagnifyCoefficient;
1372                 theX =(theCol-1)*nDim2* theMagnifyCoefficient;
1373                 text( theX,theY,sprintf('%+gmm',theXIndex), 'Parent', AConfig.hAxesSagittal, 'Color', AConfig.Overlay.LabelColor, 'HitTest', 'off', 'VerticalAlignment', 'top', 'Units', 'pixels');            
1374             end
1375         end    
1376     end
1377             
1378     Result =AConfig;
1379     
1380 function Result =SetView_Coronal(AConfig)
1381     [nDim1 nDim2 nDim3] =size(AConfig.Volume);
1382     theCenterY =AConfig.LastPosition(2);
1383     theCount   =AConfig.Montage.Across *AConfig.Montage.Down ;
1384     
1385     theYSeries =theCenterY -([floor(theCount/2) : -1 :ceil(-theCount/2)]) *AConfig.Montage.Spacing;    
1386     while ~isempty(find(theYSeries<=0)),
1387         theYSeries(find(theYSeries<=0)) = theYSeries(find(theYSeries<=0)) +nDim2;
1388     end
1389     while ~isempty(find(theYSeries>nDim2)),
1390         theYSeries(find(theYSeries>nDim2)) = theYSeries(find(theYSeries>nDim2)) -nDim2;
1391     end
1392     
1393     theCoronalImg = zeros(nDim3 * AConfig.Montage.Down, nDim1 *AConfig.Montage.Across);
1394     for theRow=AConfig.Montage.Down:-1:1,
1395         for theCol=1:AConfig.Montage.Across,
1396             %I don't draw the last image because it is used to indicate the positions
1397             theYIndex = theYSeries((theRow-1)*AConfig.Montage.Across +theCol);
1398             theCoronalImg((theRow-1)*nDim3 +(1:nDim3), (theCol-1)*nDim1+(1:nDim1)) =GetGrayImage('Coronal', AConfig.Volume, theYIndex);
1399             %Write the Z Coordinates to the left-down corner
1400             %I have to move this code to the end of Setting Axis by using TEXT function
1401             
1402             %Save the Center image's Row and Col for CrossHair-line displaying
1403             if theYIndex==theCenterY,
1404                 theCenterY_Row =theRow;
1405                 theCenterY_Col =theCol;
1406             end
1407         end
1408     end            
1409     %Save View Series
1410     AConfig.ViewSeries = theYSeries;
1411     %Auto balance
1412     theCoronalImg =SaturateContrast(theCoronalImg, AConfig.Contrast.SatMin, AConfig.Contrast.SatMax);
1413     
1414     %Calculate the Result Image after Magnifying
1415     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);
1416     if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1,         
1417         if rest_misc('GetMatlabVersion')>=7.4   %YAN Chao-Gan 090401: The imresize function has been completely rewritten in Matlab R2007a. Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version.
1418             theCoronalImg=imresize_old(theCoronalImg, theMagnifyCoefficient);
1419         else
1420             theCoronalImg=imresize(theCoronalImg, theMagnifyCoefficient);
1421         end
1422     end
1423     
1424     % Revise the Axes position to make it comfort to Magnify
1425     theFramePosParamSet =get(AConfig.hFrameSetPos, 'Position');
1426     theLeft     =theFramePosParamSet(1) +theFramePosParamSet(3) +5;
1427     theBottom     =10; %theFramePosParamSet(2);
1428     thePosCoronal     =[theLeft, theBottom, size(theCoronalImg,2), size(theCoronalImg,1)];
1429     
1430     %Map images to true color
1431     theCoronalImg =repmat(theCoronalImg, [1 1 3]);
1432     
1433     %Add overlay
1434     if SeeOverlay(AConfig),
1435         theCoronalImg =AddOverlaySeries(AConfig, theCoronalImg);    
1436     end
1437     
1438     % Show Images
1439     %Transverse
1440     set(AConfig.hAxesTransverse, 'Visible','off');
1441     set(AConfig.hImageTransverse,'Visible','off');
1442     set(AConfig.hXLineTransverse, 'Visible','off');
1443     set(AConfig.hYLineTransverse, 'Visible','off');
1444     %Sagittal
1445     set(AConfig.hAxesSagittal, 'Visible','off');
1446     set(AConfig.hImageSagittal,'Visible','off');
1447     set(AConfig.hXLineSagittal, 'Visible','off');
1448     set(AConfig.hYLineSagittal, 'Visible','off');
1449         
1450     %Transverse
1451     %theTransverseImg =repmat(theTransverseImg, [1, 1, 3])/AConfig.Contrast.GrayDepth; % For true color display
1452     set(AConfig.hImageCoronal, 'CData', (theCoronalImg), 'HitTest', 'off', 'Visible','on');
1453     %colormap(gray(AConfig.Contrast.GrayDepth));
1454     set(AConfig.hAxesCoronal, 'Visible','on', ...
1455         'XLim', [1 size(theCoronalImg,2)], ...
1456         'YLim', [1 size(theCoronalImg,1)], ...
1457         'Position', thePosCoronal);    
1458     
1459     set(AConfig.hXLineCoronal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1460         'XData', ([1 nDim1] +(theCenterY_Col-1)*nDim1 )* theMagnifyCoefficient, ...
1461         'YData', ([1 1]*AConfig.LastPosition(3) + (theCenterY_Row-1)*nDim3) *theMagnifyCoefficient);%Parallel to X-axis
1462     set(AConfig.hYLineCoronal, 'HitTest','off','Visible', IsCrosshairChecked(AConfig), ...        
1463         'XData', ([1 1]*AConfig.LastPosition(1)+(theCenterY_Col-1)*nDim1) * theMagnifyCoefficient , ...
1464         'YData', ([1 nDim3]+(theCenterY_Row-1)*nDim3)* theMagnifyCoefficient );%Parallel to Y-axis
1465         
1466     %Clear Text labels first
1467     ClearTextLabels(AConfig);    
1468     %Write text label to indicate the Z value
1469     if AConfig.Montage.WantLabel,
1470         for theRow=AConfig.Montage.Down:-1:1,
1471             for theCol=1:AConfig.Montage.Across,
1472                 %I don't draw the last image because it is used to indicate the positions
1473                 theYIndex = theYSeries((theRow-1)*AConfig.Montage.Across +theCol);
1474                 theYIndex = theYIndex -AConfig.Origin(2);
1475                                 
1476                 %Transform to Physical distance 20071102
1477                 theYIndex = AConfig.VoxelSize(2) *theYIndex;
1478                                         
1479                 
1480                 theY =theRow*nDim3* theMagnifyCoefficient;
1481                 theX =(theCol-1)*nDim1* theMagnifyCoefficient;
1482                 text( theX,theY,sprintf('%+gmm',theYIndex), 'Parent', AConfig.hAxesCoronal, 'Color', AConfig.Overlay.LabelColor, 'HitTest', 'off', 'VerticalAlignment', 'top', 'Units', 'pixels');            
1483             end
1484         end    
1485     end
1486     Result =AConfig;
1487     
1488 function Result =GetGrayImage(AType, AVolume, APosition)
1489 %Return raw image data at specific position in the Volume
1490     if nargin~=3, error('Result =GetGrayImage(AVolume, AType)'); end
1491     switch lower(AType)
1492     case 'sagittal',
1493         Result =squeeze(AVolume(APosition, :, :));
1494     case 'coronal',
1495         Result =squeeze(AVolume(:,APosition, :));
1496     case 'transverse',
1497         Result =squeeze(AVolume(:, :, APosition));
1498     otherwise
1499     end
1500     Result =Result';
1501     
1502 function Result =ClickPositionCrossHair(AConfig)
1503     theFig             =AConfig.hFig;
1504     hAxesSagittal     =AConfig.hAxesSagittal;
1505     hAxesCoronal     =AConfig.hAxesCoronal;
1506     hAxesTransverse =AConfig.hAxesTransverse;
1507     theAxes            =get(theFig, 'CurrentObject');
1508     %Check legal click point in the axes
1509     thePoint        =get(theAxes,'CurrentPoint');
1510     thePoint         =thePoint(1, 1:2);
1511     theXLim =get(theAxes, 'XLim');
1512     theYLim =get(theAxes, 'YLim');    
1513     if thePoint(1)<theXLim(1) || thePoint(1)>theXLim(2) ...
1514        || thePoint(2)<theYLim(1) || thePoint(2)>theYLim(2) ,
1515         Result =AConfig;
1516         return;
1517     end    
1518     
1519     thePosition        =AConfig.LastPosition; 
1520     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);    
1521     switch theAxes,
1522     case hAxesSagittal,
1523         thePosition(2) =round(thePoint(1));% x is Y
1524         thePosition(3) =round(thePoint(2));%y is Z
1525         %Calculate the Result Position after Magnifying
1526         if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1, 
1527             thePosition(2) =round(thePosition(2) / theMagnifyCoefficient);        
1528             thePosition(3) =round(thePosition(3) / theMagnifyCoefficient);        
1529         end
1530     case hAxesCoronal,
1531         thePosition(1) =round(thePoint(1));%x is X
1532         thePosition(3) =round(thePoint(2));%x is Z
1533         %Calculate the Result Position after Magnifying
1534         if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1, 
1535             thePosition(1) =round(thePosition(1) / theMagnifyCoefficient);        
1536             thePosition(3) =round(thePosition(3) / theMagnifyCoefficient);        
1537         end
1538     case hAxesTransverse,
1539         thePosition(1) =round(thePoint(1));%x is  X
1540         thePosition(2) =round(thePoint(2));%y is Y
1541         %Calculate the Result Position after Magnifying
1542         if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1, 
1543             thePosition(1) =round(thePosition(1) / theMagnifyCoefficient);        
1544             thePosition(2) =round(thePosition(2) / theMagnifyCoefficient);        
1545         end
1546     otherwise
1547         error(sprintf('Error call: It must be called by Axes''s ButtonDownFcn\nWhy did this occur?\nThere must be something wrong.\nrun "clear all" or re-start MATLAB to avoid this error.\n Dawnwei.song 20070526'));
1548     end
1549     
1550     % AConfig.LastPosition =thePosition;
1551     AConfig =UpdatePosition(AConfig, thePosition);
1552     %Display Images
1553     AConfig =SetImage(AConfig);
1554     
1555     Result =AConfig;
1556     
1557 function Result =ClickPositionInSagittalMode(AConfig)
1558     theFig             =AConfig.hFig;
1559     [nDim1 nDim2 nDim3] =size(AConfig.Volume);
1560     theAxes            =get(theFig, 'CurrentObject');
1561     %Check legal click point in the axes
1562     thePoint        =get(theAxes,'CurrentPoint');
1563     thePoint         =round(thePoint(1, 1:2));
1564     theXLim =get(theAxes, 'XLim');
1565     theYLim =get(theAxes, 'YLim');    
1566     if thePoint(1)<theXLim(1) || thePoint(1)>theXLim(2) ...
1567        || thePoint(2)<theYLim(1) || thePoint(2)>theYLim(2) ,
1568         Result =AConfig;
1569         return;
1570     end    
1571     
1572     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);
1573     thePosition        =AConfig.LastPosition; 
1574     thePosition(2)  =mod(thePoint(1), nDim2* theMagnifyCoefficient);% x is Y
1575     thePosition(3)  =mod(thePoint(2), nDim3* theMagnifyCoefficient);%y is Z
1576         
1577     theSeries_RowId =ceil(thePoint(2)/ (theYLim(2)/AConfig.Montage.Down));
1578     theSeries_ColId =ceil(thePoint(1)/ (theXLim(2)/AConfig.Montage.Across));
1579     thePointId_inSeries =(theSeries_RowId -1)*AConfig.Montage.Across +theSeries_ColId;
1580     
1581     %Calculate the Result Position after Magnifying
1582     if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1, 
1583         thePosition(2) =round(thePosition(2) / theMagnifyCoefficient);        
1584         thePosition(3) =round(thePosition(3) / theMagnifyCoefficient);        
1585         theXLim        =round(theXLim /theMagnifyCoefficient);
1586         theYLim        =round(theYLim /theMagnifyCoefficient);
1587     end        
1588     
1589     %Set the real position
1590     thePosition(1) = AConfig.ViewSeries(thePointId_inSeries);    
1591     % AConfig.LastPosition =thePosition;
1592     AConfig =UpdatePosition(AConfig, thePosition);
1593     
1594     %Display Images
1595     AConfig =SetImage(AConfig);    
1596     
1597     Result =AConfig;
1598     
1599 function Result =ClickPositionInCoronalMode(AConfig)
1600     theFig             =AConfig.hFig;
1601     [nDim1 nDim2 nDim3] =size(AConfig.Volume);
1602     theAxes            =get(theFig, 'CurrentObject');
1603     %Check legal click point in the axes
1604     thePoint        =get(theAxes,'CurrentPoint');
1605     thePoint         =round(thePoint(1, 1:2));
1606     theXLim =get(theAxes, 'XLim');
1607     theYLim =get(theAxes, 'YLim');    
1608     if thePoint(1)<theXLim(1) || thePoint(1)>theXLim(2) ...
1609        || thePoint(2)<theYLim(1) || thePoint(2)>theYLim(2) ,
1610         Result =AConfig;
1611         return;
1612     end    
1613     
1614     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);
1615     thePosition        =AConfig.LastPosition; 
1616     thePosition(1)  =mod(thePoint(1), nDim1* theMagnifyCoefficient);% x is Y
1617     thePosition(3)  =mod(thePoint(2), nDim3* theMagnifyCoefficient);%y is Z
1618     
1619     
1620     theSeries_RowId =ceil(thePoint(2)/ (theYLim(2)/AConfig.Montage.Down));
1621     theSeries_ColId =ceil(thePoint(1)/ (theXLim(2)/AConfig.Montage.Across));
1622     thePointId_inSeries =(theSeries_RowId -1)*AConfig.Montage.Across +theSeries_ColId;
1623     
1624     %Calculate the Result Position after Magnifying
1625     if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1, 
1626         thePosition(1) =round(thePosition(1) / theMagnifyCoefficient);        
1627         thePosition(3) =round(thePosition(3) / theMagnifyCoefficient);        
1628         theXLim        =round(theXLim /theMagnifyCoefficient);
1629         theYLim        =round(theYLim /theMagnifyCoefficient);
1630     end        
1631     
1632     %Set the real position
1633     thePosition(2) = AConfig.ViewSeries(thePointId_inSeries);    
1634     % AConfig.LastPosition =thePosition;
1635     AConfig =UpdatePosition(AConfig, thePosition);
1636     
1637     %Display Images
1638     AConfig =SetImage(AConfig);    
1639     
1640     Result =AConfig;    
1641     
1642 function Result =ClickPositionInTransverseMode(AConfig)
1643     theFig             =AConfig.hFig;
1644     [nDim1 nDim2 nDim3] =size(AConfig.Volume);
1645     theAxes            =get(theFig, 'CurrentObject');
1646     %Check legal click point in the axes
1647     thePoint        =get(theAxes,'CurrentPoint');
1648     thePoint         =round(thePoint(1, 1:2));
1649     theXLim =get(theAxes, 'XLim');
1650     theYLim =get(theAxes, 'YLim');    
1651     if thePoint(1)<theXLim(1) || thePoint(1)>theXLim(2) ...
1652        || thePoint(2)<theYLim(1) || thePoint(2)>theYLim(2) ,
1653         Result =AConfig;
1654         return;
1655     end    
1656     
1657     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig);
1658     thePosition        =AConfig.LastPosition; 
1659     thePosition(1)  =mod(thePoint(1), nDim1* theMagnifyCoefficient);% x is Y
1660     thePosition(2)  =mod(thePoint(2), nDim2* theMagnifyCoefficient);%y is Z
1661                 
1662     theSeries_RowId =ceil((theYLim(2)-thePoint(2))/ (theYLim(2)/AConfig.Montage.Down));
1663     %YAN Chao-Gan 081229 theSeries_RowId =ceil(thePoint(2)/ (theYLim(2)/AConfig.Montage.Down));
1664     theSeries_ColId =ceil(thePoint(1)/ (theXLim(2)/AConfig.Montage.Across));
1665     thePointId_inSeries =(theSeries_RowId -1)*AConfig.Montage.Across +theSeries_ColId;
1666     
1667     %Calculate the Result Position after Magnifying
1668     if license('test','image_toolbox')==1 && theMagnifyCoefficient~=1, 
1669         thePosition(1) =round(thePosition(1) / theMagnifyCoefficient);        
1670         thePosition(2) =round(thePosition(2) / theMagnifyCoefficient);        
1671         theXLim        =round(theXLim /theMagnifyCoefficient);
1672         theYLim        =round(theYLim /theMagnifyCoefficient);
1673     end        
1674     
1675     %Set the real position
1676     thePosition(3) = AConfig.ViewSeries(thePointId_inSeries);    
1677     % AConfig.LastPosition =thePosition;
1678     AConfig =UpdatePosition(AConfig, thePosition);
1679     
1680     %Display Images
1681     AConfig =SetImage(AConfig);    
1682     
1683     Result =AConfig;
1684 
1685 function Result =SetPositionCrossHair(AConfig)        
1686     % theCurrentControl =gco;
1687     % uicontrol(AConfig.hYoke);
1688     %I must change the current focus to force the callback of the edit to run at once to make sure 'get' can return current string/value instead of old value
1689     % when I use KeyPressFcn. And KeyPressFcn didn't exist for uicontrol before Matlab 7. In Matlab 6.5, there is only KeyPressFcn for figure;
1690     
1691     thePosition =AConfig.LastPosition;    
1692     theXLim =[1, size(AConfig.Volume, 1)];
1693     theYLim =[1, size(AConfig.Volume, 2)];
1694     theZLim =[1, size(AConfig.Volume, 3)];
1695     theX =str2num(get(AConfig.hEditPositionX, 'String'));
1696     theY =str2num(get(AConfig.hEditPositionY, 'String'));
1697     theZ =str2num(get(AConfig.hEditPositionZ, 'String'));
1698     
1699     %Revise Direction , dawnsong20071101
1700     theX = theX * (-1);
1701     
1702     
1703     theX =round(theX/AConfig.VoxelSize(1) +AConfig.Origin(1));
1704     theY =round(theY/AConfig.VoxelSize(2) +AConfig.Origin(2));
1705     theZ =round(theZ/AConfig.VoxelSize(3) +AConfig.Origin(3));
1706     
1707     
1708     
1709     % uicontrol(theCurrentControl);
1710     
1711     if ~isempty(theX) && theX>=theXLim(1) ...
1712         && ~isempty(theY) && theY>=theYLim(1) ...
1713         && ~isempty(theZ) && theZ>=theZLim(1) ...
1714         && any(thePosition ~= [theX theY theZ]) ,
1715         
1716         if theX >theXLim(2), theX =theXLim(2); end
1717         if theY >theYLim(2), theY =theYLim(2); end
1718         if theZ >theZLim(2), theZ =theZLim(2); end
1719         
1720         thePosition =[theX theY theZ];        
1721         % AConfig.LastPosition =thePosition;
1722         AConfig =UpdatePosition(AConfig, thePosition);
1723     end        
1724     
1725     %Display Images
1726     AConfig =SetImage(AConfig);
1727     %Save LastPosition
1728     Result =AConfig;
1729     
1730 function Result =SetDistanceFromOrigin(AConfig, ADistanceFromOrigin);
1731 % Set current cross-hair position according to the Proportion Position among many size-not-equal brain images
1732     thePosition = ADistanceFromOrigin ./ AConfig.VoxelSize + AConfig.Origin;
1733     thePosition =round(thePosition);
1734     if any(thePosition ~= AConfig.LastPosition) ...
1735         && thePosition(1)>=1 && thePosition(1)<=size(AConfig.Volume,1) ...
1736         && thePosition(2)>=1 && thePosition(2)<=size(AConfig.Volume,2) ...
1737         &&  thePosition(3)>=1 && thePosition(3)<=size(AConfig.Volume,3) , ...
1738         % AConfig.LastPosition =thePosition;
1739         AConfig =UpdatePosition(AConfig, thePosition);
1740     elseif any(thePosition ~= AConfig.LastPosition),
1741         for x=1:3,
1742             while thePosition(x)<1,
1743                 thePosition(x) =thePosition(x) +size(AConfig.Volume,x);
1744             end
1745             while thePosition(x)>size(AConfig.Volume,x),
1746                 thePosition(x) =thePosition(x) -size(AConfig.Volume,x);
1747             end
1748         end
1749     end
1750     
1751     %Display Images
1752     AConfig =SetImage(AConfig);    
1753     %Save LastPosition
1754     Result =AConfig;
1755     
1756 function ShowPositionInEdit(AConfig)
1757     thePosition =AConfig.LastPosition;
1758     set(AConfig.hEditPositionX, 'String', num2str((thePosition(1)-AConfig.Origin(1))*AConfig.VoxelSize(1) *(-1) ));    %Make sure Left is Right like BA, and Left-image is + or Right-Brain is +
1759     set(AConfig.hEditPositionY, 'String', num2str((thePosition(2)-AConfig.Origin(2) )*AConfig.VoxelSize(2) ));    %Make sure Fore is +
1760     set(AConfig.hEditPositionZ, 'String', num2str((thePosition(3)-AConfig.Origin(3) )*AConfig.VoxelSize(3) ));    %Make sure Top is +
1761     
1762 function SetMessage(AConfig)
1763     %Detect if I should hide the big information area
1764     theTitle ='Click to Toggle Hdr info';
1765     theOldMsg =get(AConfig.hMsgLabel, 'String');
1766     
1767     if SeeOverlay(AConfig),
1768         %Compute the cooresponding position according to physical distance(mm) from origin
1769         thePhysicalPos = (AConfig.LastPosition -AConfig.Origin) .* AConfig.VoxelSize;
1770         theOverlayPos  = thePhysicalPos ./ AConfig.Overlay.VoxelSize +AConfig.Overlay.Origin;
1771         theOverlayPos =round(theOverlayPos);
1772         if all(theOverlayPos<=size(AConfig.Overlay.Volume)) ...
1773             && all(theOverlayPos >=[1 1 1]),
1774             %Legal
1775         else%Illegal data
1776             warning(sprintf('Illegal Overlay Position: (%s)\nI will revise the underlay''s position to its origin.', num2str(theOverlayPos)));
1777             %Revise the LastPosition on the underlay to the origin
1778             AConfig.LastPosition =AConfig.Origin;    %This line will not work because This fun didn't save the Global variable AConfig
1779             rest_sliceviewer('SetPhysicalPosition', AConfig.hFig, [0 0 0]);
1780             rest_sliceviewer('Repaint', AConfig.hFig);
1781             return;
1782         end
1783         
1784         theUnderlayIntensity =AConfig.Volume(AConfig.LastPosition(1),AConfig.LastPosition(2),AConfig.LastPosition(3));
1785          
1786         theOverlayIntensity  =AConfig.Overlay.Volume(theOverlayPos(1),theOverlayPos(2),theOverlayPos(3));
1787         if  prod(size(AConfig.Overlay.InfoAal))==116 ...
1788             && theOverlayIntensity>0,    %AAL template description
1789             theIntensity =sprintf('%s\n%g / %g', AConfig.Overlay.InfoAal{theOverlayIntensity},theUnderlayIntensity, theOverlayIntensity);
1790         else    %Default
1791             %Show the voxel's intensity for underlay and overlay
1792             theIntensity =sprintf('\n%g / %g', theUnderlayIntensity, theOverlayIntensity);
1793         end
1794         
1795         set(AConfig.hVoxelIntensity, 'String', theIntensity, 'TooltipString', ['Value: Underlay/Overlay = ', theIntensity]);
1796         
1797         theUnderlayInfo =sprintf('Dimension: %dx%dx%d\nVoxel(mm): %gx%gx%g\nOrigin(vxl): %d,%d,%d',size(AConfig.Volume,1), size(AConfig.Volume, 2), size(AConfig.Volume, 3), AConfig.VoxelSize(1), AConfig.VoxelSize(2),AConfig.VoxelSize(3), AConfig.Origin(1), AConfig.Origin(2), AConfig.Origin(3));
1798         theUnderlayInfo =sprintf('Underlay:\n%s\n\n', theUnderlayInfo);
1799         theOverlayInfo =sprintf('Dimension: %dx%dx%d\nVoxel(mm): %gx%gx%g\nOrigin(vxl): %d,%d,%d',size(AConfig.Overlay.Volume,1), size(AConfig.Overlay.Volume, 2), size(AConfig.Overlay.Volume, 3), AConfig.Overlay.VoxelSize(1), AConfig.Overlay.VoxelSize(2),AConfig.Overlay.VoxelSize(3), AConfig.Overlay.Origin(1), AConfig.Overlay.Origin(2), AConfig.Overlay.Origin(3));
1800         theOverlayInfo =sprintf('Overlay: (%s)\n%s', num2str((Pos_Underlay2Overlay(AConfig, AConfig.LastPosition) -AConfig.Overlay.Origin).*AConfig.Overlay.VoxelSize .* [-1, 1, 1]),theOverlayInfo);
1801         
1802         theInfo =[theUnderlayInfo theOverlayInfo];
1803         %set(AConfig.hMsgLabel, 'String', theInfo);
1804     else    %Don't see Overlay
1805         theIntensity =sprintf('\n%g',AConfig.Volume(AConfig.LastPosition(1),AConfig.LastPosition(2),AConfig.LastPosition(3)));
1806         set(AConfig.hVoxelIntensity, 'String', theIntensity, 'TooltipString', ['Value: Underlay ', theIntensity]);
1807         
1808         theInfo =sprintf('Dimension: %dx%dx%d\nVoxel(mm): %gx%gx%g\nOrigin(vxl): %d,%d,%d',size(AConfig.Volume,1), size(AConfig.Volume, 2), size(AConfig.Volume, 3), AConfig.VoxelSize(1), AConfig.VoxelSize(2),AConfig.VoxelSize(3), AConfig.Origin(1), AConfig.Origin(2), AConfig.Origin(3));
1809         %set(AConfig.hMsgLabel, 'String', theInfo);
1810     end    
1811     
1812     if ~isempty(AConfig.Message) && ~all(isspace(AConfig.Message)),
1813         theInfo =sprintf('%s\n\n%s', theInfo, AConfig.Message);
1814     end
1815     
1816     if strcmpi(theTitle, theOldMsg),
1817         %Hide the Information as the old
1818         %set(AConfig.hMsgLabel, 'String', theInfo);
1819         set(AConfig.hMsgLabel, 'TooltipString', theInfo);
1820     else    %Normally showing the Hdr info
1821         set(AConfig.hMsgLabel, 'String', theInfo,'TooltipString', '');
1822     end
1823         
1824     
1825     
1826     
1827     %Threshhold value display
1828     set(AConfig.hEdtThrdValue, 'String', num2str(AConfig.Overlay.ValueThrdAbsolute));
1829     
1830     return;
1831         
1832 function ResizeFigure(AConfig)
1833     MarginX =10; MarginY =10;    
1834     [nDim1, nDim2, nDim3] =size(AConfig.Volume);
1835     
1836     if strcmpi(get(AConfig.hFrameSetPos, 'Visible'), 'on'),
1837         theFramePos =get(AConfig.hFrameSetPos, 'Position');    
1838     else
1839         theFramePos =[0 0 0 0];
1840     end
1841     theMagnifyCoefficient =GetMagnifyCoefficient(AConfig); % Considering Magnifying result
1842     nDim1 =nDim1 *theMagnifyCoefficient;
1843     nDim2 =nDim2 *theMagnifyCoefficient;
1844     nDim3 =nDim3 *theMagnifyCoefficient;
1845     if strcmpi(AConfig.ViewMode, 'Orthogonal'),
1846         FigWidth  =theFramePos(1) +theFramePos(3) +MarginX + nDim1 +2 +nDim2 + MarginX;
1847         FigHeight =10 + nDim2 +2 +nDim3 + MarginY;        
1848     elseif strcmpi(AConfig.ViewMode, 'Transverse'),
1849         FigWidth  =theFramePos(1) +theFramePos(3) +MarginX + nDim1 * AConfig.Montage.Across + MarginX;
1850         FigHeight =MarginY + nDim2 * AConfig.Montage.Down + MarginY;        
1851     elseif strcmpi(AConfig.ViewMode, 'Sagittal'),
1852         FigWidth  =theFramePos(1) +theFramePos(3) +MarginX + nDim2 * AConfig.Montage.Across + MarginX;
1853         FigHeight =MarginY + nDim3 * AConfig.Montage.Down + MarginY;        
1854     elseif strcmpi(AConfig.ViewMode, 'Coronal'),
1855         FigWidth  =theFramePos(1) +theFramePos(3) +MarginX + nDim1 * AConfig.Montage.Across + MarginX;
1856         FigHeight =MarginY + nDim3 * AConfig.Montage.Down + MarginY;        
1857     end
1858     %Resize figure's width according to colorbar's visiblity
1859     if SeeOverlay(AConfig),
1860         theColorBarPos=get(AConfig.hAxesColorbar, 'Position');
1861         FigWidth = FigWidth +MarginX +theColorBarPos(3) +1.5*MarginX +MarginX;
1862     end
1863     %FigHeight =theFramePos(2) + nDim2 +2 +nDim3 + MarginY;
1864         
1865     
1866     % Revise the Intensity position
1867     % theMsgPos =get(AConfig.hVoxelIntensity, 'Position');
1868     % theMsgPos(1) =theFramePos(1) +theFramePos(3) +MarginX + nDim1 +5;
1869     % theMsgPos(2) =theFramePos(2);
1870     % theMsgPos(3) = FigWidth -theMsgPos(1) -MarginX;
1871     % set(AConfig.hVoxelIntensity, 'Position', theMsgPos); %Set first
1872     
1873     % theIntensity =get(AConfig.hVoxelIntensity, 'String');
1874     % [newMsg,newMsgPos]=textwrap(AConfig.hVoxelIntensity, {theIntensity});
1875     % set(AConfig.hVoxelIntensity, 'Position', newMsgPos);
1876     
1877     %Revise the Message's position
1878     if strcmpi(get(AConfig.hMsgLabel,'Visible'), 'on'),
1879         theMsgPos =get(AConfig.hMsgLabel, 'Position');
1880         theMsgPos(1) =theFramePos(1);
1881         theMsgPos(2) =theFramePos(2) +theFramePos(4) +MarginY;
1882         theMsgPos(3) =theFramePos(3);
1883         theMsgPos(4) =1;
1884         set(AConfig.hMsgLabel, 'Position', theMsgPos); %Set default position first
1885         
1886         theMsg =get(AConfig.hMsgLabel, 'String');
1887         [theMsg, theMsgPos] =textwrap(AConfig.hMsgLabel, cellstr(theMsg));
1888         set(AConfig.hMsgLabel, 'String', theMsg, 'Position', theMsgPos);
1889     end
1890     % Revise the Do Callback Button's position
1891     % if AConfig.hDoCallbackBtn>0
1892         % thePos =get(AConfig.hDoCallbackBtn, 'Position');
1893         % thePos(1) =theMsgPos(1);
1894         % thePos(2) =theMsgPos(2) +theMsgPos(4) +MarginY;
1895         % thePos(3) =theMsgPos(3);
1896         % thePos(4) =25;
1897         % set(AConfig.hDoCallbackBtn, 'Position', thePos);
1898     % end
1899     
1900     % Revise the figure's position according to the Brain Image's width and height
1901     thePos         =get(AConfig.hFig, 'Position');
1902     theScrPos    =get(0, 'ScreenSize');    
1903     % if AConfig.hDoCallbackBtn>0
1904         % theBtnPos =get(AConfig.hDoCallbackBtn, 'Position');
1905         % if FigHeight< (theBtnPos(2) +theBtnPos(4) +MarginY)
1906             % FigHeight =theBtnPos(2) +theBtnPos(4) +MarginY;
1907         % end
1908     % else end
1909     if strcmpi(get(AConfig.hMsgLabel,'Visible'), 'on'),
1910         theMsgPos =get(AConfig.hMsgLabel, 'Position');
1911         if FigHeight< (theMsgPos(2) +theMsgPos(4) +MarginY)
1912             FigHeight =theMsgPos(2) +theMsgPos(4) +MarginY;
1913         end
1914     end
1915     if (thePos(2) +FigHeight +60) > theScrPos(4)
1916         thePos(2) = theScrPos(4) -FigHeight -60;
1917     end
1918     if thePos(3) <FigWidth
1919         thePos(3) =FigWidth;
1920     elseif    thePos(3) >1.5*FigWidth
1921         thePos(3) =FigWidth;
1922     end
1923     thePos(4) =FigHeight;
1924     set(AConfig.hFig, 'Position', thePos);
1925     
1926     %Resize figure position according to the Message height
1927     if strcmpi(get(AConfig.hMsgLabel,'Visible'), 'on'),
1928         theMsgPos =get(AConfig.hMsgLabel, 'Position');
1929         if ( theMsgPos(2)+theMsgPos(4) )> thePos(4), 
1930             thePos(3) =FigWidth;
1931             thePos(4) =theMsgPos(2)+theMsgPos(4) +MarginY;
1932             set(AConfig.hFig, 'Position', thePos);
1933         end
1934     end    
1935 
1936 function Result =GetMagnifyCoefficient(AConfig)    
1937     if license('test','image_toolbox')~=1 ,
1938         Result =1;
1939         return;
1940     end
1941 
1942     theStr =get(AConfig.hMagnify ,'String');
1943     theIdx =get(AConfig.hMagnify ,'Value');
1944     Result =1;
1945     switch upper(theStr{theIdx}),
1946     case 'X0.5',
1947         Result =0.5;
1948     case 'X1',
1949         Result =1;
1950     case 'X2',
1951         Result =2;
1952     case 'X3',
1953         Result =3;
1954     otherwise
1955         rest_misc( 'ComplainWhyThisOccur');
1956     end
1957 
1958 function Result =UpdateCallback(AConfig, ACallback, ACallbackCaption)
1959     Result =AConfig;
1960     Result.Callback =ACallback;
1961     % if ~isempty(ACallbackCaption) && ischar(ACallbackCaption)
1962         % theBtnCaption =ACallbackCaption;
1963     % else
1964         % theBtnCaption ='Do sth.';
1965     % end
1966     
1967     % if Result.hDoCallbackBtn>0
1968         % I have created the Button to respond to the click event
1969         % if ~isempty(ACallback) && ischar(ACallback) ,
1970             % set(Result.hDoCallbackBtn, 'Callback', ACallback, 'String', theBtnCaption);
1971         % else
1972             % Remove the button because the Callback is illegal or empty
1973             % delete(Result.hDoCallbackBtn);
1974             % Result.hDoCallbackBtn =-1;
1975             % Result.Callback ='';
1976         % end
1977     % else
1978         % Create a Button responding the click event
1979         % if ~isempty(ACallback) && (ischar(ACallback) || isa(ACallback, 'function_handle')),
1980             % theCallback =sprintf('rest_sliceviewer(''RunCallback'', ''%s'');',AConfig.Filename);
1981             % Result.hDoCallbackBtn =uicontrol(Result.hFig, 'Style','pushbutton',  ...
1982                               % 'Units','pixels','String', theBtnCaption, ...
1983                               % 'Callback', theCallback);
1984         % end
1985     % end
1986     
1987 function ClearTextLabels(AConfig)    
1988     %Clear Text labels first for multislice mode
1989     theLabels =findobj(AConfig.hAxesSagittal, 'Type', 'text');
1990     for theX=1:length(theLabels), delete(theLabels(theX)); end
1991     theLabels =findobj(AConfig.hAxesCoronal, 'Type', 'text');
1992     for theX=1:length(theLabels), delete(theLabels(theX)); end
1993     theLabels =findobj(AConfig.hAxesTransverse, 'Type', 'text');
1994     for theX=1:length(theLabels), delete(theLabels(theX)); end
1995     
1996 function Result =AutoBalance(AConfig)
1997     Result =AConfig;
1998     %Save Maping Image parameters, Auto balance 20070911 revised, 20070914 revised for Statistical map which has negative values
1999     %Revise first
2000     Result.Volume(isnan(Result.Volume)) =0;
2001     Result.Volume(isinf(Result.Volume)) =0;
2002     %Begin computation, the following two lines are time-consuming up to 4.6 seconds!!!
2003     %But after replacing AConfig with Result, then their speed rocketed to 0.2 seconds!!!
2004     %Attention!!! Dawnwei.Song, 20070914
2005     theMaxVal=max(Result.Volume(:));
2006     theMinVal=min(Result.Volume(:));
2007     if theMaxVal>theMinVal,
2008         nBins=255;
2009         %Special processing just for very common images! 20071212
2010         if (theMaxVal<257) && (theMinVal>=0) && (theMaxVal-theMinVal>100), %not statistic map
2011             theSum =histc(Result.Volume(:), 1:ceil(theMaxVal));        
2012         else
2013             theSum =histc(Result.Volume(:), theMinVal:(theMaxVal-theMinVal)/254:theMaxVal);        
2014         end
2015         theSum =cumsum(theSum);
2016         theCdf =theSum/theSum(end);
2017         if rest_misc('GetMatlabVersion')>=7.3
2018             idxSatMin =find(theCdf>0.01, 1, 'first');
2019             idxSatMax =find(theCdf>=0.99, 1, 'first');            
2020         else
2021             idxSatMin =find(theCdf>0.01);
2022             idxSatMin =idxSatMin(1);
2023             idxSatMax =find(theCdf>=0.99);
2024             idxSatMax =idxSatMax(1);
2025         end    
2026         if idxSatMin==idxSatMax, idxSatMin =1; end    %20070919, For mask file's display
2027         theSatMin =(idxSatMin-1)/(nBins-1) *(theMaxVal-theMinVal) +theMinVal;
2028         theSatMax =(idxSatMax-1)/(nBins-1) *(theMaxVal-theMinVal) +theMinVal;    
2029     elseif theMaxVal==theMinVal,
2030         theSatMin =theMaxVal;
2031         theSatMax =theMaxVal;
2032     else
2033     end
2034     Result.Contrast.GrayDepth =255;
2035     Result.Contrast.SatMin =theSatMin;
2036     Result.Contrast.SatMax =theSatMax;
2037     %20070911, AutoBalance for contrast
2038     Result.Contrast.WindowWidth =theSatMax -theSatMin;
2039     Result.Contrast.WindowCenter=(theSatMax +theSatMin)/2;
2040 
2041     %For debug display
2042     % disp(Result.Contrast);
2043     
2044     
2045     
2046 function Result =IsCrosshairChecked(AConfig)
2047     Result ='off';
2048     if get(AConfig.hCrosshair, 'Value'),
2049         Result ='on';
2050     end
2051 
2052 function Transforming_MNI_Talairach(AConfig)
2053     isNeedUpdate =false;
2054     switch get(AConfig.hMniTal, 'Value'),
2055     case 1,    %'MNI/Talairach Coordinates'
2056         %Do nothing
2057     case 2, %'From Talairach to MNI'
2058         % AConfig.LastPosition
2059         thePosition =round(rest_tal2mni(AConfig.LastPosition -AConfig.Origin) +AConfig.Origin);
2060         AConfig =UpdatePosition(AConfig, thePosition);
2061         isNeedUpdate =true;
2062     case 3, %'From MNI to Talairach'
2063         % AConfig.LastPosition
2064         thePosition=round(rest_mni2tal(AConfig.LastPosition -AConfig.Origin) +AConfig.Origin);
2065         AConfig =UpdatePosition(AConfig, thePosition);
2066         isNeedUpdate =true;
2067     otherwise
2068     end
2069     % disp(AConfig.LastPosition);
2070     % return;
2071     
2072     if isNeedUpdate,
2073         ShowPositionInEdit(AConfig);
2074         SetMessage(AConfig);
2075         rest_sliceviewer('SetPosition', AConfig.Filename);
2076     end
2077     %Reset position in Choice selection
2078     set(AConfig.hMniTal, 'Value', 1);
2079     
2080 
2081 function Result =SaturateContrast(AImage, ASatMin, ASatMax)    
2082     Result =AImage;
2083     if ASatMin<ASatMax,
2084         Result(find(Result<ASatMin)) =ASatMin;
2085         Result(find(Result>ASatMax)) =ASatMax;
2086         Result =(Result -ASatMin)/(ASatMax - ASatMin);
2087     elseif ASatMin==ASatMax,
2088         Result(:) =0.01;
2089     else
2090         error('ASatMin>ASatMax ???');
2091     end
2092     
2093     %Map a indexed 2D image to a 2D * 3 image which is true color image and range is in [0 , 1]
2094     % Result =repmat(Result, [1 1 3]) /AGrayDepth;
2095 
2096 function Result =InitUnderlay(AConfig)    
2097 %Input: Need AConfig.Filename specified
2098     try
2099         [theVolume,theVoxelSize, Header] =rest_readfile(AConfig.Filename);  %%Yan 080610
2100         theOrigin=Header.Origin; %%Yan 080610
2101         AConfig =AddRecentUnderlay(AConfig, AConfig.Filename);        
2102         AConfig.Header=Header; %%Yan 080610
2103     catch
2104         if ~(exist(AConfig.Filename, 'file')==2) ...            
2105             && ( ~all(isspace(AConfig.Filename)) && ~isempty(isspace(AConfig.Filename))),
2106             warning(sprintf('Please check whether Img/Hdr file "%s" exist!', AConfig.Filename));
2107             warndlg(sprintf('Please check whether Img/Hdr file "%s" exist!', AConfig.Filename));
2108         end
2109         theVolume =255*zeros(181,217,181);    %theVolume(:) =round([1:prod(size(theVolume))]/2^16);
2110         theVoxelSize =[1 1 1];
2111         theOrigin =[90 126 72];
2112     end
2113     [nDim1, nDim2, nDim3] =size(theVolume);
2114         
2115     % Displaying Orthogonal images
2116     theFramePos =get(AConfig.hFrameSetPos, 'Position');    
2117     MarginY =10; MarginX =10;
2118     OffsetX =theFramePos(1) +theFramePos(3) +MarginX;
2119     OffsetY =MarginY;    
2120     
2121     %Delete old handles if exists any
2122     if ishandle(AConfig.hAxesSagittal), delete(AConfig.hAxesSagittal); end
2123     if ishandle(AConfig.hAxesCoronal), delete(AConfig.hAxesCoronal); end
2124     if ishandle(AConfig.hAxesTransverse), delete(AConfig.hAxesTransverse); end    
2125     %Save Images' handles
2126     if ishandle(AConfig.hImageSagittal), delete(AConfig.hImageSagittal); end    
2127     if ishandle(AConfig.hImageCoronal), delete(AConfig.hImageCoronal); end    
2128     if ishandle(AConfig.hImageTransverse), delete(AConfig.hImageTransverse); end        
2129     %Save Lines' handles
2130     if ishandle(AConfig.hXLineSagittal), delete(AConfig.hXLineSagittal); end        %x
2131     if ishandle(AConfig.hYLineSagittal), delete(AConfig.hYLineSagittal); end        %y
2132     if ishandle(AConfig.hXLineCoronal), delete(AConfig.hXLineCoronal); end        %x
2133     if ishandle(AConfig.hYLineCoronal), delete(AConfig.hYLineCoronal); end        %y
2134     if ishandle(AConfig.hXLineTransverse), delete(AConfig.hXLineTransverse); end    %x
2135     if ishandle(AConfig.hYLineTransverse), delete(AConfig.hYLineTransverse); end    %y
2136     
2137     
2138     %Create Axes and lines and images
2139     theAxesButtonDownFcn =sprintf('rest_sliceviewer(''ClickPosition'', %g);', AConfig.hFig);
2140     hAxesTransverse    =axes('Parent', AConfig.hFig, 'Box', 'on', ...
2141                           'Units', 'pixel', 'DrawMode','fast', ...
2142                           'Position', [OffsetX OffsetY nDim1 nDim2], ...
2143                           'YDir','normal', 'XTickLabel',[],'XTick',[], ...
2144                           'YTickLabel',[],'YTick',[], 'DataAspectRatio',[1 1 1],...
2145                           'ButtonDownFcn', theAxesButtonDownFcn);
2146     hImageTransverse =image('Tag','BrainImageTransverse', 'Parent', hAxesTransverse);
2147     set(hAxesTransverse,'YDir','normal','ButtonDownFcn', theAxesButtonDownFcn, 'XTickLabel',[],'XTick',[], ...
2148                           'YTickLabel',[],'YTick',[]);
2149     hXLineTransverse =line(0, 0, 'Parent', hAxesTransverse, 'Color', 'red');
2150     hYLineTransverse =line(0, 0, 'Parent', hAxesTransverse, 'Color', 'red');    
2151         
2152     hAxesCoronal     =axes('Parent', AConfig.hFig, 'Box', 'on', ...
2153                           'Units', 'pixel', 'DrawMode','fast', ...
2154                           'Position', [OffsetX OffsetY+nDim2+2 nDim1 nDim3], ...
2155                           'YDir','normal', 'XTickLabel',[],'XTick',[], ...
2156                           'YTickLabel',[],'YTick',[], ...
2157                           'ButtonDownFcn', theAxesButtonDownFcn);
2158     hImageCoronal =image('Tag','BrainImageCoronal', 'Parent', hAxesCoronal);
2159     set(hAxesCoronal,'YDir','normal','ButtonDownFcn', theAxesButtonDownFcn, 'XTickLabel',[],'XTick',[], ...
2160                           'YTickLabel',[],'YTick',[]);
2161     hXLineCoronal =line(0, 0, 'Parent', hAxesCoronal, 'Color', 'red');
2162     hYLineCoronal =line(0, 0, 'Parent', hAxesCoronal, 'Color', 'red');
2163     
2164     hAxesSagittal     =axes('Parent', AConfig.hFig, 'Box', 'on', ...
2165                           'Units', 'pixel', 'DrawMode','fast', ...
2166                           'Position', [OffsetX+nDim1+2 OffsetY+nDim2+2 nDim2 nDim3], ...
2167                           'YDir','normal', 'XTickLabel',[],'XTick',[], ...
2168                           'YTickLabel',[],'YTick',[], ...
2169                           'ButtonDownFcn', theAxesButtonDownFcn);
2170     hImageSagittal =image('Tag','BrainImageSagittal',  'Parent', hAxesSagittal);
2171     set(hAxesSagittal,'YDir','normal','ButtonDownFcn', theAxesButtonDownFcn, 'XTickLabel',[],'XTick',[], ...
2172                           'YTickLabel',[],'YTick',[]);
2173     hXLineSagittal =line(0, 0, 'Parent', hAxesSagittal, 'Color', 'red');
2174     hYLineSagittal =line(0, 0, 'Parent', hAxesSagittal, 'Color', 'red');        
2175     
2176     
2177     %Save Axes's handles
2178     AConfig.hAxesSagittal     =hAxesSagittal;
2179     AConfig.hAxesCoronal     =hAxesCoronal;
2180     AConfig.hAxesTransverse =hAxesTransverse;
2181     %Save Images' handles
2182     AConfig.hImageSagittal     =hImageSagittal;
2183     AConfig.hImageCoronal      =hImageCoronal;
2184     AConfig.hImageTransverse =hImageTransverse;
2185     %Save Lines' handles
2186     AConfig.hXLineSagittal   =hXLineSagittal;        %x
2187     AConfig.hYLineSagittal   =hYLineSagittal;        %y
2188     AConfig.hXLineCoronal     =hXLineCoronal;        %x
2189     AConfig.hYLineCoronal     =hYLineCoronal;        %y
2190     AConfig.hXLineTransverse =hXLineTransverse;        %x
2191     AConfig.hYLineTransverse =hYLineTransverse;        %y
2192     
2193     AConfig.Volume =theVolume;    
2194     AConfig.VoxelSize =reshape(theVoxelSize, [1 3]);
2195     
2196     AConfig.Origin =reshape(theOrigin, [1 3]);
2197     AConfig.Header.Origin=AConfig.Origin;
2198     if any(AConfig.Origin==[0 0 0]),
2199         %Auto-Revise the Origin to the half of the size of the brain
2200         theMsg =sprintf('Illegal origin: (%s)\n\nI presume the origin is (%s)',num2str(AConfig.Origin), num2str(round(size(AConfig.Volume)/2)));
2201         warning(theMsg);
2202         warndlg(theMsg);
2203         AConfig.Origin =round(size(AConfig.Volume)/2);
2204     end    
2205     if (norm(theOrigin)==0 || (any(round(theOrigin)~=theOrigin)) || (any(theOrigin<0)))   %YAN Chao-Gan 090401: If the origin of the image was not positive integer, then jump to the image center.
2206         AConfig.LastPosition =round([nDim1 nDim2 nDim3]/2);        %[x y z] the position in Volume corresponding to the cross-hair position
2207     else
2208         if ~all(AConfig.LastPosition < size(theVolume)),    %If legal
2209             AConfig.LastPosition =reshape(AConfig.Origin, [1 3]);
2210         end        
2211     end
2212         
2213     %Auto balance
2214     AConfig=AutoBalance(AConfig);
2215     
2216     Result =AConfig;
2217     
2218 
2219     
2220 function Result =SeeOverlay(AConfig)
2221     Result =get(AConfig.hSeeOverlay, 'Value');
2222     
2223 function Result =GetOverlayImg(AType, AConfig, AUnderlayPosition)
2224 %Return raw overlay image data by computing the real physical distance(mm) from the origin     % AUnderlayPosition is a scalar, result is a slice according to AType and AUnderlayPosition
2225     theVolume =AConfig.Overlay.VolumeThrd;
2226         
2227     switch lower(AType)
2228     case 'sagittal',
2229         thePhysicalPosition =(AUnderlayPosition -AConfig.Origin(1)) *AConfig.VoxelSize(1);
2230         thePhysicalPosition =thePhysicalPosition/AConfig.Overlay.VoxelSize(1) +AConfig.Overlay.Origin(1);
2231         if thePhysicalPosition>size(theVolume, 1),
2232             thePhysicalPosition =size(theVolume, 1);
2233         elseif thePhysicalPosition<1,
2234             thePhysicalPosition =1;
2235         end
2236         
2237         Result =squeeze(theVolume(round(thePhysicalPosition), :, :));
2238         
2239     case 'coronal',        
2240         thePhysicalPosition =(AUnderlayPosition -AConfig.Origin(2)) *AConfig.VoxelSize(2);
2241         thePhysicalPosition =thePhysicalPosition/AConfig.Overlay.VoxelSize(2) +AConfig.Overlay.Origin(2);
2242         if thePhysicalPosition>size(theVolume, 2),
2243             thePhysicalPosition =size(theVolume, 2);
2244         elseif thePhysicalPosition<1,
2245             thePhysicalPosition =1;
2246         end
2247         Result =squeeze(theVolume(:, round(thePhysicalPosition), :));
2248         
2249     case 'transverse',
2250         thePhysicalPosition =(AUnderlayPosition -AConfig.Origin(3)) *AConfig.VoxelSize(3);
2251         thePhysicalPosition =thePhysicalPosition/AConfig.Overlay.VoxelSize(3) +AConfig.Overlay.Origin(3);
2252         if thePhysicalPosition>size(theVolume, 3),
2253             thePhysicalPosition =size(theVolume, 3);
2254         elseif thePhysicalPosition<1,
2255             thePhysicalPosition =1;
2256         end
2257         Result =squeeze(theVolume(:, :, round(thePhysicalPosition)));
2258     otherwise
2259     end
2260     Result =Result';    
2261     
2262 function Result =Pos_Underlay2Overlay(AConfig, AUnderlayPosition)
2263 % AUnderlayPosition is a 1by3 vector, result is the same
2264     Result =(AUnderlayPosition -AConfig.Origin) .*AConfig.VoxelSize;
2265     Result =Result./AConfig.Overlay.VoxelSize +AConfig.Overlay.Origin;
2266     Result =round(Result);
2267     
2268 function Result =SetThrdAbsValue(AConfig)    
2269 %By default, I only set the Min absolute value to be the threshold, and renturn the Min, 20070918
2270     theObject =get(AConfig.hFig, 'CurrentObject');
2271     if strcmpi(get(theObject, 'Style'), 'edit'),
2272         Result =str2num(get(AConfig.hEdtThrdValue, 'String'));        
2273     elseif strcmpi(get(theObject, 'Style'), 'slider'),
2274         Result =get(AConfig.hSliderThrdValue, 'Value');
2275     else
2276         Result =-Inf;
2277         return;
2278     end    
2279     
2280     theMin =get(AConfig.hSliderThrdValue, 'Min');
2281     theMax =get(AConfig.hSliderThrdValue, 'Max');
2282     if Result<theMin,
2283         Result =theMin;
2284     elseif Result>theMax,
2285         Result =theMax;
2286     end
2287     set(AConfig.hSliderThrdValue, 'Value', Result);
2288     set(AConfig.hEdtThrdValue, 'String', num2str(Result));    
2289     
2290 function Result =ThrdOverlayAbsoluteValueAbove(AOverlayImg, AAbsoluteValueMin)
2291 %Threshold for Absolute value above the Min
2292     Result =AOverlayImg;    
2293     tmp = abs(AOverlayImg)>=abs(AAbsoluteValueMin);    
2294     Result(~tmp)=0;
2295     
2296 function Result =ThrdOverlayAbsoluteValueBelow(AOverlayImg, AAbsoluteValueMax)
2297 %Threshold for Absolute value above the Min
2298     Result =AOverlayImg;    
2299     tmp = abs(AOverlayImg)<=abs(AAbsoluteValueMax);    
2300     Result(~tmp)=0;
2301 function Result =ThrdOverlayValueAbove(AOverlayImg, AValueMin)
2302 %Threshold for Absolute value above the Min
2303     Result =AOverlayImg;    
2304     tmp = (AOverlayImg)>=(AValueMin);    
2305     Result(~tmp)=0;
2306     
2307 function Result =ThrdOverlayValueBelow(AOverlayImg, AValueMax)
2308 %Threshold for Absolute value above the Min
2309     Result =AOverlayImg;    
2310     tmp = (AOverlayImg)<=(AValueMax);    
2311     Result(~tmp)=0;    
2312     
2313 function Result =ThrdOverlayValueIn(AOverlayImg, AValueSeries)
2314 %Threshold for a seiry of values
2315     Result =AOverlayImg;
2316     tmp =false(size(AOverlayImg));
2317     for x=1:length(AValueSeries),
2318         tmp = tmp | ((AOverlayImg)==(AValueSeries(x)) );
2319     end    
2320     Result(~tmp)=0;    
2321     
2322     
2323     
2324     
2325 function Result =ThrdOverlayCluster(AConfig, AVolume)    
2326 %Threshold for Cluster Size or calculated cluster size from cluster-Raidus %This function must be called after thresholding the Value already!
2327     %"AConfig.Overlay.VolumeThrd" must be thresholded before this function is called!
2328     Result =AVolume;
2329     %Raidus has Priority
2330     if AConfig.Overlay.ClusterRadiusThrd~=0, %Raidus(mm)
2331         %Calcute the cluster size according to the Raidus(mm)
2332         AConfig.Overlay.Header.Origin=AConfig.Overlay.Origin; %%Yan 080610
2333         maskROI =rest_SphereROI( 'BallDefinition2Mask' , sprintf('ROI Center(mm)=(0, 0, 0); Radius=%g mm.', AConfig.Overlay.ClusterRadiusThrd), size(AConfig.Overlay.Volume), AConfig.Overlay.VoxelSize, AConfig.Overlay.Header);  %%Yan 080610 and 081223
2334         AConfig.Overlay.ClusterSizeThrd =length(find(maskROI));
2335         AConfig.Overlay.ClusterRadiusThrd =0;
2336     end
2337     if AConfig.Overlay.ClusterSizeThrd==0, return; end
2338     [theObjMask, theObjNum]=bwlabeln(Result);    
2339     for x=1:theObjNum,
2340         theCurrentCluster = theObjMask==x;
2341         if length(find(theCurrentCluster))<AConfig.Overlay.ClusterSizeThrd,
2342             Result(logical(theCurrentCluster))=0;            %YAN Chao-Gan 081223, Original "Result(~logical(theCurrentCluster))=0;" was an error
2343         end
2344     end    
2345     
2346     
2347 function Result =ThresholdOverlayVolume(AConfig)
2348     AConfig.Overlay.VolumeThrd =AConfig.Overlay.Volume;
2349     %First, thresholding by a range set by Min,Max
2350     if ~isinf(AConfig.Overlay.ValueThrdMin),
2351         AConfig.Overlay.VolumeThrd =ThrdOverlayValueAbove(AConfig.Overlay.VolumeThrd, AConfig.Overlay.ValueThrdMin);        
2352     end
2353     if ~isinf(AConfig.Overlay.ValueThrdMax),
2354         AConfig.Overlay.VolumeThrd =ThrdOverlayValueBelow(AConfig.Overlay.VolumeThrd, AConfig.Overlay.ValueThrdMax);        
2355     end
2356     
2357     %Absolute value thresholding without priority!
2358     %Threshold the Overlay    by the Value or Range or Series
2359     if AConfig.Overlay.ValueThrdAbsolute>0,
2360         AConfig.Overlay.VolumeThrd =ThrdOverlayAbsoluteValueAbove(AConfig.Overlay.VolumeThrd, AConfig.Overlay.ValueThrdAbsolute);    
2361     end
2362         
2363     if ~isnan(AConfig.Overlay.ValueThrdSeries), 
2364         AConfig.Overlay.VolumeThrd =ThrdOverlayValueIn(AConfig.Overlay.VolumeThrd, AConfig.Overlay.ValueThrdSeries);
2365     end    
2366     AConfig.Overlay.VolumeThrd =ThrdOverlayCluster(AConfig, AConfig.Overlay.VolumeThrd);    
2367     Result =AConfig;
2368     
2369 function Result =ScaleOverlay2TrueColor(AConfig, AOverlayImg, AColorMap)
2370     [pathstr, name, ext, versn] = fileparts(AConfig.Overlay.Filename);
2371     if strcmpi(name,'aal') ||  strcmpi(name,'brodmann'),
2372         Result =ScaleTemplate2TrueColor(AConfig, AOverlayImg);
2373     else
2374         Result =Overlay2TrueColor(AOverlayImg, AColorMap);
2375     end
2376     
2377 function Result =Overlay2TrueColor(AOverlayImg, AColorMap)    
2378     Result =AOverlayImg;
2379     nColorLen =size(AColorMap, 1);
2380     %Attention:
2381     %Keep zero as zero always! 20070915
2382     
2383     %Mapping the Negative values
2384     ResultNegative =Result;
2385     ResultNegative(Result>0) =0;
2386     
2387     theNonZeroPos =find(ResultNegative~=0);
2388     theMax =max(ResultNegative(theNonZeroPos));
2389     theMin =min(ResultNegative(theNonZeroPos));    
2390     if theMax>theMin,
2391         ResultNegative(theNonZeroPos) = (ResultNegative(theNonZeroPos)-theMin)/(theMax - theMin) *(nColorLen/2-1) +1;    %Add one to make sure theMin be mapped not zero(i.e. to 1) and could be mapped to the first element in colormap
2392         ResultNegative =overlay_ind2rgb(floor(ResultNegative), AColorMap(1:nColorLen/2, :));
2393     else
2394         if theMax~=0,
2395             ResultNegative(theNonZeroPos) =1;
2396             ResultNegative =overlay_ind2rgb(floor(ResultNegative), AColorMap(1, :));
2397         else
2398             ResultNegative =zeros([size(Result), 3]);
2399         end
2400     end
2401     
2402     %Mapping the Positive values
2403     ResultPositive =Result;
2404     ResultPositive(Result<0) =0;
2405     
2406     theNonZeroPos =find(ResultPositive~=0);
2407     theMax =max(ResultPositive(theNonZeroPos));
2408     theMin =min(ResultPositive(theNonZeroPos));    
2409     if theMax>theMin,        
2410         ResultPositive(theNonZeroPos) = (ResultPositive(theNonZeroPos)-theMin)/(theMax - theMin) *(nColorLen/2-1) +1;
2411         ResultPositive =overlay_ind2rgb(ceil(ResultPositive), AColorMap(nColorLen/2+1:end, :));
2412     else
2413         if theMax~=0,
2414             ResultPositive(theNonZeroPos) =1;
2415             ResultPositive =overlay_ind2rgb(floor(ResultPositive), AColorMap(end, :));
2416         else
2417             ResultPositive =zeros([size(Result), 3]);
2418         end         
2419     end
2420     
2421     Result =ResultNegative +ResultPositive;
2422     
2423 function Result =ScaleTemplate2TrueColor(AConfig, AOverlayImg)    
2424 %Such as AAL, BRODMANN ...
2425     Result =AOverlayImg;
2426     [pathstr, name, ext, versn] = fileparts(AConfig.Overlay.Filename);
2427     if strcmpi(name, 'aal'),        
2428         AColorMap =rest_ReadLutColorScheme(fullfile(rest_misc( 'WhereIsREST'),'Template', 'aal.nii.lut'));    %YAN Chao-Gan 081223: use the NIFTI image information from the MRIcroN
2429         theBlackPos=sum(AColorMap, 2)==0;
2430         AColorMap(theBlackPos, :) =1; %Black to White for I use black always as the background
2431         Result =overlay_ind2rgb(1+floor(Result), AColorMap);%Overpass the first color which may be backgound color
2432     elseif strcmpi(name, 'brodmann'),        
2433         AColorMap =rest_ReadLutColorScheme(fullfile(rest_misc( 'WhereIsREST'),'Template', 'brodmann.nii.lut'));        %YAN Chao-Gan 081223: use the NIFTI image information from the MRIcroN
2434         theBlackPos=sum(AColorMap, 2)==0;
2435         AColorMap(theBlackPos, :) =1; %Black to White for I use black always as the background
2436         Result =overlay_ind2rgb(1+floor(Result), AColorMap);%Overpass the first color which may be backgound color
2437     end
2438     
2439     
2440 function Result =AddOverlay(AType, AConfig, ATrueColorUnderlay)    
2441     switch lower(AType)
2442     case 'sagittal',
2443         AUnderlayPosition =AConfig.LastPosition(1);
2444     case 'coronal',        
2445         AUnderlayPosition =AConfig.LastPosition(2);
2446     case 'transverse',
2447         AUnderlayPosition =AConfig.LastPosition(3);
2448     otherwise
2449     end
2450     
2451     Result =ATrueColorUnderlay;
2452     if isempty(AConfig.Overlay.Filename),        
2453         return;
2454     else    %Add Overlay Image
2455         theOverlay =GetOverlayImg(AType, AConfig, AUnderlayPosition);
2456         
2457         %Resize image to the same size with the Anatomical image
2458         if license('test','image_toolbox')==1,
2459             if rest_misc('GetMatlabVersion')>=7.4   %YAN Chao-Gan 090401: The imresize function has been completely rewritten in Matlab R2007a. Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version.
2460                 theOverlay =imresize_old(theOverlay, [size(ATrueColorUnderlay, 1), size(ATrueColorUnderlay, 2)]);
2461             else
2462                 theOverlay =imresize(theOverlay, [size(ATrueColorUnderlay, 1), size(ATrueColorUnderlay, 2)]);
2463             end
2464         else,
2465             error('You must install image_toolbox first!');
2466         end
2467         
2468         nonZeroPos = theOverlay~=0;
2469         theOverlay =ScaleOverlay2TrueColor(AConfig, theOverlay, AConfig.Overlay.Colormap);
2470         %Add r g b colors with mask
2471         Result =AddRGBInMask(theOverlay, ATrueColorUnderlay, nonZeroPos, AConfig.Overlay.Opacity);
2472         %Result =theOverlay *AConfig.Overlay.Opacity + ATrueColorUnderlay*(1-AConfig.Overlay.Opacity);
2473     end
2474 
2475 function Result =AddOverlaySeries(AConfig, ATrueColorUnderlay)
2476     %Get the Magnified Brain Size
2477     %Make sure there will be no any fractional value   if GetMagnifyCoefficient(AConfig)<1
2478     theSize= floor(GetMagnifyCoefficient(AConfig) * size(AConfig.Volume));
2479     nDim1=theSize(1); nDim2=theSize(2); nDim3=theSize(3);
2480     
2481     Result =ATrueColorUnderlay;    
2482     if isempty(AConfig.Overlay.Filename),
2483         return;
2484     else    %Add Overlay Image
2485         for theRow=AConfig.Montage.Down:-1:1,
2486             for theCol=1:AConfig.Montage.Across,
2487                 %Retrieve the underlay
2488                 switch lower(AConfig.ViewMode)
2489                 case 'sagittal',
2490                     theUnderlay =Result((theRow-1)*nDim3 +(1:nDim3), (theCol-1)*nDim2+(1:nDim2), :);
2491                 case 'coronal',        
2492                     theUnderlay =Result((theRow-1)*nDim3 +(1:nDim3), (theCol-1)*nDim1+(1:nDim1), :);
2493                 case 'transverse',
2494                     theUnderlay =Result((theRow-1)*nDim2 +(1:nDim2), (theCol-1)*nDim1+(1:nDim1), :);
2495                 otherwise
2496                 end
2497                 %Get the overlay
2498                 theIndex = AConfig.ViewSeries((AConfig.Montage.Down-theRow)*AConfig.Montage.Across +theCol);
2499                 %YAN Chao-Gan 081229 theIndex = AConfig.ViewSeries((theRow-1)*AConfig.Montage.Across +theCol);
2500                 theOverlay =GetOverlayImg(AConfig.ViewMode, AConfig, theIndex);
2501                                 
2502                 if license('test','image_toolbox')==1,
2503                     if rest_misc('GetMatlabVersion')>=7.4   %YAN Chao-Gan 090401: The imresize function has been completely rewritten in Matlab R2007a. Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version.
2504                         theOverlay =imresize_old(theOverlay, [size(theUnderlay, 1), size(theUnderlay, 2)]);
2505                     else
2506                         theOverlay =imresize(theOverlay, [size(theUnderlay, 1), size(theUnderlay, 2)]);
2507                     end
2508                 else
2509                     error('You must install image_toolbox first!');
2510                 end
2511                 
2512                 nonZeroPos = theOverlay~=0;
2513                 theOverlay =ScaleOverlay2TrueColor(AConfig, theOverlay, AConfig.Overlay.Colormap);
2514                 %Add r g b colors with mask
2515                 theUnderlay =AddRGBInMask(theOverlay, theUnderlay, nonZeroPos, AConfig.Overlay.Opacity);
2516                 %theUnderlay(theIndex) =theOverlay(theIndex) *AConfig.Overlay.Opacity + theUnderlay(theIndex)*(1-AConfig.Overlay.Opacity);
2517                 
2518                 %Save underlay to big series' map
2519                 switch lower(AConfig.ViewMode)
2520                 case 'sagittal',
2521                     Result((theRow-1)*nDim3 +(1:nDim3), (theCol-1)*nDim2+(1:nDim2), :) =theUnderlay;
2522                 case 'coronal',        
2523                     Result((theRow-1)*nDim3 +(1:nDim3), (theCol-1)*nDim1+(1:nDim1), :) =theUnderlay;
2524                 case 'transverse',
2525                     Result((theRow-1)*nDim2 +(1:nDim2), (theCol-1)*nDim1+(1:nDim1), :) =theUnderlay;
2526                 otherwise
2527                 end
2528             end %end for-loop theCol
2529         end    %end for-loop theRow
2530     end    %end if
2531     
2532 function Result =LoadOverlay(AConfig, AFilename)
2533     Result =AConfig;
2534     try
2535         [theVolume,theVoxelSize, Header] =rest_readfile(AFilename); %%Yan 080610
2536         theOrigin=Header.Origin; %%Yan 080610
2537         Result =AddRecentOverlay(AConfig, AFilename);
2538     catch
2539         if ~(exist(AFilename, 'file')==2) ...            
2540             && ( ~all(isspace(AFilename)) && ~isempty(isspace(AFilename))),
2541             warning(sprintf('Please check whether Img/Hdr file "%s" exist!', AConfig.Filename));
2542             warndlg(sprintf('Please check whether Img/Hdr file "%s" exist!', AConfig.Filename));
2543         end
2544         
2545         theVolume     =zeros(61, 73, 61); theVolume(33,33,33)=0.1;
2546         theVoxelSize=[3 3 3];
2547         theOrigin     =[31 43 25];
2548     end
2549     Result.Overlay.Filename =AFilename;
2550     Result.Overlay.Volume =theVolume;
2551     Result.Overlay.VolumeThrd =theVolume;%Volume Thresholded as cache
2552     Result.Overlay.VoxelSize =reshape(theVoxelSize, [1 3]);
2553     Result.Overlay.Origin =reshape(theOrigin, [1 3]);
2554     Result.Overlay.Header=Header; %%Yan 080610
2555     if any(Result.Overlay.Origin==[0 0 0]),
2556         %Auto-Revise the Origin to the half of the size of the brain
2557         theMsg =sprintf('Illegal origin: (%s)\n\nI presume the origin is (%s)',num2str(Result.Overlay.Origin), num2str(round(size(Result.Overlay.Volume)/2)));
2558         warning(theMsg);
2559         warndlg(theMsg);        
2560         Result.Overlay.Origin =round(size(Result.Overlay.Volume)/2);
2561     end
2562     
2563     %Calcute the min and max both in positive & negative field
2564     tmpVolume =theVolume(find(theVolume));
2565     theMinNegative = min(tmpVolume(tmpVolume<0));
2566     theMaxNegative = max(tmpVolume(tmpVolume<0));
2567     theMinPositive = min(tmpVolume(tmpVolume>0));
2568     theMaxPositive = max(tmpVolume(tmpVolume>0));
2569     clear tmpVolume;    
2570     if isempty(theMinNegative), theMinNegative =0; end    %Just For always zero map
2571     if isempty(theMaxNegative), theMaxNegative =0; end  %Just For always zero map
2572     if isempty(theMinPositive), theMinPositive =0; end    %Just For always zero map
2573     if isempty(theMaxPositive), theMaxPositive =0; end  %Just For always zero map
2574     
2575     theAbsMax =max(abs([theMinNegative, theMaxPositive]));
2576     theAbsMin =min(abs([theMaxNegative, theMinPositive]));
2577     % theAbsVolume =abs(theVolume);
2578     % theAbsMax =max(theAbsVolume(find(theAbsVolume)));
2579     % theAbsMin =min(theAbsVolume(find(theAbsVolume)));
2580     % clear theAbsVolume;
2581     if theAbsMax<=theAbsMin, theAbsMax =theAbsMin+1; end
2582     set(AConfig.hSliderThrdValue, 'Max',theAbsMax,'Min',theAbsMin, 'Value',theAbsMin, 'SliderStep',[0.01, 0.05]);
2583     
2584     
2585     Result.Overlay.MinNegative =theMinNegative;%-10
2586     Result.Overlay.MaxNegative =theMaxNegative;%-1
2587     Result.Overlay.MinPositive =theMinPositive;            %1
2588     Result.Overlay.MaxPositive =theMaxPositive;            %10
2589     Result.Overlay.AbsMin =theAbsMin;
2590     Result.Overlay.AbsMax =theAbsMax;
2591         
2592     Result.Overlay.ValueThrdAbsolute =theAbsMin; %Default, show all
2593     Result.Overlay.ValueThrdMin =theMinNegative; %Default, show all
2594     Result.Overlay.ValueThrdMax =theMaxPositive; %Default, show all
2595     Result.Overlay.ClusterThrd =0; %Default, don't confine cluster size
2596     Result.Overlay.ClusterRadius =0; %Default radius(mm) for Cluster size definition
2597     
2598     [pathstr, name, ext, versn] = fileparts(Result.Overlay.Filename);
2599     if strcmpi(name, 'aal'),        
2600         theInfoTxt =fullfile(rest_misc( 'WhereIsREST'),'Template', 'aal.nii.txt'); %YAN Chao-Gan 081223: use the NIFTI image information from the MRIcroN
2601         [x,Result.Overlay.InfoAal,y] =textread(theInfoTxt,'%d %s %d');
2602     else
2603         Result.Overlay.InfoAal='None';
2604     end
2605     
2606     
2607 function [rout,g,b] = overlay_ind2rgb(a,cm)
2608     theImage =a;
2609     % Make sure A is in the range from 0 to size(cm,1)
2610     theImage = max(0,min(theImage,size(cm,1)));
2611     %Exclude any zero values, following is the Revision
2612     theColormap =[[-1 -1 -1]; cm];
2613     theImage =theImage+1;%Make any zero to one
2614     
2615     % Extract r,g,b components
2616     r = zeros(size(theImage)); r(:) = theColormap(theImage,1);
2617     g = zeros(size(theImage)); g(:) = theColormap(theImage,2);
2618     b = zeros(size(theImage)); b(:) = theColormap(theImage,3);
2619 
2620     if nargout==3,
2621       rout = r;
2622     else
2623       rout = zeros([size(r),3]);
2624       rout(:,:,1) = r;
2625       rout(:,:,2) = g;
2626       rout(:,:,3) = b;
2627     end
2628     %Revision finally
2629     rout(rout==-1) =0;
2630     
2631 function Result =GetDefaultColormap()
2632     theNegative =winter(128);
2633     thePositive =hot(128);
2634     thePositive =thePositive(128:-1:1, :);
2635     Result =[theNegative; thePositive];
2636     
2637 function Result =AddRGBInMask(AMapO, AMapU, AMask, AOpacityX)
2638     if ~isequal(size(AMapO),size(AMapU)),    
2639         error('Non-same size are the two true-color maps');
2640     end    
2641     if AOpacityX<0 || AOpacityX>1,    
2642         error('Non legal AOpacity value');
2643     end    
2644     AMask = AMask~=0;
2645             
2646     rx =AMapO(:, :, 1);
2647     ry =AMapU(:, :, 1);
2648     r  =zeros(size(rx));
2649     r(AMask) =rx(AMask)*AOpacityX +ry(AMask)*(1-AOpacityX);
2650     r(~AMask)=ry(~AMask);
2651     
2652     gx =AMapO(:, :, 2);
2653     gy =AMapU(:, :, 2);
2654     g  =zeros(size(rx));
2655     g(AMask) =gx(AMask)*AOpacityX +gy(AMask)*(1-AOpacityX);
2656     g(~AMask)=gy(~AMask);
2657     
2658     bx =AMapO(:, :, 3);
2659     by =AMapU(:, :, 3);
2660     b  =zeros(size(rx));
2661     b(AMask) =bx(AMask)*AOpacityX +by(AMask)*(1-AOpacityX);
2662     b(~AMask)=by(~AMask);
2663     
2664     Result= zeros(size(AMapO));
2665     Result(:, :, 1)=r;
2666     Result(:, :, 2)=g;
2667     Result(:, :, 3)=b;
2668     
2669 function Result =Overlay_Misc(AConfig)    
2670     isNeedUpdate =false;
2671     % if SeeOverlay(AConfig),
2672         switch get(AConfig.hOverlayMisc, 'Value'),
2673         case 1,    %Overlay Misc
2674             %Do nothing
2675         case 2, %'Set Overlay Opacity'
2676             prompt ={'Overlay''s Opacity: (1=opaque, 0=transparent and restricted in [0, 1])'};
2677             def    ={    num2str(AConfig.Overlay.Opacity) };
2678             answer =inputdlg(prompt, 'Overlay Opacity', 1, def);
2679             if numel(answer)==1,
2680                 theVal =abs(str2num(answer{1}));
2681                 if theVal>1, theVal=1; end
2682                 AConfig.Overlay.Opacity = theVal;            
2683             end
2684         case 3, %Set Range of Threshold
2685             prompt ={'Threshold Value''s Range: Min, Max( Default=-Inf,Inf.)', sprintf('\nSet Threshold Value''s Series, such as 25,1,7,31 for only showing Brodmann''s area BA25, BA1, BA7, BA31 when overlay is BA template. This also works for AAL template. This supports MATLAB array defination syntax. NaN means not confined in any series.')};
2686             def    ={sprintf('%d, %d',AConfig.Overlay.ValueThrdMin,AConfig.Overlay.ValueThrdMax) ,...
2687                   num2str(AConfig.Overlay.ValueThrdSeries)};
2688             answer =inputdlg(prompt, 'Set a range for thresholding', 2, def);
2689             if numel(answer)==2,
2690                 theVal =(str2num(answer{1}));
2691                 if length(theVal)==2, 
2692                     if theVal(1)>theVal(2), theVal=theVal([2,1]); end
2693                     
2694                     if theVal(1)<AConfig.Overlay.MinNegative, 
2695                         theVal(1) =AConfig.Overlay.MinNegative;
2696                     end
2697                     if theVal(2)>AConfig.Overlay.MaxPositive, 
2698                         theVal(2) =AConfig.Overlay.MaxPositive;
2699                     end
2700                     
2701                     AConfig.Overlay.ValueThrdMin =theVal(1);
2702                     AConfig.Overlay.ValueThrdMax =theVal(2);
2703                 end
2704                 theVal =(str2num(answer{2}));
2705                 if ~isempty(theVal), 
2706                     AConfig.Overlay.ValueThrdSeries =theVal;
2707                 else
2708                     AConfig.Overlay.ValueThrdSeries =NaN;
2709                 end
2710                 AConfig =ThresholdOverlayVolume(AConfig);
2711             end
2712         case 4, %Set AConfig.Overlay.LabelColor
2713             theColor =uisetcolor;
2714             if numel(theColor)==1 && theColor==0,    
2715                 %User canceled the color selection
2716             else
2717                 AConfig.Overlay.LabelColor =theColor;
2718             end
2719         case 5, %Set Color map parameters
2720             prompt ={sprintf('Overlay''s Color command: ( i.e. about how to generate the color map for overlay.)\n\n1. You can input 2 or 4 or 6...16 or 18 or 20... and so on. This way would generate a N-elements colorbar.\n2. "jet(64)" or other MATLAB command(such as "Winter(20)" and so on) would generate a smooth colorbar.\n3. ** means using default colormap that''s generated by command jet(64).)')};
2721             def    ={    AConfig.Overlay.ColorbarCmd };
2722             answer =inputdlg(prompt, 'Set color bar definition', 1, def);
2723             if numel(answer)==1,                
2724                 AConfig =DefineColorMap(AConfig, answer{1});                
2725             end
2726         case 6, %Save Image
2727             %YAN Chao-Gan 081223: add "save image as" function
2728             [filename, pathname] = uiputfile({'*.tiff';'*.jpeg';'*.png';'*.bmp'}, 'Save Image As');
2729             [tempPath, fileN, extn] = fileparts(filename);
2730             while isempty(strmatch(extn, strvcat('.tiff', '.jpeg', '.png','.bmp'),'exact'))
2731                 [filename, pathname] = uiputfile({'*.tiff';'*.jpeg';'*.png';'*.bmp'}, 'Save Image As');
2732                 [tempPath, fileN, extn] = fileparts(filename);
2733             end
2734             theFilename =fullfile(pathname,filename);
2735             set(gcf,'PaperPositionMode','auto')
2736             eval(['print -r600 -dtiff -noui ''',theFilename,''';']);
2737         case 7, %Correction Thresholds by AlphaSim
2738             %YAN Chao-Gan 090401: add "Correction Thresholds by AlphaSim"
2739             msgbox({'The Correction Thresholds correspond to a corrected P < 0.05 determined by the Monte Carlo simulations with the program AlphaSim in AFNI.';...
2740                 '';...
2741                 'Mask File: BrainMask_05_61x73x61.img (70831 voxels, under /mask directory)';...
2742                 '';...
2743                 'Gaussian kernel of spatially smooth: 4mm';...
2744                 '    p on individual voxel    Cluster size (voxels)';...
2745                 '             0.05                            54';...
2746                 '             0.01                            16';...
2747                 '            0.005                           11';...
2748                 '            0.001                            6';...
2749                 '';...
2750                 'Gaussian kernel of spatially smooth: 6mm';...
2751                 '    p on individual voxel    Cluster size (voxels)';...
2752                 '             0.05                           165';...
2753                 '             0.01                            39';...
2754                 '            0.005                           27';...
2755                 '            0.001                           13';...
2756                 '';...
2757                 'Gaussian kernel of spatially smooth: 8mm';...
2758                 '    p on individual voxel    Cluster size (voxels)';...
2759                 '             0.05                           324';...
2760                 '             0.01                            71';...
2761                 '            0.005                           48';...
2762                 '            0.001                           22';...
2763                 '';...
2764                 'Gaussian kernel of spatially smooth: 10mm';...
2765                 '    p on individual voxel    Cluster size (voxels)';...
2766                 '             0.05                           524';...
2767                 '             0.01                           119';...
2768                 '            0.005                           78';...
2769                 '            0.001                           34';...
2770                 },'Correction Thresholds by AlphaSim');
2771         case 99, %Save current map,
2772             %Todo, 20070916
2773             [filename, pathname] = uiputfile('*.jpg','Save current view: ');
2774             if isequal(filename,0) | isequal(pathname,0)           
2775             else
2776                theFilename =fullfile(pathname,filename);
2777                
2778                
2779                SaveCurrentView(AConfig, AFilename);
2780             end
2781         otherwise
2782         end
2783     % else
2784         % warndlg('Please Check on "SeeOverlay" before changing Overlay options!');
2785     % end%end if SeeOverlay(AConfig)
2786     %Reset position in Choice selection
2787     set(AConfig.hOverlayMisc, 'Value', 1);
2788     Result =AConfig;
2789 function Result =Open_Template(AConfig)    
2790     isNeedUpdate =false;
2791     switch get(AConfig.hTemplate, 'Value'),
2792     case 1,    %Overlay Misc
2793         %Do nothing
2794     case 2, %'Open Template AAL'
2795         rest_misc( 'CheckTemplate');
2796         theNewOverlay =fullfile(rest_misc( 'WhereIsREST'), 'Template', 'aal.nii'); %YAN Chao-Gan 081223: use the NIFTI image information from the MRIcroN
2797         set(AConfig.hOverlayFile, 'String', theNewOverlay);
2798         % rest_sliceviewer('ChangeOverlay', AConfig.hFig);
2799         AConfig =LoadOverlay(AConfig, theNewOverlay);
2800         set(AConfig.hSeeOverlay, 'Value', 1);
2801     case 3, %'Open Template Brodmann'
2802         rest_misc( 'CheckTemplate');
2803         theNewOverlay =fullfile(rest_misc( 'WhereIsREST'), 'Template', 'brodmann.nii'); %YAN Chao-Gan 081223: use the NIFTI image information from the MRIcroN
2804         set(AConfig.hOverlayFile, 'String', theNewOverlay);
2805         % rest_sliceviewer('ChangeOverlay', AConfig.hFig);
2806         AConfig =LoadOverlay(AConfig, theNewOverlay);
2807         set(AConfig.hSeeOverlay, 'Value', 1);
2808     case 4, %'Open Template Ch2'
2809         rest_misc( 'CheckTemplate');
2810         theNewUnderlay =fullfile(rest_misc( 'WhereIsREST'), 'Template', 'ch2.nii'); %YAN Chao-Gan 081223: use the NIFTI image information from the MRIcroN
2811         set(AConfig.hUnderlayFile, 'String', theNewUnderlay);
2812         % rest_sliceviewer('ChangeOverlay', AConfig.hFig);
2813         AConfig.Filename =theNewUnderlay;
2814         AConfig =InitUnderlay(AConfig);            
2815     otherwise
2816     end
2817     set(AConfig.hTemplate, 'Value', 1);
2818     Result =AConfig;
2819     
2820 function Result =CurrentCluster2Mask(AConfig)
2821 %Retrieve the cluster containing current point!
2822     % Result =ThresholdOverlayVolume(AConfig); %ThrdOverlayValue(AConfig, AConfig.Overlay.Volume);
2823     Result =AConfig.Overlay.VolumeThrd;
2824     [theCluster, theCount] =bwlabeln(Result);
2825     %Get the current point's position
2826     thePosition =Pos_Underlay2Overlay(AConfig, AConfig.LastPosition);
2827     if Result(thePosition(1),thePosition(2),thePosition(3))~=0, %Current point is valid and must reside in some cluster
2828         [pathstr, name, ext, versn] = fileparts(AConfig.Overlay.Filename);
2829         if strcmpi(name, 'aal') || strcmpi(name, 'brodmann'),
2830             theCurrentCluster = Result==Result(thePosition(1),thePosition(2),thePosition(3));
2831             Result(~theCurrentCluster)=0;
2832             return;
2833         else %BwlabelN not work for AAL or Brodmann whose clusters are adjacent
2834             %Get the current point's cluster's label and return the current cluster
2835             theCurrentCluster = theCluster==theCluster(thePosition(1),thePosition(2),thePosition(3));
2836             theCluster(~theCurrentCluster)=0;
2837             %transform the Result to a binary mask
2838             Result(~logical(theCluster))=0;
2839             Result =ceil(abs(Result));    %Revise for t-map just for not rounding to zero!
2840             return;
2841         end
2842     else
2843         Result =[];
2844     end    
2845     
2846 %Todo, 20070919
2847 function SaveCurrentView(AConfig, AFilename)
2848     %Hide most components and save the result
2849     theObjects =allchild(AConfig.hFig);
2850     for x=1:length(AConfig.hFig),
2851         if strcmpi(get(theObjects,'Type'), 'axes'),
2852         end
2853     end
2854            
2855     saveas(AConfig.hFig,theFilename);
2856     
2857 function Result =InitRecent(AConfig)
2858     Result =AConfig;     
2859     theRecentCfg =fullfile(rest_misc( 'WhereIsREST'), 'RecentUnderlay.txt');
2860     if  exist(theRecentCfg, 'file')==2,
2861         [Result.Recent.Underlay] =textread(theRecentCfg,'%s', 'delimiter','\n');
2862     else
2863         Result.Recent.Underlay={};
2864     end
2865     theRecentCfg =fullfile(rest_misc( 'WhereIsREST'), 'RecentOverlay.txt');
2866     if  exist(theRecentCfg, 'file')==2,
2867         [Result.Recent.Overlay] =textread(theRecentCfg,'%s', 'delimiter','\n');
2868     else
2869         Result.Recent.Overlay={};
2870     end    
2871     set(AConfig.hUnderlayRecent, 'String', [{'Underlay: '}; Result.Recent.Underlay], 'Value',1);
2872     set(AConfig.hOverlayRecent, 'String', [{'Overlay: '}; Result.Recent.Overlay], 'Value',1);
2873     
2874 function Result =AddRecentUnderlay(AConfig, AFilename)
2875     Result =AConfig;
2876     
2877     %20071102
2878     %Check whether there is space in the AFilename to prevent from problem TextRead not-function when space contained !
2879     if any(isspace(AFilename)),    return;    end;
2880     
2881     %check whether the same menu item exist
2882     theIndex =strmatch(lower(AFilename), lower(Result.Recent.Underlay), 'exact');
2883     if ~isempty(theIndex),
2884         %Move the item to the first
2885         for x=theIndex-1:-1:1,
2886             Result.Recent.Underlay{x+1} =Result.Recent.Underlay{x};
2887         end
2888     else        
2889         %Add
2890         if length(Result.Recent.Underlay)<6,%few
2891             Result.Recent.Underlay =[Result.Recent.Underlay; {''}];
2892         end
2893         for x=length(Result.Recent.Underlay):-1:2,
2894             Result.Recent.Underlay{x} =Result.Recent.Underlay{x-1};
2895         end
2896     end    
2897     Result.Recent.Underlay{1} =AFilename;        
2898     set(AConfig.hUnderlayRecent, 'String', [{'Underlay: '}; Result.Recent.Underlay], 'Value',1);    
2899     
2900 function Result =AddRecentOverlay(AConfig, AFilename)
2901     Result =AConfig;
2902     %20071102
2903     %Check whether there is space in the AFilename to prevent from problem TextRead not-function when space contained !
2904     if any(isspace(AFilename)),    return;    end;
2905     
2906     
2907     %check whether the same menu item exist
2908     theIndex =strmatch(lower(AFilename), lower(Result.Recent.Overlay), 'exact' );
2909     if ~isempty(theIndex),
2910         %Move the item to the first
2911         for x=theIndex-1:-1:1,
2912             Result.Recent.Overlay{x+1} =Result.Recent.Overlay{x};
2913         end
2914     else        
2915         %Add
2916         if length(Result.Recent.Overlay)<6,%few
2917             Result.Recent.Overlay =[Result.Recent.Overlay; {''}];
2918         end
2919         for x=length(Result.Recent.Overlay):-1:2,
2920             Result.Recent.Overlay{x} =Result.Recent.Overlay{x-1};
2921         end
2922     end        
2923     Result.Recent.Overlay{1} =AFilename;
2924     set(AConfig.hOverlayRecent, 'String', [{'Overlay: '}; Result.Recent.Overlay], 'Value',1);    
2925     
2926 function SaveRecent(AConfig, AType)
2927 %AType = RecentUnderlay.txt or RecentOverlay.txt
2928     theRecentCfg =fullfile(rest_misc( 'WhereIsREST'), [AType, '.txt']);
2929     if strcmpi(AType, 'RecentUnderlay'),
2930         theList =AConfig.Recent.Underlay;
2931     elseif strcmpi(AType, 'RecentOverlay'),
2932         theList =AConfig.Recent.Overlay;
2933     end
2934     hFile =fopen(theRecentCfg, 'w');
2935     if hFile>0,                    
2936         for x=1:length(theList),
2937             fprintf(hFile, '%s\r\n', theList{x});
2938         end        
2939         fclose(hFile);
2940     else 
2941         error(sprintf('Can''t write config file: %s', theRecentCfg));
2942     end        
2943     
2944 %20070921, Colorbar definition/regeneratioin
2945 function Result =DefineColorMap(AConfig, AColorDefCmd)    
2946     Result =AConfig;
2947     try
2948         theNumberCmd =str2double(AColorDefCmd);
2949         if ~isnan(theNumberCmd), %2,4,6...20 and is even!
2950             if mod(theNumberCmd,2)==1 || theNumberCmd>20,
2951                 errordlg(sprintf('The number must be even because there must be even numbers of colors in the colormap.\n\n And the Number must be less than 20. \n\nIllegal for your input: %d.', theNumberCmd), rest_misc( 'GetRestVersion'));                
2952                 return;
2953             else
2954                 if theNumberCmd<2, theNumberCmd =2; AColorDefCmd='2'; end %for not zero encountered!
2955                 theColormap =jet(theNumberCmd);
2956             end            
2957         else    %It is an USER DEFINED MATLAB command to generate the color map
2958             if strcmpi(AColorDefCmd, '**'), %Use default color map
2959                 theColormap =jet(64);
2960             else    %Evaluate the user's command in MATLAB
2961                 theColormap=eval(AColorDefCmd);
2962             end
2963         end
2964         %Save the color-bar's definition
2965         AConfig.Overlay.ColorbarCmd =AColorDefCmd;
2966         AConfig.Overlay.Colormap     =theColormap;
2967         Result =DrawColorbar(AConfig);
2968     catch        
2969         rest_misc( 'DisplayLastException');
2970         errordlg('Error occured! Input may be illegal!');
2971     end    
2972     
2973 function Result =DrawColorbar(AConfig)
2974     Result =AConfig;
2975     %Set whether to show the color bar
2976     [pathstr, name, ext, versn] = fileparts(AConfig.Overlay.Filename);
2977     if SeeOverlay(AConfig) && ~strcmpi(name,'aal') && ~strcmpi(name,'brodmann'),
2978         set(AConfig.hAxesColorbar, 'Visible', 'on');
2979         set(AConfig.hImageColorbar,'Visible', 'on');
2980     else
2981         set(AConfig.hAxesColorbar, 'Visible', 'off');
2982         set(AConfig.hImageColorbar,'Visible', 'off');
2983         %Clear old labels
2984         theLabels =findobj(AConfig.hAxesColorbar, 'Type', 'text');
2985         for theX=1:length(theLabels), delete(theLabels(theX)); end
2986         return;
2987     end
2988     
2989     
2990     theColorbarWidth =20;
2991     %Set the colorbar's position according to the figure's height
2992     MarginX =10; MarginY =10;
2993     thePos =get(AConfig.hFig, 'Position');
2994     if strcmpi(AConfig.ViewMode, 'Orthogonal'),
2995         theAxesPosTop  =get(AConfig.hAxesSagittal, 'Position');
2996         theAxesPosDown =get(AConfig.hAxesTransverse, 'Position');
2997         theLeft     =theAxesPosTop(1) +theAxesPosTop(3) +MarginX;
2998         theHeight    =theAxesPosTop(4) +theAxesPosDown(4);
2999         theColorBarPos =[theLeft, MarginY, theColorbarWidth, theHeight];
3000     elseif strcmpi(AConfig.ViewMode, 'Sagittal'),
3001         theAxesPos  =get(AConfig.hAxesSagittal, 'Position');        
3002         theLeft     =theAxesPos(1) +theAxesPos(3) +MarginX;
3003         theHeight    =theAxesPos(4);
3004         theColorBarPos =[theLeft, MarginY, theColorbarWidth, theHeight];
3005     elseif strcmpi(AConfig.ViewMode, 'Transverse'),
3006         theAxesPos  =get(AConfig.hAxesTransverse, 'Position');        
3007         theLeft     =theAxesPos(1) +theAxesPos(3) +MarginX;
3008         theHeight    =theAxesPos(4);
3009         theColorBarPos =[theLeft, MarginY, theColorbarWidth, theHeight];
3010     elseif strcmpi(AConfig.ViewMode, 'Coronal'),
3011         theAxesPos  =get(AConfig.hAxesCoronal, 'Position');        
3012         theLeft     =theAxesPos(1) +theAxesPos(3) +MarginX;
3013         theHeight    =theAxesPos(4);
3014         theColorBarPos =[theLeft, MarginY, theColorbarWidth, theHeight];
3015     end
3016     set(AConfig.hAxesColorbar, 'Position', theColorBarPos);
3017         
3018     
3019     theNumberCmd =str2double(AConfig.Overlay.ColorbarCmd);
3020     if ~isnan(theNumberCmd), %2,4,6...20 and is even!
3021         %Draw a element-divided colorbar, each element-color is defined by the coordesponding color in jet(theNumberColorElements)
3022         theColormap =reshape(AConfig.Overlay.Colormap, [size(AConfig.Overlay.Colormap,1), 1, size(AConfig.Overlay.Colormap,2)]);
3023         theColormap =repmat(theColormap, [1 theColorbarWidth 1]);
3024         if rest_misc('GetMatlabVersion')>=7.4   %YAN Chao-Gan 090401: The imresize function has been completely rewritten in Matlab R2007a. Fixed the bug of 'Set Overlay's Color bar' in Matlab R2007a or latter version.
3025             theColormap =imresize_old(theColormap, [theColorBarPos(4), theColorbarWidth]);
3026         else
3027             theColormap =imresize(theColormap, [theColorBarPos(4), theColorbarWidth]);
3028         end
3029         theDivideLine =reshape(get(AConfig.hFig, 'Color'), [1 1 3]);
3030         theDivideLine =repmat(theDivideLine, [3, theColorbarWidth, 1]);
3031         for x=1:theNumberCmd-1,
3032             theGrayLinePos = floor(x*(theColorBarPos(4)/theNumberCmd) +[-1 0 1]);
3033             theColormap(theGrayLinePos, :, :) = theDivideLine;            
3034         end
3035     else    %Evaluate the user's command in MATLAB  and %Draw a smooth colorbar
3036         %Build the image to show
3037         theColormap =reshape(AConfig.Overlay.Colormap, [size(AConfig.Overlay.Colormap,1), 1, size(AConfig.Overlay.Colormap,2)]);
3038         theColormap =repmat(theColormap, [1 theColorbarWidth 1]);
3039     end
3040     
3041     set(AConfig.hImageColorbar, 'CData', (theColormap), 'HitTest', 'off','Visible', 'on');
3042     set(AConfig.hAxesColorbar,'Visible', 'on', 'XLim', [1 size(theColormap,2)], ...
3043         'YLim', [1 size(theColormap,1)]);
3044     
3045     
3046     %Clear old labels
3047     theLabels =findobj(AConfig.hAxesColorbar, 'Type', 'text');
3048     for theX=1:length(theLabels), delete(theLabels(theX)); end
3049     %Add new labels
3050     if ~isnan(theNumberCmd), %2,4,6...20 and is even!
3051         %Draw a element-divided colorbar, each element-color is defined by the coordesponding color in jet(theNumberColorElements)
3052         %        for x=1:(theNumberCmd+1),
3053         %Draw negative lables
3054         for x=1:theNumberCmd/2,
3055             theGrayLinePos  = floor((x-1)*(theColorBarPos(4)/theNumberCmd));
3056             
3057             if theNumberCmd/2 >1,
3058                 thePercentValue = AConfig.Overlay.MinNegative +(AConfig.Overlay.MaxNegative -AConfig.Overlay.MinNegative) /(theNumberCmd/2 -1)  * (x-1);
3059             elseif theNumberCmd/2 ==1,
3060                 thePercentValue = AConfig.Overlay.MinNegative;
3061             end
3062             
3063             text( 1.5* theColorbarWidth, theGrayLinePos, sprintf('%+g',thePercentValue), 'Parent', AConfig.hAxesColorbar, 'Color', 'black', 'HitTest', 'off', 'Units', 'pixels', 'VerticalAlignment', 'bottom', 'FontName','FixedWidth', 'FontSize', 10);
3064         end
3065         %Draw positive lables
3066         for x=(theNumberCmd/2+1):theNumberCmd,
3067             theGrayLinePos  = floor((x-1+1)*(theColorBarPos(4)/theNumberCmd)) -12;
3068             
3069             if theNumberCmd/2 >1,
3070                 thePercentValue = AConfig.Overlay.MinPositive +(AConfig.Overlay.MaxPositive -AConfig.Overlay.MinPositive) /(theNumberCmd -1 -theNumberCmd/2)  * (x-1 -theNumberCmd/2);
3071             elseif theNumberCmd/2 ==1,
3072                 thePercentValue = AConfig.Overlay.MaxPositive;
3073             end
3074             
3075             text( 1.5* theColorbarWidth, theGrayLinePos, sprintf('%+g',thePercentValue), 'Parent', AConfig.hAxesColorbar, 'Color', 'black', 'HitTest', 'off', 'Units', 'pixels', 'VerticalAlignment', 'bottom', 'FontName','FixedWidth', 'FontSize', 10);
3076         end
3077     else        %Draw labels for smooth display
3078         %Draw negative lables
3079         text( 1.5* theColorbarWidth, 0, sprintf('%g',AConfig.Overlay.MinNegative), 'Parent', AConfig.hAxesColorbar, 'Color', 'black', 'HitTest', 'off', 'Units', 'pixels', 'VerticalAlignment', 'bottom');
3080         text( 1.5* theColorbarWidth, floor(theColorBarPos(4)/2)-10, sprintf('%g',AConfig.Overlay.MaxNegative), 'Parent', AConfig.hAxesColorbar, 'Color', 'black', 'HitTest', 'off', 'Units', 'pixels', 'VerticalAlignment', 'bottom');
3081         %Draw positive lables
3082         text( 1.5* theColorbarWidth, ceil(theColorBarPos(4)/2)+10, sprintf('%g',AConfig.Overlay.MinPositive), 'Parent', AConfig.hAxesColorbar, 'Color', 'black', 'HitTest', 'off', 'Units', 'pixels', 'VerticalAlignment', 'bottom');
3083         text( 1.5* theColorbarWidth, theColorBarPos(4), sprintf('%g',AConfig.Overlay.MaxPositive), 'Parent', AConfig.hAxesColorbar, 'Color', 'black', 'HitTest', 'off', 'Units', 'pixels', 'VerticalAlignment', 'bottom');
3084     end    
3085     
3086     ResizeFigure(AConfig);
3087     
3088 function Result =SetColorElements(AConfig)    
3089 %Callback by clicking the color element on the color bar
3090     %1. Detect which element was clicked
3091     %2. Change the color and save
3092     
3093     theAxes            =get(AConfig.hFig, 'CurrentObject');
3094     %Check legal click point in the axes
3095     thePoint        =get(theAxes,'CurrentPoint');
3096     thePoint         =round(thePoint(1, 1:2));
3097     theXLim =get(theAxes, 'XLim');
3098     theYLim =get(theAxes, 'YLim');    
3099     if thePoint(1)<theXLim(1) || thePoint(1)>theXLim(2) ...
3100        || thePoint(2)<theYLim(1) || thePoint(2)>theYLim(2) ,
3101         Result =AConfig;
3102         return;
3103     end
3104     
3105     theColorBarPos =get(AConfig.hAxesColorbar, 'Position');
3106     theNumberCmd =str2double(AConfig.Overlay.ColorbarCmd);
3107     if ~isnan(theNumberCmd), %2,4,6...20 and is even!
3108         % theColorbar =get(AConfig.hImageColorbar, 'CData');
3109         % uisetcolor(theColorbar(thePoint(2), 1, :));
3110         theColorIndex =1+ floor(thePoint(2)/(theColorBarPos(4)/theNumberCmd));
3111         theColor =uisetcolor(AConfig.Overlay.Colormap(theColorIndex, :));
3112         if numel(theColor==3),%User defined a color, didn't clicked Cancel btn
3113             AConfig.Overlay.Colormap(theColorIndex, :) =theColor;
3114         end
3115     end
3116     Result =AConfig;
3117     return;
3118     
3119     
3120 
3121 function ToggleInfoDisplay(AConfig);
3122     theTitle ='Click to Toggle Hdr info';
3123     theOldMsg =get(AConfig.hMsgLabel, 'String');
3124     if strcmpi(theTitle, theOldMsg),
3125         set(AConfig.hMsgLabel, 'String', 'Anything not same with theTitle');
3126     else
3127         set(AConfig.hMsgLabel, 'String', theTitle);
3128     end
3129     SetMessage(AConfig);
3130     ResizeFigure(AConfig);
3131     
3132 
3133 
3134         
3135 
3136     
3137 function Result =OnKeyPress(AConfig)
3138 %Processing up/down left/right J/K F1/F2... to responding previous slice or next slice
3139     %left=0x1C, right=0x1D, up=0x1E, down=0x1F
3140     %j =0x6A, k=0x6B;
3141     %J=0x4A, K=0x4B
3142     %F1, F2 not known! MATLAB not responding!
3143     %disp(sprintf('%x',(get(AConfig.hFig, 'CurrentCharacter'))));
3144     Result =AConfig;
3145     theKey =get(AConfig.hFig, 'CurrentCharacter');
3146     if isempty(theKey), return; end
3147     if any(theKey==hex2dec(['1c';'1f';'6a';'4a';])),
3148         Result =Slice2Previous(AConfig);
3149     elseif any(theKey==hex2dec(['1d';'1e';'6b';'4b';])),
3150         Result =Slice2Next(AConfig);
3151     end
3152     
3153 function Result =Slice2Previous(AConfig)
3154     Result =AConfig;
3155     switch lower(AConfig.LastAxes),
3156     case 'transverse',
3157         AConfig.LastPosition(1) =AConfig.LastPosition(1)-1;
3158         while AConfig.LastPosition(1) <1,
3159             AConfig.LastPosition(1) = AConfig.LastPosition(1) +size(AConfig.Volume, 1);
3160         end
3161     case 'coronal',
3162         AConfig.LastPosition(2) =AConfig.LastPosition(2)-1;
3163         while AConfig.LastPosition(2) <1,
3164             AConfig.LastPosition(2) = AConfig.LastPosition(2) +size(AConfig.Volume, 2);
3165         end
3166     case 'sagittal',
3167         AConfig.LastPosition(3) =AConfig.LastPosition(3)-1;
3168         while AConfig.LastPosition(3) <1,
3169             AConfig.LastPosition(3) = AConfig.LastPosition(3) +size(AConfig.Volume, 3);
3170         end
3171     end
3172     Result =AConfig;
3173     
3174 function Result =Slice2Next(AConfig)
3175     Result =AConfig;
3176     switch lower(AConfig.LastAxes),
3177     case 'transverse',
3178         AConfig.LastPosition(1) =AConfig.LastPosition(1)+1;
3179         while AConfig.LastPosition(1) >size(AConfig.Volume, 1),
3180             AConfig.LastPosition(1) = AConfig.LastPosition(1) -size(AConfig.Volume, 1);
3181         end
3182     case 'coronal',
3183         AConfig.LastPosition(2) =AConfig.LastPosition(2)+1;
3184         while AConfig.LastPosition(2) >size(AConfig.Volume, 2),
3185             AConfig.LastPosition(2) = AConfig.LastPosition(2) -size(AConfig.Volume, 2);
3186         end
3187     case 'sagittal',
3188         AConfig.LastPosition(3) =AConfig.LastPosition(3)+1;
3189         while AConfig.LastPosition(3) >size(AConfig.Volume, 3),
3190             AConfig.LastPosition(3) = AConfig.LastPosition(3) -size(AConfig.Volume, 3);
3191         end
3192     end
3193     Result =AConfig;
3194     
3195 function Result =UpdatePosition(AConfig, ACurrentPosition)
3196     %Set the last axes by comparing the last position's value change
3197     theV =sum(AConfig.LastPosition==ACurrentPosition);
3198     if theV==1,        
3199         %Clicking one image/axes
3200         switch find(AConfig.LastPosition==ACurrentPosition),
3201         case 1,
3202             AConfig.LastAxes ='Transverse';
3203         case 2,
3204             AConfig.LastAxes ='Coronal';
3205         case 3,
3206             AConfig.LastAxes ='Sagittal';
3207         end
3208     elseif theV==2,
3209         %Directly Setting the value in the edit control
3210         switch find(AConfig.LastPosition~=ACurrentPosition),
3211         case 1,
3212             AConfig.LastAxes ='Transverse';
3213         case 2,
3214             AConfig.LastAxes ='Coronal';
3215         case 3,
3216             AConfig.LastAxes ='Sagittal';
3217         end
3218     end
3219     AConfig.LastPosition =ACurrentPosition;
3220     Result =AConfig;
3221     
3222 function ToDo    
3223 %ToDo, 20070921
3224 %1. Show/Hide information
3225 %2. Set Min or Max for thresholding and this should has priority
3226 %Done 20070922
3227

Generated on Wed 29-Apr-2009 01:06:38 by m2html © 2005