function [mappnames,figname] = find_mfiles(h,VERBOSE);
%FIND_MFILES - Find m-files that open a particular figure handle or the GCF
% function [mappnames,figname] = find_mfiles(h,VERBOSE);
% Given a figure handle, find m-files that open it or its associated m-file. 
%
% H is optional, with default of GCF
% VERBOSE is optional, with default of 1;
%
% MAPPNAMES is the m-file application filenames
% FIGNAME is the name of the file associated with the figure
% First file returned in mappnames should be the same name, if such one exists.
% 
% The BrainStorm Contents also list files that open the figure
%
% See also CONTENTS, GCF

%<autobegin> ---------------------- 12-Oct-2004 01:11:15 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Database Management
%
% Alphabetical list of external functions (non-Matlab):
%   developers\mosher\developmenttools_v2\str2cell.m
%
% Group : Preference data and their calls in this file:
%   HOME = getpref('BrainStorm','brainstormHomeDir');
%
% At Check-in: $Author: Mosher $  $Revision: 3 $  $Date: 10/11/04 11:32p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 23-Sep-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> ------------------------ 12-Oct-2004 01:11:15 -----------------------


% ----------------------------- Script History ---------------------------------
% JCM 17-Jun-2004 Creation by John C. Mosher, Ph.D.
% ----------------------------- Script History ---------------------------------


if ~exist('h','var'),
   h = gcf;
end

if ~ishandle(h),
   disp(sprintf('%s: Invalid handle on input',mfilename))
   return
end

if ~exist('VERBOSE','var'),
   VERBOSE = 1;
end

mappnames = []; % initialize as empty

figname = get(h,'filename');

if isempty(figname),
   disp('No .fig name associated with the current graphics figure');
   return
end

if VERBOSE,
   disp(sprintf('Filename for the current graphics figure is %s',figname));
end

[ignore,rootfilename,ext] = fileparts(figname);


if ~ispc,
   disp(sprintf('Sorry, this routine "%s" is currently written only for PCs.',mfilename))
   disp(sprintf('Please look at the contents.m file for help with this figure name: %s.fig',rootfilename));
   helpwin('contents.m')
   return
end

% now look for explicit calling
HOME = getpref('BrainStorm','brainstormHomeDir');
cd(fullfile(HOME,'Toolbox'))

[s,w] = dos(sprintf('findstr /c:"%s" %s',rootfilename,'*.m'));

if(~s), % good return
    w = str2cell(w); % convert to cell array
    w = w(:); % vertical
    
    % now trim off the filenames from the returns
    for i = 1:length(w),
        sep = findstr(w{i},':'); % separator
        line = w{i}(sep(1)+1:end); % the line containing this filename
        if(~strcmp('%',line(1))), % not a comment line            
            w{i} = w{i}(1:(sep(1)-1)); % trim out filename
        else
            w{i} = ' '; % blank out filename
        end
    end
    
    w(strcmp(' ',w)) = []; % remove the blank filenames
    
    if(~isempty(mappnames))
       mappnames = [mappnames;w];
    else
       mappnames = w;
    end
    
    mappnames = unique(mappnames);
    
    mappnames(strcmp('contents.m',mappnames)) = []; % strip the contents if found
    % Remove any help files which don't need to be listed
    mappnames(strncmp('help_',mappnames,length('help_'))) = [];
    
 end
    
% the easy one
% we are looking for a corresponding m-file application
tdir = dir([rootfilename '.m']);

if(~isempty(tdir)),
    samename = {tdir.name}; % m-file has same root name as figure
    mappnames(strcmp(samename,mappnames)) = []; % remove if already in list
    mappnames = [samename;mappnames]; % the mates are now below
end

if VERBOSE,
   disp(sprintf('The following m-files either open directly the figure %s.fig or call the m-file %s.m',...
      rootfilename,rootfilename))
end
