function [ func, vecs ] = loadFunc(filename, stride, infinity)
%  [ func, vecs ] = loadFunc(filename, stride, infinity)
%
% loads a level set function from the file given by filename
%
% the file will contain the following data in order
%	one line giving the dimension of the function
%	dimension lines giving the coordinates
%		<lower bound>  <delta x>  <upper bound>
%	data values one to a line thereafter
%
% the data are read and stored in func
% vectors for the coordinate system are stored in the cell array vecs
%
% Ian Mitchell for aa278, 6/1/00
%
% $Id: loadFunc.m,v 1.1 2000/10/11 16:46:55 imitchel Exp imitchel $

dataFormat = '%lf';

if(nargin < 2)
  stride = 1;
end

if(nargin < 3)
  infinity = inf;
end

fh = fopen(filename, 'r');
if(fh == -1)
  error([ 'unable to open file ' filename ]);
end

% load data about the grid
dim = fscanf(fh, '%d', 1);

vecs = cell(dim, 1);
ns = zeros(1, dim);

for i = 1:dim
  lb = fscanf(fh, dataFormat, 1);
  dx = fscanf(fh, dataFormat, 1);
  ub = fscanf(fh, dataFormat, 1);
  vecs{i} = (lb : dx : (ub + dx / 2))';
  if(abs(vecs{i}(end) - ub) > dx / 100)
    warning([ 'Having problems with grid; upper bound error ' ...
              num2str(vecs{i}(end) - ub) ]);
  end
  ns(i) = length(vecs{i});
  vecs{i} = vecs{i}(1:stride:end);
end

% get the level set data, and close the (now exhausted) file
[ func count ] = fscanf(fh, dataFormat, prod(ns));
fclose(fh);

% check that the number of nodes in the grid agrees with the amount of data
if(count ~= prod(ns))
  error([ 'insufficient data detected in file ' filename ]);
end

% reshape to the grid size
if(dim > 1)
  func = reshape(func, ns);
end

% if we are striding, some data is unnecessary
if(stride > 1)
  switch(dim)
  case 1
    func = func(1:stride:end);
  case 2
    func = func(1:stride:end, 1:stride:end);
  case 3
    func = func(1:stride:end, 1:stride:end, 1:stride:end);
  case 4
    func = func(1:stride:end, 1:stride:end, 1:stride:end, 1:stride:end);
  otherwise
    warning(['unable to use nonunit stride in ' num2str(dim) ' dimensions.']);
  end
end

% for display, matlab likes the first two dimensions in wrong order
order = 1:dim;
order(1:2) = [ 2 1 ];
func = permute(func, order);
