function p=auto_plot(nl,nr,space,pcmd,height,width)
% function p=auto_plot(nl,nr,space,pcmd,height,width)
%
% This function is similar to subplot but you can control
% the spacing between the plots. Also, makes the whole figure
% fit a 8.5x11in paper size.
% It returns a matrix containing the position of all plots
% and opens a figure with a specified size.
% 
% nl - number of lines - controls the height 
% nr - number of rows  - controls the width
% space - space between the figures
% height - height of the total figure
% width  - width of the figure,
% pcmd - plot command (use any number or string)
% if height and width are not specified, the default is the whole
% page.
%
% The figure leaves 1in on each side of the paper, so the effective
% size of the paper will be 6.5x9in
%
% ---------------------------------------------------------------------
% initial setups
if nargin<=4
height=9;
width=6.5;
end
if nargin==5;
width=height;
height=pcmd;
end

% ---------------------------------------------------------------------
% define each plot size
%
heig=(height-1-space*(nl-1))/nl;
widt=(width-1-space*(nr-1))/nr;

% ---------------------------------------------------------------------
% define paper an screen size
%
pppos=[1 1 width height]; %paper position
scpos=[13-width 10-height width height]; % screen position
set(gcf,'PaperUnits','inches','PaperPosition',pppos)
set(gcf,'Units','inches','Position',scpos);

% ---------------------------------------------------------------------
% calculate the position of each plot
%
nfig=nl*nr; % total number of plots 
nf=[1:nfig]';

p1=.75+mod(nf-1,nr)*(widt+space);
p2=.75+flipud(sort(mod(nf-1,nl)))*(heig+space);
p3=widt*ones(size(nf));
p4=heig*ones(size(nf));

p=[p1 p2 p3 p4];

if nargin==4|nargin==6
for i=1:nfig
set(gca,'units','inches','position',p(i,:),'fontname','palatino','fontsize',8)
set(gca,'HandleVisibility','off')
end
end
