% save a figure 'wysiwyg' in pdf (and optionally in eps)
% usage: saver(name,fignumber,path,save_eps(1=yes/0=no))
%     default figure:   current figure
%     default path:     current dir
%     default save_eps: 0
%
%  version:  2011.0
%  author:   Rob Hoogendijk
%  contact:  r.hoogendijk@tue.nl

function saver(name,handle,path,eps)
%use current figure if no handle is supplied
if (nargin<2)
    handle=gcf;
end
%default path current dir
if (nargin<3)
    if(computer=='GLNX86')        
        path=[cd '/']; %for linux users
    else
        path=[cd '\']; %for windows users
    end
end
%store eps as well
if(nargin<4)
    eps=0;
end

%wysiwyg part...
%store old units
oldpaperunits=get(handle,'PaperUnits');
oldunits=get(handle,'Units');
%set papersize
set(handle,'PaperUnits','centimeters');
set(handle,'Units','centimeters');
currentpos = get(handle,'Position');
set(handle,'Paperposition',[0 0 currentpos(3) currentpos(4)]);
set(handle,'PaperSize',[currentpos(3) currentpos(4)]);
%restore old units
set(handle,'PaperUnits',oldpaperunits);
set(handle,'Units',oldunits);

% save eps
if(eps)
    print(handle,'-depsc2',[path,name,'.eps']);
    disp(['Figure ' num2str(handle) ' stored in ' path,name '.eps']);
end

% save pdf
if exist([path,name,'.pdf'])
    R=input(['Overwrite file ' path, name '.pdf? [y/n] : '],'s');
    if(R=='y')
        try
            chan=ddeinit('acroview','control');
            if chan
                ddeexec(chan,[ '[DocOpen("' path , name '.pdf")]' ]);
                ddeexec(chan,[ '[DocClose("' path , name '.pdf")]' ]);
            end;
            delete([path, name '.pdf'])
        catch
            delete([path, name '.pdf']);
        end
    else
        error('Figure not saved.');
    end
end
warning off;
print(handle,'-dpdf',[path,name,'.pdf']);
warning on;
disp(['Figure ' num2str(handle) ' stored in ' path,name '.pdf']);
