function graph2imwrite(ff,filename,fmt,quality,fnt)
% Converts figure in image and saves it in the format given as extension
% (bmt,jpg,png... see imwrite)
%% INPUTS: ff=figure number
%          filename=...
%          fmt=one of the formats bmt jpg png (see imwrite)
%          quality ( digits of quality (0 to 100)
% Converts it in pdf (if have the 'convert' program)

% if ~exist('figures','dir')
mkdir('figures')
% end
savefig(['figures/',filename,'.fig'])
set((ff),'Color',[1,1,1])

% set((ff),'Units','centimeters','Position',[2,2,40,20])
set(ff,'units','normalized','outerposition',[0 0 1 1])
if nargin<5
    fnt=12
end
set(findall(ff,'-property','FontSize'),'FontSize',fnt)
F = getframe(ff);
[X, Map] = frame2im(F);
if nargin<4
    quality=100;
end
if strmatch(fmt,'jpg')
    imwrite(X,['figures/',filename,'.',fmt],'Quality',quality);
elseif strmatch(fmt,'j2c')
    imwrite(X,['figures/',filename,'.',fmt],'CompressionRatio',2.0);
else
     imwrite(X,['figures/',filename,'.',fmt]);
end
gg=system('which convert');
if gg==0
    eval(['!convert ',['figures/',filename,'.',fmt],' ','figures/',filename,'.pdf']);
end