function [ err, n, inds ] = errorLS(lsFile, pts, scaleFactors, errorType)
% [ err, n, inds ] = errorLS(lsFile, pts, scaleFactors, errorType)
%
% computes 1, 2 and/or infty norms of the value of the level set function
%    stored in lsFile at the 3D points in pts
%
%   errorType = 1       return sum of absolute value / n
%               2       return sum of squares / n
%               Inf     return maximum absolute value
%       the default is to return a vector of the errors in the above order
%
% n is the number of rows in pts
% inds is the indicies of the points in pts, sorted in descending abs error
%
% Ian Mitchell for TransAC, 5/4/01

if(nargin < 3)
  scaleFactors = [ 25; 25; 2*pi ];                        % for aircraft3D 
end

n = size(pts, 1);

if(size(pts, 2) ~= 3)
  error('errorLS only works on 3D data sets');
end

% which interpolation method to use
method = '*cubic';              % can use * version on uniform grids
%method = '*linear';

% load level set
[ lsFunc, vecs ] = loadFunc(lsFile, 1);

% create level set's grid
[ xs, ys, zs ] = meshgrid(vecs{1} * scaleFactors(1), ...
                          vecs{2} * scaleFactors(2), ...
                          vecs{3} * scaleFactors(3));

% interpolate values of level set at pts
vals = interp3(xs, ys, zs, lsFunc, pts(:,1), pts(:,2), pts(:,3), method);

% compute error norms
if(nargin < 4)
  err = [ norm(vals, 1) / n; norm(vals, 2) / n; norm(vals, inf) ];
else
  err = norm(vals, errorType);
  if(~isinf(errorType))
    err = err / n;
  end
end

if(nargout > 2)
  [ sorted inds ] = sort(-abs(vals));
end
