function jimagesc(varargin)
% jimagesc([x,y],image,[colormap],[cmin],[cmax])
% This is like imagesc, but fills in NaNs with the background color of the
% figure. You can supply the colormap as an argument; if none is given, it
% uses jet. You can also supply the max and min values used for the
% colorscaling.
% 
if nargin==1
	im = varargin{1};
	map = colormap(jet);
	[ny,nx]=size(im);
	x=[1:nx];
	y=[1:ny];
elseif nargin==2
	im = varargin{1};
	map = varargin{2};
	[ny,nx]=size(im);
	x=[1:nx];
	y=[1:ny];
elseif nargin==2
	im = varargin{1};
	map     = varargin{2};
	[ny,nx]=size(im);
	x=[1:nx];
	y=[1:ny];
elseif nargin==3
	x=varargin{1};
	y=varargin{2};
	im=varargin{3};
	map = colormap(jet);
elseif nargin==4
	x=varargin{1};
	y=varargin{2};
	im=varargin{3};
	map=varargin{4};
elseif nargin==6
	x=varargin{1};
	y=varargin{2};
	im=varargin{3};
	map=varargin{4};
    cmin = varargin{5};
    cmax = varargin{6};
else
	disp('too many args in jimagesc')
	return
end
[ny,nx]=size(im);
if exist('cmin')
    mn = cmin;
    mx = cmax;
else
    mn=min(min(im));
    mx=max(max(im));
end
[nc,tmp]=size(map);
% Scale the data from 0 to 1
if mx~=mn
	scledim = (im-mn)./(mx-mn);
else % image is the same everywhere
	scledim = 0.5*ones(ny,nx);
end
% FInd which color to use
indx = round(scledim*(nc-1))+1;
% Saturate at top and bottom of colorscale:
indx(indx<1)=1;
indx(indx>64)=64;
colim = zeros(ny,nx,3);
nancol =  get(gcf,'color');
for jy=1:ny
	for jx=1:nx
		if isnan(indx(jy,jx))
			colim(jy,jx,:) = nancol;
        else
            colim(jy,jx,:) = map(indx(jy,jx),:);
		end
	end
end
image(x,y,colim)