%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Saves an RGB image in PGM format (Grayscale)
%
%Written by:
%   Alexander Stoytchev 
%   College of Computing 
%   Georgia Tech
%   saho@cc.gatech.edu
%   http://www.cc.gatech.edu/~saho
%
% Returns:
%   The number of bytes written.
%   On failure the function returns -1.
%
% Last modified: Nov 28, 1998
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function n=imwrite_pgm(IMAGE_RGB, fname)

fid=fopen(fname,'w');
if fid== -1
  n=-1;
else
  GRAY=rgb2gray(IMAGE_RGB);
  [R, C]=size(GRAY);
  fprintf(fid,'P5\n#\n%d %d\n255\n',C,R);  %Dump the header
  n=fwrite(fid, double(GRAY'),'char*1');
  fclose(fid)
end;
