function [camber, rc] = mfs_fitcamber(data, splopts)

# usage: [camber, rc] = mfs_fitcamber(data, splopts)
#
# Input  data(:, 2)  x- and z-coordinates of points on camber
#        splopts     either number of spline intervals or
#                    structure with spline options
#
# Output camber      Piecewise polynomial defining camber
#        rc          Return code: 0 = no errors
#
# Structure splopts has the following fields:
#
#   nbcam   Number of camber spline intervals
#   nbcon   Number of contour spline intervals (not used)
#   smooth  Number of loops to smooth data
#
# Smoothing, if requested, is done by averaging over 3 adjacent
# points.
#
# ---------------------------------------------------------------------

# Check arguments

  if (nargin != 2 || nargout != 2)
     print_usage();
  end

# Initialize

  camber = struct();
  rc     = 0;
  np     = rows(data);

# Check spline options

  if (isstruct(splopts))
     if (! isfield(splopts, "nbcam"))
        printf("*E* mfs_airfoil: number of spline intervals undefined\n");
        rc = 1; return;
     else
        nb = splopts.nbcam;
     end
     if (isfield(splopts, "smooth"))
        for s = 1 : splopts.smooth
            data(2 : end - 1, 2) = (data(1 : end - 2, 2) + ...
                                    data(2 : end - 1, 2) + ...
                                    data(3 : end, 2)) / 3;
        end
     end
  else
     nb = splopts;
  end

  if (nb <= 0)
     printf("*E* mfs_airfoil: number of spline intervals must be positive\n");
     rc = 1; return;
  end
  if (nb > np)
     printf("*E* mfs_airfoil: number of spline intervals (%d) exceeds\n", nb);
     printf("                 number of data points (%d)\n", np);
     rc = 1; return;
  end

# Create spline fit

  data   = data / data(end, 1);
  camber = splinefit(data(:, 1), data(:, 2), nb, "robust", 1);

end
