function gax = colorbarf_pos(cont, pos, orientation)
% COLORBARF_POS: puts a discretised colorbar in a figure
%
% function gax = colorbarf_pos(cont, pos, orientation)
%
% cont is a vector of contour levels.
% pos is a [x y width height] vector for the colorbar; the units are
%     normalised in the current figure
% orientation is either 'vert' or 'horiz', indicating the orientation of the
%     colorbar.
% gax is the handle for the axis containing the colorbar.
%
%    NOTES:
% 1) Unlike colorbar or colorbarf colorbarf_pos does not resize any existing
%    axes and so relies on you leaving appropriate room for it. This has the
%    advantage that any scaling done with the other axes is not broken.
% 2) colorbarf_pos uses the current colormap.
% 3) It is not necessary for 'hold on' to be set.
% 4) Provided that cont has been used for other calls to contourf then
%    colorbarf_pos will give the right colours.
%
%    USAGE
%
% cont = -7:9;
% contourf(peaks, cont)
% set(gca, 'Position', [0.13 0.11 0.7 0.8])
% colorbarf_pos(cont, [0.9 0.11 0.03, 0.8], 'vert')
  
% $Id: colorbarf_pos.m,v 1.1 2000/09/08 08:46:46 mansbrid Exp $
% Copyright J. V. Mansbridge, CSIRO, Fri Sep  8 19:26:42 EDT 2000

if nargin == 2
  orientation = 'vert';
elseif nargin ~= 3
  error('expects 2 or 3 input arguments')
end
ih = ishold;
hold on

pos = pos(:)';
if length(pos) ~= 4
  error('pos should be a 4 element row vector')
end

switch orientation
 case 'horiz'
  cont = cont(:)';
  gax = axes;
  axis([cont(1) cont(end) 0 1])
  contourf(cont, [0 1], [cont; cont], cont);
  set(gax, 'Position', pos);
  set(gax, 'XTick', cont)
  set(gax, 'YTick', [])
 case 'vert'
  cont = cont(:);
  gax = axes;
  axis([0 1 cont(1) cont(end)])
  contourf([0 1], cont, [cont cont], cont);
  set(gax, 'Position', pos);
  set(gax, 'XTick', [])
  set(gax, 'YTick', cont)
  set(gax, 'YAxisLocation', 'right')
 otherwise
  error(['orientation must be ''vert'' or ''horiz'': not ' orientation])
end

if ~ih
  hold off
end