function [w,h]=printsize(t1,s1,t2,s2)
% PRINTSIZE set the figure size for printouts to the correct aspect.
%    [w,h]=PRINTSIZE(...)  sets the figure printout size as specified (see
%    below) while keeping the figure aspect ratio, and also returns width
%    and height.
%    PRINTSIZE  sets the printout size to maximum size
%    PRINTSIZE('Width',width)  sets the printout size, using given width.
%    PRINTSIZE('Height',height)  sets the printout size, using given height.
%    PRINTSIZE('Width',width,'Height',height)  sets the printout size,
%    using given width and height.
%
if ((nargin~=0) & (nargin~=2) & (nargin~=4))
  error('Wrong number of input arguments.')
end
ww=0; hh=0;
if (nargin>0)
  if (strcmp(deblank(lower(t1)),'width'))
    ww=s1;
  elseif (strcmp(deblank(lower(t1)),'height'))
    hh=s1;
  else
    error(['Unknown parameter: ' t1]);
  end
end
if (nargin==4)
  if (strcmp(deblank(lower(t2)),'width'))
    ww=s2;
  elseif (strcmp(deblank(lower(t2)),'height'))
    hh=s2;
  else
    error(['Unknown parameter: ' t2]);
  end
  if (strcmp(deblank(lower(t1)),deblank(lower(t2))))
    error(['Conflicting definitions: ' t1 ' & ' t2]);
  end
end
if ((ww<0) | (hh<0))
  error('Illegal size values given');
end
%
set(gcf,'PaperOrientation','portrait');
un = get(gcf,'PaperUnits');
set(gcf,'PaperUnits','inches');
%
ps = get(gcf,'PaperSize');
max_width=ps(1); max_height=ps(2);
p_aspect=ps(2)/ps(1);
center_x=max_width/2; center_y=max_height/2;
%
fs = get(gcf,'Position');
f_aspect=fs(4)/fs(3);
%
% Do the no argument case
if ((ww==0) & (hh==0))
  if (f_aspect>p_aspect)
    hh=max_height; ww=hh/f_aspect;
  else
    ww=max_width; hh=ww*f_aspect;
  end
elseif (hh==0)
  % Do the case for width given
  if (ww>max_width)
    disp(['Width larger than paper size. Changing ' num2str(ww) '-->' num2str(max_width)]);
    ww=max_width;
  end
  hh=ww*f_aspect;
  if (hh>max_height)
    disp(['Height larger than paper size. Changing ' num2str(hh) '-->' num2str(max_height)]);
    hh=max_height;
  end
elseif (ww==0)
  % Do the case for height given
  if (hh>max_height)
    disp(['Height larger than paper size. Changing ' num2str(hh) '-->' num2str(max_height)]);
    hh=max_height;
  end
  ww=hh/f_aspect;
  if (ww>max_width)
    disp(['Width larger than paper size. Changing ' num2str(ww) '-->' num2str(max_width)]);
    ww=max_width;
  end
else
  if (hh>max_height)
    disp(['Height larger than paper size. Changing ' num2str(hh) '-->' num2str(max_height)]);
    hh=max_height;
  end
  if (ww>max_width)
    disp(['Width larger than paper size. Changing ' num2str(ww) '-->' num2str(max_width)]);
    ww=max_width;
  end
end  
%
rect = [center_x-ww/2 center_y-hh/2 ww hh];
set(gcf,'PaperPosition',rect);
set(gcf,'PaperUnits',un);
%
if (nargout==1)
  if (ww~=0)
    w=ww;
  else
    w=hh;
  end
end
if (nargout==2)
  w=ww; h=hh;
end
