% WRITEPPM  - Dump the current figure window to a file using PPM format.
%
%    WRITEPPM(FILENAME) dumps the current figure window in PPM
%    format to file FILENAME.  
%
%    [PPMSIZE] = WRITEPPM(FILENAME) will return a 2 element vector
%    PPMSIZE, where PPMSIZE(1) is the Y pixel size and PPMSIZE(2)
%    is the X pixel size of the figure window written to FILENAME.
%    
%    NOTE:  Due to a quirk in matlab, 1 Y pixel is "lost", so the
%    pixel size of the image saved to file is X by Y-1.
%
%    EXAMPLE:   
%    >>figure('Position',[200,200,500,300]); % Create a figure window
%                                            % 500 X by 300 Y pixels.
%    >>plot(randn(10,10),randn(10,10));      % Plot some random numbers.
%    >>pix = writeppm('testimg.ppm')         % Write figure window to
%                                            % file testimg.ppm.

%    Version 1.0 (15-Aug-94) 
%    by Stefan Hudson (hudson@usw.nps.navy.mil)
%    Mike Cook - NPS Oceanography Dept., OCT 94. - Added error
%    checking and documentation.

function [ppmsize] = writeppm(fname);

if (isstr(fname) ~= 1)
    error(' File name must be a string')
end

[ppmrast, ppmcmap] = capture;
ppmsize=size(ppmrast);
ppmsize=[ppmsize(1)-2, ppmsize(2)-1];
ppmfp=fopen(fname, 'w');

if(ppmfp==-1)
        disp('Unable to open ',fname,' for writing.');
        return;
end;

ppmcmap = round(ppmcmap*255);

fprintf(ppmfp, 'P6\n#RAW PPM file generated by Matlab with writeppm.m by Stefan Hudson\n');
fprintf(ppmfp, '%6d %6d %6d\n', ppmsize(2), ppmsize(1), 255);
fwrite(ppmfp, ppmcmap(ppmrast(1:ppmsize(1),2:ppmsize(2)+1)',:)', 'char');
fclose(ppmfp);
return;
