function formatfig(varargin)
%FORMATFIG   Format figure window: set custom axes size and margins.
%
%   h = FORMATFIG(h,AxesSize,Margins) configures the figure window with the
%   handle h so that the axes and the margins have the specified size both on
%   the screen and when saved to a PostScript file with the function SAVEFIG.
%   FORMATFIG also brings the specified figure to the foreground.
%
%   h          Figure handle or figure name.
%              Default: current figure.
%   AxesSize   Vector containing width and height of the axes in centimeters.
%              Default: [10 7.5]
%   Margins    Vector containing the margins between the axes and the boundary
%              of the figure in centimeters.
%              If Margins == [a] then a is used for all 4 margins.
%              If Margins == [a b] then a is used for the left and right margins
%              and b for the bottom and top margins.
%              If Margins == [a b c d] then a, b, c and d are used for the left,
%              bottom, right and top margin respectively.
%              Default: [2 1.5 1 1]
%
%   See also NEWFIG, SAVEFIG.

% Copyright (c) 2004-2014 Mattias Schevenels
% October 2004

if ~isempty(varargin)
    if ischar(varargin{1})
        varargin{1} = findobj('Name', varargin{1});
        if isempty(varargin{1})
            error('Figure not found.');
        end
    end
    if length(varargin{1}) ~= 1
        varargin = [{gcf}, varargin];
    end
end
if nargin >= 1
    h = varargin{1};
else
    h = gcf;
end
if nargin >= 2
    AxesSize = varargin{2};
else
    AxesSize = [];
end;
if nargin >= 3
    Margins = varargin{3};
else
    Margins = [];
end

if isempty(AxesSize)
    AxesSize=[10 7.5];
end
if isempty(Margins)
    Margins=[2 1.5 1 1];
end

AxesSize = AxesSize(:).';
Margins = Margins(:).';

figure(h);

switch length(Margins)
    case 1
        Margins = repmat(Margins,1,4);
    case 2
        Margins = repmat(Margins,1,2);
    case 4
    otherwise
        error('Margins should be a vector with 1, 2 or 4 elements.');
end

ScreenSize = get(0,'ScreenSize')/get(0,'screenPixelsPerInch')*2.54;
FigPosition(3:4) = Margins(1:2) + AxesSize+Margins(3:4);
FigPosition(1:2) = (ScreenSize(3:4)-FigPosition(3:4))/2;
FigPaperSize = [21, 29.7];
FigPaperPosition = [(FigPaperSize(1)-FigPosition(3))/2, ...
    FigPaperSize(2)-FigPosition(4)- (FigPaperSize(1)-FigPosition(3))/2, ...
    FigPosition(3:4)];
AxesPosition = [Margins(1)/FigPosition(3),Margins(2)/FigPosition(4), ...
    AxesSize(1)/FigPosition(3),AxesSize(2)/FigPosition(4)];

set(gcf,'Units','centimeters');
set(gcf,'Position',FigPosition);
set(gcf,'PaperUnits','centimeters');
set(gcf,'PaperSize',FigPaperSize);
set(gcf,'PaperPosition',FigPaperPosition);
set(gca,'Units','normalized');
set(gca,'Position',AxesPosition);
end