function varargout = prtUtilSubplotTitle(varargin)
%   prtUtilSubplotTitle add titles to subplots
%
%   prtUtilSubplotTitle(STRING) makes string STRING the title*(see note) across all
%   available sub-plots in the current figure.
%
%   prtUtilSubplotTitle(AXESLIST,STRING) place the title STRING over only the
%   axes specified in AXESLIST (a list of axes handles as generated by
%   subplot or equivalent).
%
%   For example:
%
%       clear all; close all;
%       a1 = subplot(3,3,1); plot(1:10); 
%       a1_2 = subplot(3,3,2); plot(sin(linspace(0,2*pi)*5)); 
%       a1_3 = subplot(3,3,3); plot(cos(linspace(0,2*pi)*5)); 
%       a2 = subplot(3,3,[4,7]); h = surf(peaks); set(h,'EdgeAlpha',0);
%       a3 = subplot(3,3,[5,8]); h = surf(-peaks); set(h,'EdgeAlpha',0);
%       a4 = subplot(3,3,[6,9]); mesh(randn(10)); 
%       
%       th1 = subplot_title(a1,'Plot of 1-10');
%       th2 = subplot_title([a1_2,a1_3],'Plot of Sinusoids');
%       th3 = subplot_title([a2 a3],'SURF Pics');
%       th4 = subplot_title([a4],'Mesh');
%       
%   *Note that subplot_title creates invisible axes to make these new
%   titles, the handles to which are lost after subplot_title exits.  As a
%   result, multiple calls to subplot_title in a row over the same set of
%   axes will result in multiple overlaying titles.  This is undesirable.
%   To mediate these effects, use title_handle to erase current titles
%   prior to calling subplot_title multiple times.







% Originally written as subplot_title, part of FROI:
%   This function is part of froi, available from http://froi.sourceforge.net,
%   and is governed under the terms of the Artistic License.


%Mod History:
ax = gca;
cfig = gcf;

if nargin == 1
    title_string = varargin{1};
    relevantAxes = findobj(gcf, 'Type', 'axes', 'Box', 'on');
elseif nargin == 2
    relevantAxes = varargin{1};
    title_string = varargin{2};
elseif nargin > 2
    if ischar(varargin{1}) || iscell(varargin{1})
        title_string = varargin{1};
        relevantAxes = findobj(gcf, 'Type', 'axes', 'Box', 'on');
    else
        relevantAxes = varargin{1};
        title_string = varargin{2};
    end
end
    

if isempty(relevantAxes);
    error('No current axes available for titling');
end

for i = 1:length(relevantAxes);
    P(i,:) = get(relevantAxes(i),'Position');
end

minX = min(P(:,1));
maxX = max(P(:,3) + P(:,1));
minY = min(P(:,2));
maxY = max(P(:,4) + P(:,2));

axes('position',[minX minY maxX-minX maxY-minY],'Box','off','Visible','off');

if nargin > 2
    if ~any(ishandle(varargin{1}))
        title_handle = title(title_string,varargin{2:end});
    else
        title_handle = title(title_string,varargin{3:end});
    end
else
    title_handle = title(title_string);
end

set(title_handle,'visible','on');

children = get(gcf,'Children');
set(gcf,'Children',[children(2:end); children(1)])

figure(cfig);

if nargout>0
    varargout{1} = title_handle;
end
