function setplot(fig, figsize, margins, fontsize, fontname)
%
%Set figure size, text size, margins axis sizes etc 
%   Usage:
%   setplot(fig, figsize, margins, fontsize, fontname)
%   default: 
%   setplot(gcf, [10 10], [0.25 0.9 0.5 1.2 1.2 0.75], 10, 'Times');
%   parameters:
%       fig = figure handle 
%             current figure is default
%       figsize = [figwidth figheight] in cm
%                     *1       *2  (see figure below)
%                 [10 10] is default
%       margins = [top bottom rows left right cols] in cm
%                   *m1  *m2  *m3  *m4   *m5  *m6  (see figure below)
%                default see below
%       fontsize = size of the font
%                 10 is default             
%       fontname = type of fontfile:
%                 'Times' is default
%            _____________________________________________  _ _ _ _ _ __
%           |        __________         __________        | _ _ _*m1   ^
%           |   y   |          |       |          |       |            |
%           |   l   | subplot1 |       | subplot2 |       |            .
%           |   b   |          |       |          |       |            | 
%           |   l   |__________|       |__________|       | _ _ _      .                                                    
%           |                                             |      *m3   |
%           |        __________         __________        | _ _ _     *2
%           |   y   |          |       |          |       |            | 
%           |   l   | subplot3 |       | subplot4 |       |            .
%           |   b   |          |       |          |       |            | 
%           |   l   |__________|       |__________|       | _ _ _      . 
%           |          xlabel             xlabel          |      *m2   | 
%           |_____________________________________________| _ _ _ _ _ _v_ 
%         
%           |       |          |       |          |       |
%           |<-*m4->|          |<-*m6->|          |<-*m5->|
%           |<-------------- *1 ------------------------->|
%
%  version:  2011.1
%  author:   Rob Hoogendijk
%  contact:  r.hoogendijk@tue.nl



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.25;
    bottommargin = 0.9;
    rowsmargin   = 0.5;
    leftmargin   = 1.2;
    rightmargin  = leftmargin;
    colsmargin   = 0.75;
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

%% get handles
gtxt    =   findall(fig,'type','text');
gax     =   findall(fig,'type','axes');


%% Adjust figure
% set figure size
currentpos = get(fig,'Position');
set(fig,'Paperposition',[0 0 figsize]);
set(fig,'Position',[currentpos(1:2) figsize]);    
%set paper size for pdf
set(fig,'PaperSize',figsize);
%set fontsize
% set(gtxt,'Interpreter','latex');
set(gtxt,'FontSize',fontsize);
set(gtxt,'FontName',fontname)
set(gax,'FontSize',0.8*fontsize);


%set axis properties
set(gax,'Units','centimeters');
poscells=get(gax,'Position');
posxy=zeros(length(gax),4);
for ii=1:length(gax)        
    if(iscell(poscells))
        posxy(ii,:)=poscells{ii};
    else %only one plot: poscells is not a cell!
        posxy=poscells;
    end
end
posxy=round(posxy*10)/10; %set accuracy to 1 mm to prevent numeric problems

xval=unique(sort(posxy(:,1)));
yval=unique(sort(posxy(:,2)));
dimx=length(xval);
dimy=length(yval);

axwidth=(figsize(1)-rightmargin-leftmargin-(dimx-1)*colsmargin)/dimx;
axheight=(figsize(2)-topmargin-bottommargin-(dimy-1)*rowsmargin)/dimy;

axposx=leftmargin+([1:dimx]-1)*(axwidth+colsmargin);
axposy=bottommargin+([1:dimy]-1)*(axheight+rowsmargin);

%set axis positions
for jj=1:length(gax)    
    for ii=1:dimx
        if(posxy(jj,1)==xval(ii))
            posxy(jj,1)=axposx(ii);
        end
        if(ii==1)
            
        end
        
    end
    for ii=1:dimy
        if(posxy(jj,2)==yval(ii))
            posxy(jj,2)=axposy(ii);
        end
    end
    posxy(jj,3:4)=[axwidth axheight];
    set(gax(jj),'position',posxy(jj,:))
end

%align labels
for jj=1:length(gax)
    %xlabels
    %vertical alignment
    xlabelhandle=get(gax(jj),'xlabel');
    set(xlabelhandle,'units','centimeters');
    set(xlabelhandle,'VerticalAlignment','bottom');
    oldpos=get(xlabelhandle,'position');
    set(xlabelhandle,'position',[oldpos(1) -bottommargin+0.05 oldpos(3)]);
    %set horizontal alignment to middle of axis
    set(xlabelhandle,'units','normalized');
    oldpos=get(xlabelhandle,'position');
    set(xlabelhandle,'position',[0.5 oldpos(2) oldpos(3)]);
    %ylabels
    %horizontal alignment
    ylabelhandle=get(gax(jj),'ylabel');
    set(ylabelhandle,'units','centimeters');
    set(ylabelhandle,'VerticalAlignment','top');
    oldpos=get(ylabelhandle,'position');
    set(ylabelhandle,'position',[-leftmargin+0.15 oldpos(2:end)]);
    %set vertical alignment to middle of axis
    set(ylabelhandle,'units','normalized');
    oldpos=get(ylabelhandle,'position');
    set(ylabelhandle,'position',[oldpos(1) 0.5 oldpos(3)]);
end

%set resize function to this function
margins=[topmargin bottommargin rowsmargin leftmargin rightmargin colsmargin];
eval([ 'set(' num2str(fig) ',''ResizeFcn'',''setplot(' num2str(fig) ',[], [' num2str(margins) '])'');' ]);

end %function