*-----------------------------------------------------------------------
*    Runge-Kutta dirver (Variable step)
*-----------------------------------------------------------------------
*     Copyright (C) 2000-2022 GFD Dennou Club. All rights reserved.
*-----------------------------------------------------------------------
      SUBROUTINE ODRKDV(N, STEPER, FCN, T, TEND, DT, X, WORK)

      DIMENSION X(N), WORK(N,*)
*                     WORK(N,7) FOR ODRK4R
*                     WORK(N,5) FOR RKGR
      EXTERNAL  FCN, STEPER
      SAVE

      IF(DT*(TEND-T).LE.0.)
     #             CALL MSGDMP('E', 'ODRKDV', 'INVALID TEND OR DT.')

      CALL ODIGET('MAXSTEP', MXSTEP)
      CALL ODRGET('EPSILON', EPSL)

      T0  = T
      DTT = DT

      DO 10 I=1,MXSTEP
        DT = DTT
        IF((T+DT*2-TEND)*(T+DT*2-T0).GT.0.) DTT=(TEND-T)/2.
        CALL STEPER(N, FCN, T, DTT, EPSL, X, WORK)
        NS = I
        IF((T-TEND)*(TEND-T0).GE.0.) THEN
          CALL ODISET('NSTEP', NS)
          RETURN
        ENDIF
   10 CONTINUE
      CALL MSGDMP('W', 'ODRKDV', 'TOO MANY STEPS.')

      RETURN
      END
