% readInputFile.m   Script m-file, reads 'input.txt' into a cell array
% P. Conrad for CISC106, sect 99, 09/24/2007.

% Reads input from 'input.txt'.  Each line is read into successive
% entries in a Cell Array called lines, i.e. lines{1} is the first
% line, lines{2} is the second line, etc.    numLines is the
% variable that keeps track of how many lines are in the file.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% open the file;
% if successful, continue, 
% otherwise, stop with an error message
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



fileIsOpen = false;


% fid is the "file id"--it is the variable we use to 
% access the file after it is opened.   message is a message
% that is returned if the open is not successful.  In that case,
% fid will be -1.


[fid, message]  = fopen('input.txt');

if (fid == -1)
  % print an error message
  disp (['File input.txt could not be opened: ' message]);  
else
  fileIsOpen = true;
end;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if the file was opened successfully,
% read all the lines into a cell array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


if (fileIsOpen)
  
  % start number of lines read at zero
  
  numLinesRead = 0;

  % the fgetl(fid) function returns a char array which is the next
  % line from the file, and it moves fid to point to the next line
  % in the file.    fgets(fid) does the same thing, but includes
  % the \n character.   fgetl throws it away for us.

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % read all lines from file pointed to by fid
  % into the cell array called lines
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
  % try reading the first line
  
  thisLine = fgetl(fid);
  while (thisLine ~= -1)    % in MATLAB, ~= means "not equal to"

    % if we got here, then thisLine != -1, so we successfully read
    % a line
        
    numLinesRead = numLinesRead + 1;
    lines{numLinesRead} = thisLine;
    
    % read the next line
    
    thisLine = fgetl(fid);  
  end; % end of while loop

  % close the input file
  
  fclose(fid);
  
end; % if fileIsOpen





% if the operation was successful, the lines from 'input.txt' have
% been left in the cell array called lines




