C....*...1.........2.........3.........4.........5.........6.........7.*.......8
C     DRUNS    5/18/75
C
C     PURPOSE
C     RUNS TEST FOR REGRESSION RESIDUALS
C
C     USAGE
C     CALL DRUNS(E,N,NN,N1,N2,NR,ER,Z)
C
C     ARGUMENTS
C     E  - INPUT VECTOR OF RESIDUALS
C          REAL*8
C     N  - LENGTH OF E
C          INTEGER*4
C     NN - NUMBER OF NON-ZERO RESIDUALS
C          INTEGER*4
C     N1 - NUMBER OF POSITIVE RESIDUALS
C          INTEGER*4
C     N2 - NUMBER OF NEGATIVE RESIDUALS
C          INTEGER*4
C     NR - NUMBER OF RUNS
C          INTEGER*4
C     ER - EXPECTED NUMBER OF RUNS
C          REAL*8
C     Z  - Z-STATISTIC
C          REAL*8
C
C     REFERENCE
C     DRAPER, N.R. AND SMITH, H.  APPLIED REGRESSION ANALYSIS.
C     NEW YORK: JOHN WILEY AND SONS, INC., 1966.  SEC. 3.9.
C
C
      SUBROUTINE DRUNS(E,N,NN,N1,N2,NR,ER,Z)
      IMPLICIT REAL*8 (A-H,O-Z)
      save
      REAL*8 E(1)
      N1=0
      N2=0
      DO 10 I=1,N
      IF(E(I).GT.0.D0) N1=N1+1
10    IF(E(I).LT.0.D0) N2=N2+1
      NN=N1+N2
      FN1=N1
      FN2=N2
      FNN=NN
      ER=(2.D0*FN1*FN2)/FNN+1.D0
      S=((2.D0*FN1*FN2)*(2.D0*FN1*FN2-FNN))/((FNN**2)*(FNN-1.D0))
      S=DSQRT(S)
      NR=1
      J=N
      DO 20 I=1,N
      IF(E(I).EQ.0.D0) GO TO 20
      J=I
      GO TO 30
20    CONTINUE
30    IF(J.EQ.N) GO TO 50
      LAG=-1
      IF(E(J).GT.0.D0) LAG=1
      J=J+1
      DO 40 I=J,N
      IF(E(I).LT.0.D0) ISGN=-1
      IF(E(I).GT.0.D0) ISGN=1
      IF(E(I).EQ.0.D0) ISGN=LAG
      IF(LAG.NE.ISGN) NR=NR+1
40    LAG=ISGN
50    FNR=NR
      Z=(FNR-ER+.5D0)/S
      RETURN
      END
