%
% function imdisp(img[,map[,dont_scale_map[,dont_scale_image[,title[,colormask[,masked]]]]]]);
%          Displays an image. 
%          if IMG is string the image is loaded from disk
%          use MAP for correct display of indexed images
%          use DONT_SCALE_MAP to use function IMAGE and not IMAGESC
%          use DONT_SCALE_IMAGE to display the image in the original size
%          use TITLE to impose optional image window title
%          use COLORMASK to mask in|out colors:
%              use negative values to mask out and positive to select
%              can be matrix of color values
%          use MASKED to display as binary mask using COLORMASK range
%
function imdisp(varargin);

	if nargin<1,
		error('IMDISP: at least image parameter expected!');
	end;

	img=varargin{1};

	if length(img(:))>1,

		if isa(img,'char'),
			%%%%% parameter refers to a filename
			img=imload(img);
		end;

		fig=figure( ...
 			'Name','Processing image...', ...
			'NumberTitle','off', 'HandleVisibility', 'on', ...
			'tag', 'Fig1', ...
			'Visible','on', 'Resize', 'on',...
			'BusyAction','Queue','Interruptible','on',...
			'units','pixels',...
			'Menubar','none');
		ax=axes('Parent',fig, ...
			'Box','on', ...
			'Color',[0 0 0], ...
			'Position',[0 0 1 1], ...
			'Tag','Axes1', ...
			'YDir','reverse' );

		map = [];
		if nargin>=2, if prod(size(varargin{2}))>1, map=varargin{2}; end; end;

		if isempty(map),
			if nargin<2,dont_scale_map=0;else,dont_scale_map=varargin{2};end;
			if nargin<3,dont_scale_image=0;else,dont_scale_image=varargin{3};end;
			if nargin<4,title=sprintf('[%dx%d]',size(img,2),size(img,1));
				else,if ~isempty(varargin{4}),title=varargin{4};
					else title=sprintf('[%dx%d]',size(img,2),size(img,1));end;end;
		else
			if nargin<3,dont_scale_map=0;else,dont_scale_map=varargin{3};end;
			if nargin<4,dont_scale_image=0;else,dont_scale_image=varargin{4};end;
			if nargin<5,title=sprintf('[%dx%d]',size(img,2),size(img,1));
				else,if ~isempty(varargin{5}),title=varargin{5};
					else title=sprintf('[%dx%d]',size(img,2),size(img,1));end;end;
		end;
		
		lims = limits( img);
		mn   = lims(1);
		mx   = lims(2);
		if isempty(map),
		if nargin>=5,		%% 5th parameter is color mask
			if nargin>=6,
				masked=varargin{6};
			end;
			imm=uint8(img);
			if length(find(imm==0))==0,
				mask=0;
			else
				mask=255;
			end;
			colormask=varargin{5};
			if colormask(1)<0,	% colormask defines colors to exclude
				fprintf('Excluding colors...\n');
				if masked,
%					im = ones(size(imm))*255;
					im = zeros(size(imm));
				else
					im = imm;
				end;
				for i=1:length(colormask),
					if ~isempty(find(imm==abs(colormask(i)))),
						im(find(imm==abs(colormask(i))))=mask;
					end;
				end;
			else
				fprintf('Masking colors...\n');
%				im = ones(size(imm))*mask;
				im = zeros(size(imm));
				for i=1:length(colormask),
					if ~isempty(find(imm==colormask(i))),
						if masked,
							im(find(imm==colormask(i)))=255;
						else
							im(find(imm==colormask(i)))=colormask(i);
						end;
					end;
				end;
			end;
			imm=im;
			clear im;
			img=imm;
			imm=img(find(img~=mask));
			mn=min(imm(:));
			mx=max(imm(:));
			clear imm;
		end;
		end;	

		if accuracy( mn)>0 || accuracy( mn)>0,
			title = [title, sprintf('-[%.3f..%.3f]',double(mn),double(mx)), ' (x,y)=color'];
		else
			title = [title, sprintf('-[%.0f..%.0f]',double(mn),double(mx)), ' (x,y)=color'];
		end;

		if ~isa(img,'double'),img=double(img);end;
		
		% if we've got a 3-D image get the 1st slice in z-axis
		if (ndims(img)==3) & (size(img,3)~=3),
			img = squeeze( img(:,:,1) );
		end;
		
		m=lims(2);if m==0,m=1;end;
		truecolor=(length(size(img))==3);
		%% ************************************************************************
		%% check the image limits in order to force scaling the colormap
		if lims(1)<0 | lims(2)>255,
			dont_scale_map = 0;
		end;
		if lims(1)==0 & lims(2)==1,
			dont_scale_map = 0;
		end;
		%% ************************************************************************
		if isempty(map),
		if ~dont_scale_map,
			mn=lims(1);
			if m-mn~=0,
				if truecolor,
					img=(img-mn)/(m-mn);
				else,
					img=(img-mn)*255/(m-mn);
				end;
			end;
		else
			if truecolor,img=img/255;end;
		end;
		if ~truecolor,
			colormap(gray(256));
		end;
		end;

		if ~isempty(map),
			img = ind2rgb( img, map );
		end;
		image(img,'CDataMapping','direct');

		if dont_scale_image,
%%%			truesize;
			%% **********************************************************************
			%% check the image size and the screen resolution: resize accordingly
			[ height, width, channels] = size( img);
			screen = get(0,'ScreenSize');
			scwidth = screen(3);
			scheight = screen(4);
			stepX = .25 * width;
			stepY = .25 * height;
			zoomfactor = 100;
			if height>scheight | width>scwidth,
				while (height>scheight | width>scwidth) & (height>0) & (width>0),
					height = height - stepY;
					width = width - stepX;
					zoomfactor = zoomfactor-25;
				end;
			end;
			if width==0 | height==0
				[ height, width, channels] = size( img);
				screen = get(0,'ScreenSize');
				scwidth = screen(3);
				scheight = screen(4);
				stepX = .10 * width;
				stepY = .10 * height;
				zoomfactor = 100;
				if height>scheight | width>scwidth,
					while (height>scheight | width>scwidth) & (height>0) & (width>0),
						height = height - stepY;
						width = width - stepX;
						zoomfactor = zoomfactor-10;
					end;
				end;
			end;				
			X = floor((scwidth-width)/2);
			Y = floor((scheight-height)/2);
			PositionArray = [ X, Y, width, height];
			set( fig, 'Position', PositionArray );
			title = [sprintf('[%d%%]-',zoomfactor), title];
			clear scwidth scheight screen stepX stepY;
		%% **********************************************************************
		end;
		axis image;
		zoom on;

		set( fig, 'Name',title);
		set(fig,'pointer','crosshair');
		set(fig,'WindowButtonMotionfcn','imdisp(1)');
		imdisp(1);

	else

		fig=get(0,'Currentfigure');
		ca=get(fig,'CurrentAxes');
		pos=get(ca,'CurrentPoint');
		pos=round(pos(1,1:2));
		position = get(fig,'Position');
		win_width=position(3);
		win_height=position(4);
		imsize=get(ca,'Plotboxaspectratio');
		zoom_width = imsize(1);
		zoom_height= imsize(2);
		xlim=max(1,ceil(get(ca,'Xlim')));
		ylim=max(1,ceil(get(ca,'Ylim')));

		imagedata=findobj(fig,'type','image');
		imagedata=get(imagedata,'CData');
		truecolor=(length(size(imagedata))==3);
		if ~truecolor,[r,c]=size(imagedata);else,[r,c,m]=size(imagedata);end;
		xlim=min(xlim,c);
		ylim=min(ylim,r);
		if truecolor,
			imagedata=imagedata(ylim(1):ylim(2),xlim(1):xlim(2),:);
		else
			imagedata=imagedata(ylim(1):ylim(2),xlim(1):xlim(2));
		end;
		zoomX = num2str( c/zoom_width,2);
		zoomY = num2str( r/zoom_height,2);
		percentX = int2str(round( win_width*100/c));
		percentY = int2str(round( win_height*100/r));
		title = get( fig, 'Name' );
		if ~strcmp(percentX,percentY),
			if ~strcmp(zoomX,zoomY),
				title = ['[win:',percentX,'%,',percentY,'%,zoom:',zoomX,'x,',zoomY,'x',title(findstr(title,']'):end)];
			else
				title = ['[win:',percentX,'%,',percentY,'%,zoom:',zoomX,'x',title(findstr(title,']'):end)];
			end;
		else
			if ~strcmp(zoomX,zoomY),
				title = ['[win:',percentX,'%,zoom:',zoomX,'x,',zoomY,'x',title(findstr(title,']'):end)];
			else
				title = ['[win:',percentX,'%,zoom:',zoomX,'x',title(findstr(title,']'):end)];
			end;
		end;
		pos(1)=pos(1)-xlim(1)+1;
		pos(2)=pos(2)-ylim(1)+1;
		if ~truecolor,[r,c]=size(imagedata);else,[r,c,m]=size(imagedata);end;
		if pos(1)<1, pos(1)=1; end; if pos(1)>c, pos(1)=c; end;
		if pos(2)<1, pos(2)=1; end; if pos(2)>r, pos(2)=r; end;
		fmt='%.0f';
		if truecolor,
			clr=imagedata(pos(2),pos(1),:);
			stat=sprintf(['(%d,%d)=(',fmt,',',fmt,',',fmt,')'],pos(2)+ylim(1)-1,pos(1)+xlim(1)-1,clr(1)*255,clr(2)*255,clr(3)*255);
		else
			clr=imagedata(pos(2),pos(1));
			stat=sprintf(['(%d,%d)=',fmt],pos(2)+ylim(1)-1,pos(1)+xlim(1)-1,clr);
		end;
%		val=imagedata(pos(2),pos(1));
		title = title(1:findstr(title,'(')-2);
		set(fig,'Name',[title,' ',stat]);

	end;

return;


