% reads either a raw pgm or a raw ppm image, and returns it in either
% a w * h matrix or a w * h * 3 array

function i = pnmread(filename)

% open file
[fid, msg] = fopen(filename, 'r');
if fid == -1,
  error(msg)
end

% read magic number
magic = readstring(fid);
if length(magic) ~= 2,
  error('Unknown image format')
end
if any(magic ~= 'P5') & any(magic ~= 'P6'),
  error('Unknown image format')
else
  w = readnumber(fid);
  h = readnumber(fid);
  maxvalue = readnumber(fid);
  fgetl(fid);
  if all(magic == 'P5'),
    % read pgm image
    i = fread(fid, [w h], 'uint8')';
  else % must be P6
    % read ppm image
    pixels = uint8(fread(fid, [3 w*h], 'uint8'));
    i = uint8(zeros(h, w, 3));
    i(:, :, 1) = reshape(pixels(1,:), w, h)';	% red
    i(:, :, 2) = reshape(pixels(2,:), w, h)';	% green
    i(:, :, 3) = reshape(pixels(3,:), w, h)';	% blue
  end
end

% close file
fclose(fid);
