
      SUBROUTINE func (n, v, p, g)

      IMPLICIT UNDEFINED (A-Z)
      INTEGER n
      REAL    v (n), g (n)
      REAL    p

C       Chi-squared and derivatives.

        REAL x (40), y (40), s (40)
        INTEGER npnts
        COMMON /data/ x, y, s, npnts

        REAL    df (10)
        LOGICAL debug
        COMMON /debug/ debug

        INTEGER ldf
        DATA ldf /10/

        INTEGER i, j
        REAL    thy, dev

        IF (n .GT. ldf) THEN
          WRITE (6, *) '***func: Array needs redimensioning.'
          STOP
        ENDIF

        IF (debug) THEN
          WRITE (6, *) 'Entering func.'
          WRITE (6, *) 'v =', v
        ENDIF

        p = 0.0
        DO 10 j = 1, n
          g (j) = 0.0
 10     CONTINUE

        DO 30 i = 1, npnts
          CALL model (x (i), v, n, thy, df)
          IF (s (i) .EQ. 0.0) THEN
            WRITE (6, *) '***func: Standard deviation = 0.  i =', i
            STOP
          ENDIF
          dev = (thy - y (i)) / s (i)
          p   = p + dev**2
          DO 20 j = 1, n
            g (j) = g (j) + ((2 * dev * df (j)) / s (i))
 20       CONTINUE
 30     CONTINUE
        
        IF (debug) THEN
          WRITE (6, *) 'p =', p
          WRITE (6, *) 'g:', g
          WRITE (6, *) 'Exiting func'
        ENDIF

        RETURN
      END

      SUBROUTINE model (t, v, n, y, dy)

      IMPLICIT UNDEFINED (A-Z)
      INTEGER n
      REAL    v (n), dy (n)
      REAL    t, y

C     Curve to be fitted, and derivatives.

        REAL b, tcrit, x

        b     = v (1)
        tcrit = v (2)
  
        IF (t .GT. tcrit) THEN
          x = t - tcrit
          y = x / b**2
          dy (1) = - (2 * x) / b**3
          dy (2) = - 1.0 / b**2
        ELSE
          y = 0.0
          dy (1) = 0.0
          dy (2) = 0.0
        ENDIF
  
        RETURN
      END
