%N nllsqu %F $MIR/src/subs/nllsqu.for
%D Nonlinear least squares fitting
%P bpw
%: least-squares, fitting
%B
        subroutine nllsqu(n,m,x,h,itmax,eps1,eps2,der,ifail,
     *    FUNCTION,DERIVE,f,fp,dx,dfdx,aa)

        implicit none
        integer n,m,itmax,ifail
        real eps1,eps2,x(n),h(n)
        logical der
        external FUNCTION,DERIVE

        real f(m),fp(m),dx(n),dfdx(n,m),aa(n,n)

  NLLSQU minimizes the sum of squares, and solves a set of nonlinear
  equations. This is derived from H. Spath, "The damped Taylors series
  method for minimizing a sum of squares and solving systems of nonlinear
  equations." Comm. ACM v10, n11, p726-728.

  There have been some modifications to the algorithm as presented in CACM.
  In particular the call sequence is different, and the algorithm has been
  mildly improved in a few places.

  Inputs:
    n          Number of unknowns.
    m          Number of nonlinear equations.
    itmax      Max no of iterations.
    eps1       Iteration stops if (sum f**2) < eps1
    eps2       Iteration stops if eps2 * sum (abs(x)) < sum( abs(dx) )
    der        Logical. If true, then the derivative routine is called. If
               false, the derivative is estimated by many calls to FUNCTION.
    h          This is used ONLY if der=.false. It gives the step sizes
               to use in estimating partial derivatives.
  Input/Output:
    x          Input: Initial estimate of solution.
               Output: The best solution so far.

  Scratch:
    f
    fp
    dx
    dfdx
    aa

  Outputs:
    ifail      ifail = 0 All OK.
                       1 Singular matrix encountered.
                       2 Max number of iterations exceeded.
                       3 Failure to find better solution.

  Externals:
       The external FUNCTION must be implemented. But DERIVE is not
       needed if "der" is set false.

c      subroutine DERIVE(x,dfdx,n,m)
c      real x(n),dfdx(n,m)
c Inputs:
c      x       Prospective solution.
c Outputs:
c      dfdx    Derivatives of the nonlinear equation for this particular
c              value of x.
c
c      subroutine FUNCTION(x,f,n,m)
c      real x(n),f(m)
c Inputs:
c      x       Prospective solution.
c Outputs:
c      f       Value of the m nonlinear equations, given x.
