% readppm      Reads image files in the ppm format
%
%       function C = readppm(fname);
%
% fname is a string with the filename
% C is an image of same format as those generated by ppmpack
% Warning: May not accept all header formats. All comments must be within the 
% header. Can't have comments between the header and the data. 
% works for xv and writeppm.

% M Jagersand 1994

function C = readppm(fname);

  fid = fopen(fname,'r');
		
% Read in header
  TheLine = fgetl(fid);
  while TheLine(1) == '#'          % Skip initial comments
    TheLine = fgetl(fid);
  end
  format = TheLine;
  TheLine = fgetl(fid);
  while TheLine(1) == '#'          % Skip initial comments
    TheLine = fgetl(fid);
  end
  size = TheLine;
  TheLine = fgetl(fid);
  while TheLine(1) == '#'          % Skip initial comments
    TheLine = fgetl(fid);
  end
  maxint = TheLine;
  s = sscanf(size,'%d');
  if format=='P6' | format=='P3'
    last = s(1)*s(2)*3+2;
  else
    last = s(1)*s(2)+2;
  end
  C = zeros(last,1);
  C(1) = s(1);
  C(2) = s(2);
  if format=='P6'
    C(3:last) = fread(fid,s(1)*s(2)*3,'uint8');
  elseif format=='P5'
    C(3:last) = fread(fid,s(1)*s(2),'uint8');
  else
    if format=='P3'
      S = '%3.0f %3.0f %3.0f';
    elseif format=='P2'
      S = '%3.0f';
    else
      error('readppm: Unknown format');
    end
    C(3:last) = fscanf(fid,S);
  end
  fclose(fid);


   