C
C     ..................................................................
C
C        SUBROUTINE SRANK
C
C        PURPOSE
C           TEST CORRELATION BETWEEN TWO VARIABLES BY MEANS OF SPEARMAN
C           RANK CORRELATION COEFFICIENT
C
C        USAGE
C           CALL SRANK(A,B,R,N,RS,T,NDF,NR)
C
C        DESCRIPTION OF PARAMETERS
C           A   - INPUT VECTOR OF N OBSERVATIONS FOR FIRST VARIABLE
C           B   - INPUT VECTOR OF N OBSERVATIONS FOR SECOND VARIABLE
C           R   - OUTPUT VECTOR FOR RANKED DATA, LENGTH IS 2*N. SMALLEST
C                 OBSERVATION IS RANKED 1, LARGEST IS RANKED N. TIES
C                 ARE ASSIGNED AVERAGE OF TIED RANKS.
C           N   - NUMBER OF OBSERVATIONS
C           RS  - SPEARMAN RANK CORRELATION COEFFICIENT (OUTPUT)
C           T   - TEST OF SIGNIFICANCE OF RS (OUTPUT)
C           NDF - NUMBER OF DEGREES OF FREEDOM (OUTPUT)
C           NR  - CODE, 0 FOR UNRANKED DATA IN A AND B, 1 FOR RANKED
C                 DATA IN A AND B (INPUT)
C
C        REMARKS
C           T IS SET TO ZERO IF N IS LESS THAN TEN
C
C        SUBROUTINES AND FUNCTION SUBPROGRAMS REQUIRED
C           RANK
C           TIE
C
C        METHOD
C           DESCRIBED IN S. SIEGEL, 'NONPARAMETRIC STATISTICS FOR THE
C           BEHAVIORAL SCIENCES', MCGRAW-HILL, NEW YORK, 1956,
C           CHAPTER 9
C
C     ..................................................................
C
      SUBROUTINE SRANK(A,B,R,N,RS,T,NDF,NR)
      DIMENSION A(1),B(1),R(1)
C
      FNNN=N*N*N-N
C
C        DETERMINE WHETHER DATA IS RANKED
C
      IF(NR-1) 5, 10, 5
C
C        RANK DATA IN A AND B VECTORS AND ASSIGN TIED OBSERVATIONS
C        AVERAGE OF TIED RANKS
C
    5 CALL RANK (A,R,N)
      CALL RANK (B,R(N+1),N)
      GO TO 40
C
C        MOVE RANKED DATA TO R VECTOR
C
   10 DO 20 I=1,N
   20 R(I)=A(I)
      DO 30 I=1,N
      J=I+N
   30 R(J)=B(I)
C
C        COMPUTE SUM OF SQUARES OF RANK DIFFERENCES
C
   40 D=0.0
      DO 50 I=1,N
      J=I+N
   50 D=D+(R(I)-R(J))*(R(I)-R(J))
C
C        COMPUTE TIED SCORE INDEX
C
      KT=1
      CALL TIE (R,N,KT,TSA)
      CALL TIE (R(N+1),N,KT,TSB)
C
C        COMPUTE SPEARMAN RANK CORRELATION COEFFICIENT
C
      IF(TSA) 60,55,60
   55 IF(TSB) 60,57,60
   57 RS=1.0-6.0*D/FNNN
      GO TO 70
   60 X=FNNN/12.0-TSA
      Y=X+TSA-TSB
      RS=(X+Y-D)/(2.0*(SQRT(X*Y)))
C
C        COMPUTE T AND DEGREES OF FREEDOM IF N IS 10 OR LARGER
C
      T=0.0
   70 IF(N-10) 80,75,75
   75 T=RS*SQRT(FLOAT(N-2)/(1.0-RS*RS))
   80 NDF=N-2
      RETURN
      END
