%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Reads a PPM image into a Matrix (RBG format)
%
%Written by:
%   Alexander Stoytchev 
%   College of Computing 
%   Georgia Tech
%   saho@cc.gatech.edu
%   http://www.cc.gatech.edu/~saho
%
% Returns:
%   On success a (R,C,3) matrix is returned. 
%   On failure the function returns -1;
%
% Note: No color scaling is performed, i.e. the number of colors read 
%       from the PPM file is ignored.
%
% Last modified: Nov 28, 1998
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function IMAGE_RGB=imread_ppm(fname)

fid=fopen(fname,'r');
if fid== -1
  IMAGE_RGB=-1;
else
  magic=fgetl(fid);
  if ~strcmp(magic,'P6')
     IMAGE_RGB=-1;
     return
  end;
  Comment=fgetl(fid);

  if (Comment(1) ~= '#')  %File with no comment
     CR=sscanf(Comment,'%d %d');
  else
     C_R=fgetl(fid);
     CR=sscanf(C_R,'%d %d');
  end;
  C=CR(1);
  R=CR(2);
  Colors=fgetl(fid);
  Col=sscanf(Colors,'%d');
  count=0;

  IMAGE_RGB=zeros(R,C,3);
  for i=1:R
    [tmp, cnt]=fread(fid,[3,C], 'char*1');
    IMAGE_RGB(i,:,:)=tmp'; 
    count= count + cnt;
  end;

  IMAGE_RGB=uint8(IMAGE_RGB);
% imshow(IMAGE_RGB);
  fclose(fid);

end;
