%SETPLOT   Set figure size, text size, margins axis sizes etc   
%   
%   Usage:   setplot(fig, figsize, margins, fontsize, fontname)  
%            defaults:   
%            setplot(gcf, [], [0.5 1 0 1.5 1.5 0], 10, 'Times');
%
%   Inputs:  fig = figure handle   
%            figsize = [figwidth figheight] in cm  
%                          *1       *2  (see figure below)  
%            margins = [top bottom rows left right cols] in cm  
%                        *m1  *m2  *m3  *m4   *m5  *m6  (see figure below)  
%                      note that m3 and m6 are not absolute. They can be used to  
%                      add extra positive or negative spacing between cols/rows   
%            fontsize = size of the font                
%            fontname = type of fontfile:  
%            _____________________________________________  _ _ _ _ _ __  
%           |        __________         __________        | _ _ _*m1   ^  
%           |   y   |          |       |          |       |            |  
%           |   l   | subplot1 |       | subplot2 |       |            .  
%           |   b   |          |       |          |       |            |   
%           |   l   |__________|       |__________|       | _ _ _      .                                                      
%           |                                             |      *m3   |  
%           |        __________         __________        | _ _ _     *2  
%           |   y   |          |       |          |       |            |   
%           |   l   | subplot3 |       | subplot4 |       |            .  
%           |   b   |          |       |          |       |            |   
%           |   l   |__________|       |__________|       | _ _ _      .   
%           |          xlabel             xlabel          |      *m2   |   
%           |_____________________________________________| _ _ _ _ _ _v_   
%           
%           |       |          |       |          |       |  
%           |<-*m4->|          |<-*m6->|          |<-*m5->|  
%           |<-------------- *1 ------------------------->|  
%      
%   
%   Outputs: none
%   
%   See also SAVER.
%   
%   Rob Hoogendijk (2011-08-3) 

%   Changes: 
%   2011083 - Initial version 
%   
%   ________________________________
%   Eindhoven University of Technology
%   Dept. of Mechanical Engineering
%   Control Systems Technology group
%   PO Box 513, WH -1.126
%   5600 MB Eindhoven, NL
%   T +31 (0)40 247 4227
%   F +31 (0)40 246 1418
%   E r.hoogendijk@tue.nl

function subplots=setplot(fig, figsize, margins, fontsize, fontname)  
%% process inputs  
if (nargin<1 || isempty(fig) )  
    fig=gcf;  
end  
set(fig,'PaperUnits','centimeters');  
set(fig,'Units','centimeters');  
if (nargin<2 || isempty(figsize) )  
    figpos=get(fig,'position');  
    figsize=[figpos(3) figpos(4)];  
end  
if (nargin<3 || isempty(margins) )  
    topmargin    = 0.5;  
    bottommargin = 1;  
    rowsmargin   = 0;  
    leftmargin   = 1.5;  
    rightmargin  = leftmargin;  
    colsmargin   = 0;  
else  
    topmargin    = margins(1);  
    bottommargin = margins(2);  
    rowsmargin   = margins(3);  
    leftmargin   = margins(4);  
    rightmargin  = margins(5);  
    colsmargin   = margins(6);  
end  
if (nargin<4 || isempty(fontsize) )  
    fontsize=10;  
end  
if (nargin<5 || isempty(fontname) )  
    fontname='Times';  
end  
  
%% general settings  
%get handles to all axes and text  
gtxt    =   findall(fig,'type','text');  
gax     =   findall(fig,'type','axes','visible','on');  nax=length(gax);  
set(gax,'units','centimeters');  
  
% set figure size  
currentpos = get(fig,'Position');  
set(fig,'Position',[currentpos(1:2) figsize]);    
  
%set fontsizes  
set(gtxt,'FontSize',fontsize);  
set(gtxt,'FontName',fontname)  
set(gax,'FontSize',0.8*fontsize);  
fontspace=fontsize*(1/72)*2.54; %in cm  
  
%% get info from figure  
%get all axis positions  
for ii=1:nax  
    posxy(ii,:)=round(get(gax(ii),'position')*100)/100;  
end  
%put axes handles in subplots(nrows,ncols)  
xval=unique(sort(posxy(:,1)));  yval=flipud(unique(sort(posxy(:,2))));  
ncols=length(xval);             nrows=length(yval);  
%get axis subplot indices  
for jj=1:nax  
    for ii=1:nrows  
        if(posxy(jj,2)==yval(ii))  %check which y value it had   
           row=ii;      %store this index  
        end  
    end  
    for ii=1:ncols  
        if(posxy(jj,1)==xval(ii))  %check which x value it had  
           col=ii;       %store this index             
        end  
    end  
    subplots(row,col)=gax(jj);  
end  
  
% store relevant handles in arrays, set units to cm  
isylabelinbetween=0;isxlabelinbetween=0; %init  
mtiscols=0;mtisrows=0;  
mxtype=0;mytype=0;  
% get necessary info from figure  
for ii=1:nrows  
    for jj=1:ncols   
        ax=subplots(ii,jj);  
        %xlabel  
        xlab(ii,jj)=get(ax,'xlabel');   
        hasxlab(ii,jj)=~isempty(get(xlab(ii,jj),'string'));  
        set(xlab(ii,jj),'units','centimeters');  
        %ylabel  
        ylab(ii,jj)=get(ax,'ylabel');   
        hasylab(ii,jj)=~isempty(get(ylab(ii,jj),'string'));  
        set(ylab(ii,jj),'units','centimeters');  
        %title  
        titl(ii,jj)=get(ax,'title');   
        hastitl(ii,jj)=~isempty(get(titl(ii,jj),'string'));  
        set(titl(ii,jj),'units','centimeters');  
        % ticks  
        hasxticklbls(ii,jj)=~isempty(get(ax,'xticklabel'));  
        hasyticklbls(ii,jj)=~isempty(get(ax,'yticklabel'));  
        % tightinset (excluding labels)  
        set(gtxt,'visible','off');  
        tis=get(ax,'tightinset');  
        tisleft(ii,jj)  =tis(1);  
        tisbottom(ii,jj)=tis(2);  
        tisright(ii,jj) =tis(3);  
        tistop(ii,jj)   =tis(4);  
        set(gtxt,'visible','on');  
        %type: 0=nothing,1=ticklabels,2=labels,3=ticksandlabels         
        if(hasxticklbls(ii,jj) && hasxlab(ii,jj)),xtype(ii,jj)=3;  
        elseif(hasxlab(ii,jj)),                   xtype(ii,jj)=2;  
        elseif(hasxticklbls(ii,jj)),              xtype(ii,jj)=1;  
        else,                                     xtype(ii,jj)=0;  
        end  
        if(hasyticklbls(ii,jj) && hasylab(ii,jj)),ytype(ii,jj)=3;  
        elseif(hasylab(ii,jj)),                   ytype(ii,jj)=2;  
        elseif(hasyticklbls(ii,jj)),              ytype(ii,jj)=1;  
        else,                                     ytype(ii,jj)=0;  
        end  
        if(ii<nrows) %between the rows...  
            if(xtype(ii,jj)>1),isxlabelinbetween=1;end; % is there an x label between the plots?  
            mtisrows=max(mtisrows,tisbottom(ii,jj));    % get max dist between rows  
            mxtype=max(mxtype,xtype(ii,jj));            % get max type  
        end  
        if(jj>1) %between the cols...  
            if(ytype(ii,jj)>1),isylabelinbetween=1;end; % is there an y label between the plots?  
            mtiscols=max(mtiscols,tisleft(ii,jj));       % get max dist between cols  
            mytype=max(mytype,ytype(ii,jj));            % get max type   
        end  
    end  
end  
  
% compute minimum dist between rows and cols  
if(ncols>1),mtiscols=max(max(tisleft(:,2:end)))    +max(max(tisright(:,1:end-1)));end  
if(nrows>1),mtisrows=max(max(tisbottom(1:end-1,:)))+max(max(tistop(2:end,:)));    end  
  
%determine axwidth  
colspace=(colsmargin+mtiscols+isylabelinbetween*fontspace);  
rowspace=max((rowsmargin+mtisrows+isxlabelinbetween*fontspace)-0.1, 0.1);  
  
%if no labels and no ticks, use same spacing  
if(mxtype==0 && mytype==0)  
    maxspace=max(colspace,rowspace);  
    colspace=maxspace;rowspace=maxspace;  
end  
axwidth = (figsize(1)-rightmargin-leftmargin  -(ncols-1)*colspace)/ncols;  
axheight= (figsize(2)-topmargin  -bottommargin-(nrows-1)*rowspace)/nrows;  
  
%determine desired axes positions  
axcolpos=leftmargin+([1:ncols]-1)*(axwidth+colspace);  
axrowpos=fliplr(bottommargin+([1:nrows]-1)*(axheight+rowspace));  
  
%% set axes positions, labels  
for ii=1:nrows  
    for jj=1:ncols  
        ax=subplots(ii,jj);          
        set(ax,'position',[axcolpos(jj),axrowpos(ii),axwidth,axheight]);       
        set(xlab(ii,jj),'position',[0.5*axwidth                                  -max(tisbottom(ii,:)) 0]);  
        set(ylab(ii,jj),'position',[-max(tisleft(:,jj))-hasyticklbls(ii,jj)*0.1   0.5*axheight         0]);  
        set(titl(ii,jj),'position',[0.5*axwidth                                   axheight             0]);  
    end  
end  
  
%% set invisible axis position for labels for all the axes  
ivax = findall(fig,'type','axes','visible','off');   
set(ivax,'units','centimeters','position',[axcolpos(1) axrowpos(end) axcolpos(end)+axwidth-axcolpos(1) axrowpos(1)+axheight-axrowpos(end)]);  
  
  
%% set resize function to this function with the proper arguments  
margins=[topmargin bottommargin rowsmargin leftmargin rightmargin colsmargin];  
eval([ 'set(' num2str(fig) ',''ResizeFcn'',''setplot(' num2str(fig) ',[], [' num2str(margins) ']);'');' ]);  
  
end %function   
