function [ vars, data ] = readtabular( filename )
%[vars, data] = readtabular(filename)
%[vars, data] = readtabular('cantilever_centered_tabular.dat');
%
%  Description:
%
%    Open and read the tabular data file from Dakota.
%
%  Inputs:
%
%    filename = string with the name of the file
%
%  Outputs:
%
%    vars = cell vector containing the variables and responses
%    data = array containing the variables and reponses for each Dakota
%             function evaluation
%
%  Contact:
%
%    Bob Cochran
%    Applied CHT
%    rjc@heattransfer.org
%
%  History:
%
%    Who    Date   Version  Note
%    ---  -------- -------  -----------------------------------------------
%    RJC  05/16/17  0.1.0   Initial release.
%
%==========================================================================

fid = fopen(filename);

line = fgetl(fid);
tok = regexp(line,'[a-zA-Z_0-9+-./]*','match');   % header line from file
vars = tok(3:end);

ndat = 0;
while 1
  line = fgetl(fid);  %  Fetch the next line from the input file
  if ~ischar(line)    %  Check for the end of file
    if ~fclose(fid)   %  Close the file      
      return
    else
      error('Error closing the data file.')
    end
  end
  ndat = ndat + 1;
  tok = regexp(line,'[a-zA-Z_0-9+-./]*','match');
  for i=3:length(tok)
    data(ndat,i-2) = str2num(tok{i});  % Extract the data
  end
end