function center_cbar(h, frac, thin)
% center_cbar(h)
%
%  This adjusts the position of a colorbar so that it is centered
%  with respect to the current axes.  It also optionally sets the
%  length of the colorbar to a fraction of the current axes dimension,
%  and can slim down the colorbar.
%  The repositioning is typically needed when one uses one horizontal
%  colorbar, and one vertical.  Use center_cbar on the first colorbar
%  after creating the second one.
%  Center_cbar can also be used simply to slim down a colorbar that
%  is already centered.
% 
%     h is a colorbar axes handle.
%     frac gives the length of the colorbar as a fraction 
%           of the current axes.  Default is 0.7.
%     thin is the factor by which the colorbar is thinned, relative its
%           original thickness.  Default is 1 (no thinning).  A good
%           value for application to the result of the colorbar function
%           is 0.25.
%

%  Eric Firing

if nargin < 2, frac = 0.7; end
if nargin < 3, thin = 1; end

h_main = gca;

pos_main = get(h_main,'Position');
pos_cb = get(h, 'Position');

if pos_cb(4) > pos_cb(3),
   vert = 1;
else
   vert = 0;
end

if vert == 1,
   pos_cb(2) = pos_main(2) + (1-frac)*0.5*pos_main(4);
   pos_cb(4) = pos_main(4)*frac;
   pos_cb(3) = pos_cb(3) * thin;
else
   pos_cb(1) = pos_main(1) + (1-frac)*0.5*pos_main(3);
   pos_cb(3) = pos_main(3)*frac;
   pos_cb(4) = pos_cb(4) * thin;
end
set(h,'Position', pos_cb);
