function truesize(fig,siz)
%TRUESIZE Resize figure so that image is true size.
%	TRUESIZE(FIG) changes the figure size of FIG so that the current 
%	image has one true pixel for each pixel in the image.
%
%	TRUESIZE(FIG,[M N]) changes the figure size of FIG so that the
%	current axis is M-by-N pixels.
%	
%	TRUESIZE or TRUESIZE([M N]) without a figure argument works on
%	the current figure.
%
%	This routine works best with figures that contain a single
%	image.
%
%	See also AXIS IMAGE.

%	Clay M. Thompson 10-15-92
%	Copyright (c) 1992-93 by The MathWorks, Inc.
%	$Revision: 1.9 $  $Date: 1993/08/24 16:02:41 $

if nargin<1, fig = gcf; siz = []; end
if nargin==1,
  if prod(size(fig))==1,
    siz = [];
  else
    siz = fig; fig = gcf;
  end
end

ax = get(fig,'currentAxes');
ch = get(ax,'children');
hasimage = 0;
for i=1:length(ch),
  if strcmp(get(ch(i),'type'),'image'),
     hasimage = hasimage + 1;
     im = ch(i);
  elseif strcmp(get(ch(i),'type'),'surface'),
     if strcmp(get(ch(i),'FaceColor'),'texturemap'),
       hasimage = hasimage + 1;
       im = ch(i);
     end
  end
end
if hasimage>1, 
  error('Current axes must contain a single image.');
end

aunits = get(ax,'units'); funits = get(fig,'units'); runits = get(0,'units');
set(ax,'units','normalized'), set(fig,'units','pixels'), set(0,'units','pixels')
apos = get(ax,'position'); fpos = get(fig,'position'); 
rpos = get(0,'screensize');

if isempty(siz), siz = size(get(im,'Cdata')); end

% Change figure position to closest size
dx = ceil(siz(2)/apos(3) - fpos(3));
dy = ceil(siz(1)/apos(4) - fpos(4));
fpos = [fpos(1)-round(dx/2) fpos(2)-round(dy/2) fpos(3)+dx fpos(4)+dy];

if fpos(3)>rpos(3) | fpos(4)>rpos(4),
  disp('Figure would be too big to fit on the screen. No change made.');
  return
end

set(fig,'Position',fpos);

% Change axis position to get exactly one pixel per image pixel.
dx = siz(2)/fpos(3) - apos(3);
dy = siz(1)/fpos(4) - apos(4);
set(ax,'Position',[apos(1)-dx/2 apos(2)-dy/2 apos(3)+dx apos(4)+dy])

set(ax,'units',aunits), set(fig,'units',funits) % Restore units
