function [p,e]=mmnlfit(x,y,fun,po,options)
%MMNLFIT Nonlinear Curve Fitting. (MM)
% P=MMNLFIT(X,Y,'FUN',P0,OPTIONS) fits the data in X and Y in a
% least squares sense to the function described in FUN.M.
% MMNLFIT solves:
%                 min ||Y - FUN(X,P)||^2
%                  P
% X is a vector of the independent variable. FUN(X,P) must
% return an array the same size as Y. P is a vector of parameters
% to be determined and P0 is the initial guess.
%
% MMNLFIT calls the standard MATLAB function FMINS to perform
% the minimization. OPTIONS is an optional vector as used by FMINS:
% OPTIONS(i) Values  Default  Decription
%    1       0 or 1     0     True to show intermediate steps.
%    2        >0      1e-4    Tolerance on P.
%    3        >0      1e-4    Tolerance on FUN(X,P).
%   14        >0       500    Maximum iterations.
%
% [P,E]=MMNLFIT(...) in addition returns the mean squared error
% of the fit.

% Calls: mmnlfit_

% D.C. Hanselman, University of Maine, Orono, ME 04469
% 7/14/96
% Mastering MATLAB, Prentice Hall, ISBN 0-13-191594-0

if nargin<5, options=[]; end
sy=size(y);
yf=feval(fun,x,po);
sf=size(y);
if any(sy-sf)
	error('Y and FUN(X,P) Must be the Same Size.')
end

[p,opt]=fmins('mmnlfit_',po,options,[],x,y,[],fun);

if opt(10)>=opt(14)
	disp(['Solution May be Incorrect: ';...
	      'Maximum Iterations Reached.';...
		  'Increase OPTIONS(14) or Try';...
		  'Different Initial Estimates'])
end

if nargout==2
	e=mmnlfit_(p,x,y,[],fun);
end
