% displays a greyscale image; returns nothing
%
% Examples:
% tv(Z)
% tv(X,Y,Z) % axes are labelled accordingly
%           % plot is also scaled accordingly
%
% displays NaN as red
% clips anything past end of colortable to white (e.g. clipping won't go red)

function like_PVwave_tv(A,in_y,in_z) % returns nothing

if nargin==2
  disp('tvs: you entered 2 arguments; not sure how to handle that case yet')
  error('tvs: exiting')
end%if

if nargin==3
  X=A;
  Y=in_y;
  A=in_z;
end%if

map = colormap;
[M,N]=size(map);
if N~=3
  disp('tvs: colormap is not 3 wide;')
  disp('     i am exiting so you can do something about it')
  return
end%if

if M>256
  disp(sprintf('tvs: colormap length=%g: longer than 256; ',M));
  disp('     exiting...')
  return
end%if

% check to see if colormap last element is red
% cannot check is not red: ~=[1 0 0] must be cyan=[0 1 1]
last_isred = 0; % initialize to false
if map(M,:)==[1 0 0] % get the check down to a scalar
  last_isred = 1; % true
end%if
if ~last_isred
  disp('tvs: last colormap entry is not red (should be for NaN),')
  disp('     so i am going to take the liberty of setting the colormap to')
  disp('     grey with one extra red element at the end')
  greynan(M)
end%if

% DO NOT scale non-NaN parts on 1..M   but still control it

if ~last_isred
  % on 1..M: so clip >M to M      (M+1 is red)
  Aclip = (A>M)*M + (A<=M).*A;  % don't want big numbers looking like NaN
  B = chnan(Aclip,M+1);  % last entry in extended colormap (red)
else %if
  % on 1..M-1: so clip >M-1 to M-1    (M is red)
  Aclip = (A>(M-1))*(M-1) + (A<=(M-1)).*A;
  B = chnan(Aclip,M);  % last entry in original colormap (red)
end%if

if nargin==1
  image(B)      % just z
end%if
if nargin==3
  image(X,Y,B)  % x,y,z
end%if

%axis('equal')
axis('image')   % equal axes with cropping as well.

