      SUBROUTINE SORTIM(Q,TQ,NQ,NORUN,SAMTIM,LIM,HELJD,MODE)     
C     
C     ROUTINE TO SORT THE RUNS INTO CHRONOLOGICAL ORDER OF HELJD
C     OF THE START OF THE RUN IF MODE=0, OR IN ORDER OF TQ IF MODE=1
C     
      DIMENSION Q(1),SAMTIM(1),LIM(2,1),QSTORE(5000),TQSTOR(5000)   
      DOUBLE PRECISION TQ(1),HELJD(1),TIME,XTEMP
      IF(MODE.NE.0)GO TO 200
      PRINT 5
    5 FORMAT(12X,'BEFORE THE SORT:'/
     *       12X,'----------------'/)
      PRINT 75
      PRINT 100,(J,SAMTIM(J),HELJD(J),LIM(1,J),TQ(LIM(1,J)),
     *           Q(LIM(1,J)),LIM(2,J),TQ(LIM(2,J)),Q(LIM(2,J)),
     *           J=1,NORUN)
      PRINT 125
   10 IFLAG=0
      DO 50 J=1,NORUN-1
        IF(HELJD(J).GT.HELJD(J+1))THEN
C
C         FIRST SWOP THE ARRAYS
C
          NQJ=LIM(2,J)-LIM(1,J)+1
          KK=LIM(1,J)
          DO 20 K=1,NQJ
            QSTORE(K)=Q(KK+K-1)
            TQSTOR(K)=TQ(KK+K-1)
   20     CONTINUE
          NQJ1=LIM(2,J+1)-LIM(1,J+1)+1
          KK=LIM(1,J+1)
          II=LIM(1,J)
          DO 25 K=1,NQJ1
            Q(II+K-1)=Q(KK+K-1)
            TQ(II+K-1)=TQ(KK+K-1)
   25     CONTINUE
          LIM(2,J)=LIM(1,J)+NQJ1-1
          LIM(1,J+1)=LIM(2,J)+1
          II=LIM(1,J+1)
          DO 30 K=1,NQJ
            Q(II+K-1)=QSTORE(K)
            TQ(II+K-1)=TQSTOR(K)
   30     CONTINUE
C
C         NOW SWOP THE OTHER PARAMETERS
C
          TIME=HELJD(J)
          STIME=SAMTIM(J)
          HELJD(J)=HELJD(J+1)
          SAMTIM(J)=SAMTIM(J+1)
          HELJD(J+1)=TIME
          SAMTIM(J+1)=STIME
          IFLAG=1
        END IF
   50 CONTINUE
      IF(IFLAG.EQ.1)GO TO 10
      PRINT 60
   60 FORMAT(12X,'AFTER  THE SORT:'/
     *       12X,'----------------'/)
      PRINT 75
      PRINT 100,(J,SAMTIM(J),HELJD(J),LIM(1,J),TQ(LIM(1,J)),
     *           Q(LIM(1,J)),LIM(2,J),TQ(LIM(2,J)),Q(LIM(2,J)),
     *           J=1,NORUN)
      PRINT 125
   75 FORMAT(12X,'RUN   DT  START HJD  FIRST         TIME          Q',
     *           '   LAST         TIME          Q'/12X,81('-'))
  100 FORMAT(12X,I3,0PF5.1,F11.5,I7,F13.1,1PE11.3,I7,0PF13.1,1PE11.3)
  125 FORMAT(12X,81('-'))
      RETURN
  200 IF(MODE.NE.1)RETURN
C
C     BUBBLE SORT THE DATA
C
  210 IFLAG=0
      DO J=2,NQ
        IF(TQ(J).LT.TQ(J-1))THEN
          IFLAG=1
          XTEMP=TQ(J)
          YTEMP=Q(J)
          TQ(J)=TQ(J-1)
          Q(J)=Q(J-1)
          TQ(J-1)=XTEMP
          Q(J-1)=YTEMP
        END IF
      END DO
      IF(IFLAG.EQ.1)GO TO 210

      RETURN
      END   
