      SUBROUTINE BIN1(Q,TQ,NQ,NORUN,SAMTIM,LIM,HELJD)     
C     
      DIMENSION Q(NQ),SAMTIM(NORUN),LIM(2,NORUN)   
      DOUBLE PRECISION TQ(NQ),CYCLE,TQ1
      DOUBLE PRECISION EPOCH,PERIOD,HELJD(NORUN)  
      DIMENSION BINS(1000),NBINS(1000)     
C     
C     ROUTINE TO BIN DATA.  THIS ROUTINE USES THE FIRST DATA POINT       
C     AS THE FIRST BIN AND FOLDS ON THE SPECIFIED PERIOD (IN DAYS)
C     ENDING UP WITH NB BINS. THIS ROUTINE DOES NOT THEREFORE NEED
C     THE DATA TO BE FOLDED ON AN EPHEMERIS WITH TIMBAS LIKE THE
C     ROUTINE BIN DOES.
C     
      IDIV=0
      READ *,EPOCH,PERIOD,NB     
      ITWO=0
      IF(PERIOD.LT.0.0)THEN
        PERIOD=-PERIOD
        ITWO=1
      END IF
      IF(NB.LT.0)THEN   
        IDIV=1    
        NB=-NB    
      END IF
      PRINT 10,PERIOD,EPOCH,NB   
   10 FORMAT(12X,'DATA TO BE BINNED ON THE PERIOD ',F18.9,' DAYS'/
     *       12X,'W.R.T. EPOCH ',f15.6,'  USING ',I4,' BINS')     
      IF(IDIV.GT.0)PRINT 12   
   12 FORMAT(12X,'DATA WILL NOT BE NORMALIZED BY NUMBER IN BIN')  
      IF(ITWO.EQ.1)PRINT 14
   14 FORMAT(12X,'DATA WILL BE REPEATED TO COVER TWO CYCLES')
      IF(NB.GT.1000)THEN
        PRINT 15  
   15   FORMAT(12X,'TOO MANY BINS REQUESTED - MAX IS 1000') 
        STOP
      END IF
      DO 20 J=1,1000    
        BINS(J)=0.0     
        NBINS(J)=0.0    
   20 CONTINUE    
      PERIOD=PERIOD*86400.0D0
      TQ1=(EPOCH-HELJD(1))*86400.0d0
      DO 30 J=1,NQ
        CYCLE=(TQ(J)-TQ1)/PERIOD
        CYCLE=CYCLE-INT(CYCLE)
        IB=1+(CYCLE*FLOAT(NB))
   25   IF(IB.GT.NB)THEN   
          IB=IB-NB      
          GO TO 25
        END IF    
   26   IF(IB.LT.1)THEN
          IB=IB+NB
          GO TO 26
        END IF
        BINS(IB)=BINS(IB)+Q(J)
        NBINS(IB)=NBINS(IB)+1 
   30 CONTINUE    
      NQ=0  
      DO 50 J=1,NB
        Q(J)=BINS(J)    
        TQ(J)=TQ1+(FLOAT(J)-0.5)*PERIOD/FLOAT(NB)
        IF(IDIV.EQ.0.AND.NBINS(J).GT.0)Q(J)=Q(J)/NBINS(J)   
        IF(ITWO.EQ.1)THEN
          Q(J+NB)=Q(J)  
          TQ(J+NB)=TQ(J)+PERIOD
          NQ=NB   
        END IF    
   50 CONTINUE    
      PRINT 60,(NBINS(J),J=1,NB)    
   60 FORMAT(12X,20I6)  
      NQ=NQ+NB    
      NORUN=1
      SAMTIM(NORUN)=PERIOD/FLOAT(NB)
      LIM(1,NORUN)=1
      LIM(2,NORUN)=NQ
      RETURN
      END   
