% I = PPMREAD(FILENAME)
% 
% This function will read a .ppm file into a image array
%
%

function I = ppmread(filename)

% Open the file
fid = fopen(filename);

% Make sure the file opened
if(fid==-1)
    error('Could not open file');
end

% Read the data header
header = fgetl(fid);
A = fscanf(fid,'%d %d %d');
w = A(1);
h = A(2);
d = A(3);

% Read in data from file as character vector
[A,count] = fread(fid,'int8');

% Close the file
if(fclose(fid)==-1)
    error('Error closing file')
end

% Convert the character vector into integer array
I = zeros(3,w,h);
n = 0;
index = 1;
for(i=1:count)
    switch(A(i))
    case ' '
        n = 0;
    case ','
        I(index) = n;
        index = index+1;
    case '}'
    case ';'
    otherwise
        n = n*10 + (A(i)-'0');
    end
end

% Reshape the array
I = shiftdim(I,1);

for(i=1:h)
    for(j=1:w)
        J(i,j,:) = I(j,i,:);
    end
end

% Scale the values between 0 and 1
I = J/d;
