function maa(varargin)
% MAA Antialias figure
% 
% Usage
%    maa            Enable antialiasing (default scale 2)
%    maa(n)         Enable antialiasing and set scale to n
%    maa off        Disable antialiasing

% Copyright 2010 Mikkel N. Schmidt, ms@it.dk, www.mikkelschmidt.dk

tempFileName = 'temp.tiff';
userDataToken = 'MAA AntiAlias Axes';
scaleFactor = 2;
turnOff = false;

if nargin>=1
    if isnumeric(varargin{1})
        scaleFactor = varargin{1};
    elseif ischar(varargin{1})
        if strcmp(varargin{1}, 'off')
            turnOff = true;
        end
    end
end

h0 = gca;
ha = findobj(get(gcf, 'Children'), 'UserData', userDataToken);
if isempty(ha), 
    axes;
    axis off image;
else
    set(gcf, 'CurrentAxes', ha);
    delete(get(ha, 'Children'));
end

if turnOff
    delete(ha);
    set(gca, 'UserData', []);
    set(gcf, 'ResizeFcn', [])
else
    cPaperPositionMode = get(gcf, 'PaperPositionMode');
    cInvertHardcopy = get(gcf, 'InvertHardcopy');
    set(gcf, 'PaperPositionMode', 'auto');
    set(gcf, 'InvertHardcopy', 'off');
    print(gcf, ['-r',num2str(get(0,'ScreenPixelsPerInch')*scaleFactor)], '-dtiff', tempFileName);
    set(gcf, 'PaperPositionMode', cPaperPositionMode);
    set(gcf, 'InvertHardcopy', cInvertHardcopy);

    r = imresize(imread(tempFileName), 1/scaleFactor);
    delete(tempFileName);
    set(gca,'Units', 'pixels', 'Position', [1 1 size(r,2) size(r,1)]);
    image(r);
    axis off image;
    set(gca, 'UserData', userDataToken); 

    set(gcf, 'CurrentAxes', h0);
    set(gcf, 'ResizeFcn', @(src, eventData) maa(scaleFactor))
end