function handle=mycolorbar2(loc,iirev,bar_label)
%COLORBAR Display color bar (color scale).
%   COLORBAR('vert') appends a vertical color scale to the current
%   axis. COLORBAR('horiz') appends a horizontal color scale.
%
%   COLORBAR(H) places the colorbar in the axes H. The colorbar will
%   be horizontal if the axes H width > height (in pixels).
%
%   COLORBAR without arguments either adds a new vertical color scale
%   or updates an existing colorbar.
%
%   H = COLORBAR(...) returns a handle to the colorbar axis.

%   Clay M. Thompson 10-9-92
%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 5.27 $  $Date: 1997/12/18 17:04:01 $

%   If called with COLORBAR(H) or for an existing colorbar, don't change
%   the NextPlot property.
if nargin<3, bar_label=[]; end
%
changeNextPlot = 1;

if nargin<1, loc = 'vert'; end
if nargin<2, iirev=0; end

% Catch colorbar('delete') special case -- must be called by the deleteFcn.
if nargin==1 & strcmp(loc,'delete'),
  ax = gcbo;
  if strcmp(get(ax,'tag'),'TMW_COLORBAR'), ax=get(ax,'parent'); end
  ud = get(ax,'userdata');
  if isfield(ud,'PlotHandle') & ishandle(ud.PlotHandle) & ...
     isfield(ud,'origPos') & ~isempty(ud.origPos)
     set(ud.PlotHandle,'position',ud.origPos);
  end
  if isfield(ud,'DeleteProxy') & ishandle(ud.DeleteProxy)
    delete(ud.DeleteProxy)
  end
  return
end
% Delete existing colorbar:
ch=get(gcf,'Children');
tags=get(ch,'Tag');
iich=find(strcmp(tags,'Colorbar'));
if length(ch)<=2 & length(iich)==1,
	delete(ch(iich));
end

ax = [];
if nargin==1,
    if ishandle(loc)
        ax = loc;
        if ~strcmp(get(ax,'type'),'axes'),
            error('Requires axes handle.');
        end
        units = get(ax,'units'); set(ax,'units','pixels');
        rect = get(ax,'position'); set(ax,'units',units)
        if rect(3) > rect(4), loc = 'horiz'; else loc = 'vert'; end
        changeNextPlot = 0;
    end
end

% Determine color limits by context.  If any axes child is an image
% use scale based on size of colormap, otherwise use current CAXIS.

ch = get(gca,'children');
hasimage = 0; t = [];
cdatamapping = 'direct';

for i=1:length(ch),
    typ = get(ch(i),'type');
    if strcmp(typ,'image'),
        hasimage = 1;
        cdatamapping = get(ch(i), 'CDataMapping');
    elseif strcmp(typ,'surface') & ...
            strcmp(get(ch(i),'FaceColor'),'texturemap') % Texturemapped surf
        hasimage = 2;
        cdatamapping = get(ch(i), 'CDataMapping');
    elseif strcmp(typ,'patch') | strcmp(typ,'surface')
        cdatamapping = get(ch(i), 'CDataMapping');
    end
end

%%( strcmp(cdatamapping, 'scaled') ), hasimage,
%%if ( strcmp(cdatamapping, 'scaled') )
  % Treat images and surfaces alike if cdatamapping == 'scaled'
  t = caxis;
  d = (t(2) - t(1))/size(colormap,1);
  t = [t(1)+d/2  t(2)-d/2];
%%else
%%    if hasimage,
%%        t = [1, size(colormap,1)];
%%    else
%%        t = [1.5  size(colormap,1)+.5];
%%    end
%%end

h = gca;

if nargin==0,
    % Search for existing colorbar
    ch = get(findobj(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'}); ax = [];
    for i=1:length(ch),
        ud = get(ch{i},'userdata');
        d = ud.PlotHandle;
        if prod(size(d))==1 & isequal(d,h), 
            ax = ch{i}; 
            pos = get(ch{i},'Position');
            if pos(3)<pos(4), loc = 'vert'; else loc = 'horiz'; end
            changeNextPlot = 0;
            % Make sure image deletefcn doesn't trigger a colorbar('delete')
            % for colorbar update
            set(get(ax,'children'),'deletefcn','')
            break; 
        end
    end
end

origNextPlot = get(gcf,'NextPlot');
if strcmp(origNextPlot,'replacechildren') | strcmp(origNextPlot,'replace'),
    set(gcf,'NextPlot','add')
end

if loc(1)=='v', % Append vertical scale to right of current plot
    
    if isempty(ax),
% EKW: set size in inches, not normalized:
%		units = get(h,'units'); set(h,'units','normalized')
        units = get(h,'units'); set(h,'units','inches');
        pos = get(h,'Position');
        [az,el] = view;
        stripe = 0.075; edge = 0.02; 
        if all([az,el]==[0 90]), space = 0.05; else space = .1; end
% EKW: Don't change position of current axis:
%		set(h,'Position',[pos(1) pos(2) pos(3)*(1-stripe-edge-space) pos(4)])
%		rect = [pos(1)+(1-stripe-edge)*pos(3) pos(2) stripe*pos(3) pos(4)];
		between=0.1; width=min(.375,.2*pos(3));
		rect = [pos(1)+pos(3)+between pos(2) width pos(4)];
        ud.origPos = pos;
        
        % Create axes for stripe and
        % create DeleteProxy object (an invisible text object in
        % the target axes) so that the colorbar will be deleted
        % properly.
        ud.DeleteProxy = text('parent',h,'visible','off',...
                              'tag','ColorbarDeleteProxy',...
                              'handlevisibility','off',...
             'deletefcn','eval(''delete(get(gcbo,''''userdata''''))'','''')');
% EKW: Make units of colorbar axis inches:
%		ax = axes('Position', rect);
		ax = axes('Units','inches','Position', rect);
        set(ud.DeleteProxy,'userdata',ax)
        set(h,'units',units)
    else
        axes(ax);
        ud = get(ax,'userdata');
    end
    % Create color stripe
    n = size(colormap,1); data=[1:n]'; xax=[0 1];
    image(xax,t,(1:n)','Tag','TMW_COLORBAR','deletefcn','mycolorbar2(''delete'')');
	if iirev, set(ax,'Ydir','reverse'); else, set(ax,'Ydir','normal'); end
    set(ax,'YAxisLocation','right')
    set(ax,'xtick',[])

    % set up axes deletefcn
    set(ax,'tag','Colorbar','deletefcn','mycolorbar2(''delete'')')
    
elseif loc(1)=='h', % Append horizontal scale to top of current plot
    
    if isempty(ax),
        units = get(h,'units'); set(h,'units','normalized')
        pos = get(h,'Position');
        stripe = 0.075; space = 0.1;
        set(h,'Position',...
            [pos(1) pos(2)+(stripe+space)*pos(4) pos(3) (1-stripe-space)*pos(4)])
        rect = [pos(1) pos(2) pos(3) stripe*pos(4)];
        ud.origPos = pos;

        % Create axes for stripe and
        % create DeleteProxy object (an invisible text object in
        % the target axes) so that the colorbar will be deleted
        % properly.
        ud.DeleteProxy = text('parent',h,'visible','off',...
                              'tag','ColorbarDeleteProxy',...
                              'handlevisibility','off',...
             'deletefcn','eval(''delete(get(gcbo,''''userdata''''))'','''')');
        ax = axes('Position', rect);
        set(ud.DeleteProxy,'userdata',ax)
        set(h,'units',units)
    else
        axes(ax);
        ud = get(ax,'userdata');
    end
    
    % Create color stripe
    n = size(colormap,1);
    image(t,[0 1],(1:n),'Tag','TMW_COLORBAR','deletefcn','mycolorbar2(''delete'')'); set(ax,'Ydir','normal')
    set(ax,'ytick',[])

    % set up axes deletefcn
    set(ax,'tag','Colorbar','deletefcn','mycolorbar2(''delete'')')
    
else
  error('COLORBAR expects a handle, ''vert'', or ''horiz'' as input.')
end
% Keep same font, font size, and font weight:
fn=get(h,'FontName'); fs=get(h,'FontSize'); fw=get(h,'FontWeight');
set(ax,'FontName',fn); set(ax,'FontSize',fs); set(ax,'FontWeight',fw); 

if ~isfield(ud,'DeleteProxy'), ud.DeleteProxy = []; end
if ~isfield(ud,'origPos'), ud.origPos = []; end
ud.PlotHandle = h;
set(ax,'userdata',ud)
if ~isempty(bar_label),
    if strcmp(loc,'vert'), ylabel(bar_label); else, xlabel(bar_label); end
end
set(gcf,'CurrentAxes',h)
set(gcf,'NextPlot',origNextPlot)

if nargout>0, handle = ax; end

%
% COPYRIGHT (c) 2008
% 
% Applied Research Laboratories, The University of Texas at Austin
% (ARL:UT)
% All rights reserved.
% 
% This material may be reproduced by or for the U.S. Government
% only. This notice must appear in all copies of this file and its
% derivatives. Further distribution outside the U.S. Government is
% prohibited without the explicit written authorization from the
% Director of the Environmental Sciences Laboratory, ARL:UT.
% 
% THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
% EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE
% IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
% PURPOSE, OR NONINFRINGEMENT.
% 
% IN NO EVENT WILL ARL:UT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING
% OUT OF THE USE OR INABILITY TO USE THIS SOFTWARE, EVEN IF ARL:UT HAS
% BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
