function varargout = tessellation_handler(varargin)
%TESSELLATION_HANDLER - : Basic Viewing of tessellation objects in BrainStorm format; GUI Manager
% function varargout = tessellation_handler(varargin)
%    FIG = TESSELLATION_HANDLER launch tessellation_handler GUI.
%    TESSELLATION_HANDLER('callback_name', ...) invoke the named callback.

%<autobegin> ---------------------- 26-May-2004 11:34:36 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Visualization
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_color_scheme.m
%   toolbox\bst_layout.m
%   toolbox\find_brainstorm_files.m
%   toolbox\get_user_directory.m
%   toolbox\tessellation_handler.m  NOTE: Routine calls itself explicitly
%
% Subfunctions in this file, in order of occurrence in file:
%   varargout = TessellationFilesList_Callback(h, eventdata, handles, varargin)
%   varargout = EnvelopeList_Callback(h, eventdata, handles, varargin)
%   varargout = ImportFiles_Callback(h, eventdata, handles, varargin)
%   varargout = RenameEnvelope_Callback(h, eventdata, handles, varargin)
%   varargout = CurrentEnvelope_Callback(h, eventdata, handles, varargin)
%   varargout = DeleteEnvelope_Callback(h, eventdata, handles, varargin)
%   varargout = DownsizeEnvelope_Callback(h, eventdata, handles, varargin)
%   varargout = ConcatenateEnvelopes_Callback(h, eventdata, handles, varargin)
%   varargout = ViewEnvelope_Callback(h, eventdata, handles, varargin)
%   varargout = SwapFaces_Callback(h, eventdata, handles, varargin)
%   varargout = Save_Callback(h, eventdata, handles, varargin)
%   varargout = SaveAs_Callback(h, eventdata, handles, varargin)
%   varargout = HDone_Callback(h, eventdata, handles, varargin)
%
% Application data and their calls in this file:
%   'Comment'
%   'TessellationFiles'
%   'TileType'
%   'nFaces'
%   'nVertices'
%   
%   setappdata(fig,'TessellationFiles',TessFiles);
%   setappdata(fig,'TileType','T');
%   setappdata(handles.figure1,'Comment',Comment)
%   setappdata(handles.figure1,'nFaces',nFaces)
%   setappdata(handles.figure1,'nVertices',nVertices)
%   
%   TessFiles = getappdata(handles.figure1,'TessellationFiles');
%   nFaces = getappdata(handles.figure1,'nFaces');
%   nVertices = getappdata(handles.figure1,'nVertices');
%
% Figure Files opened by this function:
%   mfilename
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure tessellation_handler.fig
%   uicontrol:frame:frame1 "" uses Callback for <automatic>
%   uicontrol:frame:frame4 "" uses Callback for <automatic>
%   uicontrol:listbox:EnvelopeList "" uses Callback for <automatic>
%   uicontrol:popupmenu:TessellationFilesList "N/A" uses Callback for <automatic>
%   uicontrol:pushbutton:ConcatenateEnvelopes "Concatenate" uses Callback for <automatic>
%   uicontrol:pushbutton:DeleteEnvelope "Delete" uses Callback for <automatic>
%   uicontrol:pushbutton:DownsizeEnvelope "Downsize" uses Callback for <automatic>
%   uicontrol:pushbutton:HDone "Done" uses Callback for <automatic>
%   uicontrol:pushbutton:ImportFiles "Import" uses Callback for <automatic>
%   uicontrol:pushbutton:pushbutton16 "Cancel" uses Callback for <automatic>
%   uicontrol:pushbutton:RenameEnvelope "Rename" uses Callback for <automatic>
%   uicontrol:pushbutton:Save "Save" uses Callback for <automatic>
%   uicontrol:pushbutton:SaveAs "Save as" uses Callback for <automatic>
%   uicontrol:pushbutton:SwapFaces "Swap faces" uses Callback for <automatic>
%   uicontrol:pushbutton:ViewEnvelope "View" uses Callback for <automatic>
%   uicontrol:text:FacesVertices "n/a Faces - n/a Vertices" uses Callback for ''
%   uicontrol:text:HowManyEnvelopes "Envelope(s)" uses Callback for
%     tessellation_handler('text2_Callback',gcbo,[],guidata(gcbo))
%   uicontrol:text:HowManyFiles "Tessellation File(s)" uses Callback for
%     tessellation_handler('text1_Callback',gcbo,[],guidata(gcbo))
%
% At Check-in: $Author: Mosher $  $Revision: 7 $  $Date: 5/26/04 10:02a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 26-May-2004 11:34:36 -----------------------


% Last Modified by GUIDE v2.0 11-Nov-2003 09:12:32

if nargin == 0  % LAUNCH GUI
	
	% Open and make the GUI look good
	fig = openfig(mfilename,'reuse');
	setappdata(fig,'TileType','T');
	bst_color_scheme(fig);
	bst_layout('align',fig,2,2,4);
	set(fig,'visible','on')
	
	% Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
	guidata(fig, handles);
	
	% Look for tessellation files in current subject folder
	Users = get_user_directory;
	SubjectPath = fileparts(fullfile(Users.SUBJECTS,Users.CurrentData.SubjectFile));
	TessFiles = find_brainstorm_files('tess',SubjectPath);
	if isempty(TessFiles)
		TessFiles = {'N/A'};
		set(handles.TessellationFilesList,'Enable','off')
		nEnvelopes = 0; 
	else
		set(handles.TessellationFilesList,'Enable','on')
		nEnvelopes = length(TessFiles);    
	end
	set(handles.TessellationFilesList,'String',TessFiles,'Value',1,'Max',nEnvelopes)
	set(handles.HowManyFiles,'String',sprintf('%d Tessellation file(s)',nEnvelopes))
	
	% Store tessellation files
	setappdata(fig,'TessellationFiles',TessFiles); 
	
	% Display info about first tessellation in list
	TessellationFilesList_Callback(fig,[],handles)
	
	if nargout > 0
		varargout{1} = fig;
	end
	
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
	
	try
		if (nargout)
			[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
		else
			feval(varargin{:}); % FEVAL switchyard
		end
	catch
		disp(lasterr);
	end
	
end


%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and 
%| sets objects' callback properties to call them through the FEVAL 
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the 
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback.  You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks.  Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.



% --------------------------------------------------------------------
function varargout = TessellationFilesList_Callback(h, eventdata, handles, varargin)

% Display information about selected tessellation file

set(handles.figure1,'pointer','watch')
drawnow

set(handles.EnvelopeList,'Value',1)

TessFiles = getappdata(handles.figure1,'TessellationFiles');
iFile = get(handles.TessellationFilesList,'Value'); % Which file is selected ?
if strcmpi(TessFiles{iFile},'N/A') % No file available, return
	set(fig,'pointer','arrow')
	return
end


Users = get_user_directory;
SubjectPath = fileparts(fullfile(Users.SUBJECTS,Users.CurrentData.SubjectFile));
cd(SubjectPath)
load(TessFiles{iFile},'Comment','Faces','Vertices')

if isempty(Comment) 
	% empty tessellation file - delete
	ButtonName=questdlg('This file is apparently empty - would you like to remove it from disk?', ...
		'DataBase Cleaning', ...
		'Yes','No','No');
	switch(ButtonName)
	case 'No'
		set(fig,'pointer','arrow')
		return
	case 'Yes'
		switch(upper(computer))
		case('PCWIN')
			dos(sprintf('del %s', TessFiles{iFile}));
		case ('UNIX')
			unix(sprintf('rm %s %s', TessFiles{iFile}));
		end
		tessellation_handler
	end
else
	set(handles.EnvelopeList,'string',Comment)
	
	for k = 1:length(Faces);
		nFaces(k) = size(Faces{k},1);
	end
	clear Faces
	for k = 1:length(Vertices);
		nVertices(k) = size(Vertices{k},2);
	end
	clear Vertices
	
	setappdata(handles.figure1,'Comment',Comment)
	setappdata(handles.figure1,'nFaces',nFaces)
	setappdata(handles.figure1,'nVertices',nVertices)
	
	set(handles.HowManyEnvelopes,'String',sprintf('%d Envelope(s)',length(Comment)));
	set(handles.EnvelopeList,'Max',length(Comment),'Value',1)
	
	EnvelopeList_Callback(h,[],handles); % Get info from first envelope in list
	
end


set(handles.figure1,'pointer','arrow')


% --------------------------------------------------------------------
function varargout = EnvelopeList_Callback(h, eventdata, handles, varargin)


% Display info related to selected envelope in tessellation file

iCurrent = get(handles.EnvelopeList,'Value'); % what's the current envelope ?

nFaces = getappdata(handles.figure1,'nFaces');
nVertices = getappdata(handles.figure1,'nVertices');
	

try 
	if length(nFaces) == length(nVertices) % several envelopes of different tissues are stored (pre-MMII convention)
		set(handles.FacesVertices,'String',sprintf('%d Faces - %d Vertices',nFaces(iCurrent),nVertices(iCurrent)))
	else % Variations of the same envelope: number of faces and vertices is the same for all variations 
		set(handles.FacesVertices,'String',sprintf('%d Faces - %d Vertices',nFaces(1),nVertices(1)))
	end
catch
	set(handles.EnvelopeList,'Value', min(iCurrent));
	EnvelopeList_Callback(h, eventdata, handles)
	return
end




% --------------------------------------------------------------------
function varargout = ImportFiles_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = RenameEnvelope_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = CurrentEnvelope_Callback(h, eventdata, handles, varargin)


% --------------------------------------------------------------------
function varargout = DeleteEnvelope_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = DownsizeEnvelope_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = ConcatenateEnvelopes_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = ViewEnvelope_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = SwapFaces_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = Save_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = SaveAs_Callback(h, eventdata, handles, varargin)




% --------------------------------------------------------------------
function varargout = HDone_Callback(h, eventdata, handles, varargin)




