
!***************************************************************************

 module approachlib

!  Fortran module with math, astro and celmech routines needed to compute
!  closest approaches between pair of minor planets
!
!  Aut : F. Mignard,
!  Version date : August 2005
!
!***************************************************************************
!   This section initializes global parameters and arrays default values.


   integer,       parameter :: dp        = selected_real_kind(15, 60)

!
!     Primary constants
!
   
   real(kind=dp), parameter :: pi        = 3.141592653589793238462643d0
   real(kind=dp), parameter :: deupi     = 6.283185307179586476925286d0
   real(kind=dp), parameter :: degrad    = pi/180d0                       !  1.74532925199433d-2   :: radians to degree
   real(kind=dp), parameter :: raddeg    = 180d0/pi                       !  57.2957795130823d0    :: degree to radian

   real(kind=dp), parameter  ::xjd2000   = 2451545d0                      ! 1.5 Jan 2000     = J2000
   real(kind=dp), parameter :: xjd2010   = 2455197.5d0                    ! 1.0 Jan 2010 0h  = J2010.0.
   real(kind=dp), parameter :: xk        = 0.01720209895000d0             ! xk : Gauss constant  
   real(kind=dp), parameter :: year      = 365.25d0                       ! julian year    in days
   real(kind=dp), parameter :: century   = 36525d0                        ! julian century in days
   real(kind=dp), parameter :: daym      = 1440d0                         ! day in minutes
   real(kind=dp), parameter :: days      = 86400d0                        ! day in seconds
   real(kind=dp), parameter :: dayh      = 24d0	                          ! day in hours
   real(kind=dp), parameter :: round     = 360d0	                      
   real(kind=dp), parameter :: audtokms  = 1731.45683670139d0             !  1731.45683670139d0   :: au/day to km/s
   real(kind=dp), parameter :: degmas    = 3.600d6                        !  3.6e6                ::degree to mas
   real(kind=dp), parameter :: xau       = 149597870.690959d0             !  149597870.690959d0    :: AU in km (TDB)
 
!
!     Derived constants
!
   real(kind=dp), parameter :: radmas    = 180d0/pi*3.600d6               !  206264806.247096d0    :: radian to mas
   real(kind=dp), parameter :: gm        = xk*xk                          !  2.95912208285591d-4   :: gm =xk^2 (units will be au and days)         


contains
!************************************************************************!******************************************************
      function rad(xdeg)
!******************************************************
!
!
!       Transformation from degree to radians
!
!       author F. Mignard OCA/CERGA
!
!*** Input 
!
!       xdeg  : angle in decimal degrees
!
!*** Output
!
!       rad(xdeg) : angle in radians
!
! 
!******************************************************
      implicit none
      real(kind=dp), intent(in) ::  xdeg
      real(kind=dp)             ::  rad

        
      rad = pi/180.0d0*xdeg
        
      return
      end function rad
!******************************************************
      function deg(xrad)
!******************************************************
!
!
!       Transformation from radians to degrees
!
!       author F. Mignard OCA/CERGA
!
!*** Input 
!
!       xrad  : angle in radians 
!
!*** Output
!
!       deg(xrad) : angle in degrees
!
! 
!******************************************************
      implicit none

      real(kind=dp), intent(in) ::  xrad
      real(kind=dp)             ::  deg

        
      deg = (180.0d0/pi)*xrad
        
      return
      end   function deg

!******************************************************
      function angle(x,y)
!******************************************************
!
!
!     angle solution of x = r*cos(teta), y = r*sin(teta)  r >0
!
!     author F. Mignard OCA/CERGA
!
!***  INPUT
!
!     x      : r*cos(teta)
!     y      : r*sin(teta)
!
!***  OUTPUT 
!
!     angle  : angle in degrees in 0 - 360
! 
!******************************************************
      implicit none

      real(kind=dp), intent(in) ::  x, y
      real(kind=dp)             ::  angle
      real(kind=dp)             ::  xx 
!******************************************************

      if((x*x+y*y) == 0) then
        xx = 0                  ! conventional value for the zero vector
      else
        xx = deg(atan2(y,x))    ! atan2d is not in double precision
      endif

      if(xx <0) then
        xx  = xx +360.d0
      endif

      angle = xx
      return
      end function angle
!***********************************************************
      function sind(x)
!***********************************************************
!
!     sin with argument in degree
!     could be deleted if sind is accepted by the Fortran implementation
!
      implicit none
      real(kind=dp) x, sind
          sind = sin(x*degrad) 
      end function sind

!***********************************************************
      function cosd(x)
!***********************************************************
!
!     cos with argument in degree
!     could be deleted if cosd is accepted by the Fortran implementation
!
      implicit none
      real(kind=dp) x, cosd
          cosd = cos(x*degrad) 
      end function cosd


!***********************************************************
      function tand(x)
!***********************************************************
!
!     tan with argument in degree
!     could be deleted if tand is accepted by the Fortran implementation
!
      implicit none
      real(kind=dp) x, tand
          tand = tan(x*degrad) 
      end function tand

!***********************************************************
      function asind(x)
!***********************************************************
!
!     asin with result in degree
!     could be deleted if asind is accepted by the Fortran implementation
!
      implicit none
      real(kind=dp) x, asind
          asind = asin(x)*raddeg 
      end function asind
!***********************************************************
      function acosd(x)
!***********************************************************
!
!     acos with result in degree
!     could be deleted if acosd is accepted by the Fortran implementation
!
      implicit none
      real(kind=dp) x, acosd
          acosd = acos(x)*raddeg 
      end function acosd

!***********************************************************
      function atand(x)
!***********************************************************
!
!     atan with result in degree
!     could be deleted if atand is accepted by the Fortran implementation
!
      implicit none
      real(kind=dp) x, atand
          atand = atan(x)*raddeg 
      end function atand

      
!***********************************************************
      function atan2d(x,y)
!***********************************************************
!
!     atan2 with result in degree
!     could be deleted if atan2d is accepted by the Fortran implementation
!
      implicit none
      real(kind=dp) x, y, atan2d
          atan2d = atan2(x,y)*raddeg 
      end function atan2d
!******************************************************
      function sqr(x)
!******************************************************
!       square of a real number (for compatibility with Pascal source)
!
!       author F. Mignard OCA/CERGA
!
!*** Input 
!
!       x  : number to be squared
!
!*** Output
!
!      sqr(x) : x*x
!
! 
!******************************************************
      implicit none
      real(kind = dp)  x, sqr

      sqr = x*x

      return
      end function sqr
         

!***********************************************************
!******************************************************
      subroutine carsphe (v, rho, alpha, delta)
!******************************************************
!
!     Transformation from cartesian coordinates to spherical.
!     latitude from the equator and not from the pole
!
!     author F. Mignard OCA/CERGA
!
!***  INPUT
!
!       v    : input vector v(3)
!
!***  OUTPUT 
!
!      rho   : modulus of v
!      alpha : longitude in degrees
!      delta : latitude in degrees
! 
!      for the poles : alpha = 0
!******************************************************
      implicit none
      
      real(kind=dp), intent(in)          :: v(3)
      real(kind=dp), intent(out)         :: rho, alpha, delta
      real(kind=dp)                      :: rhop

!******************************************************
      rho  = sqrt(dot_product(v,v))
      rhop = sqrt(v(1)*v(1) +v(2)*v(2))

      if(rho==0) then
         alpha = 0d0        ! conventional values
         delta = 0d0
      else
         if(rhop==0) then
            if(v(3) >0) then
               delta =  90.0d0
            else
               delta = -90.0d0
            endif
            alpha = 0.0d0   ! conventional value
         else
            delta = deg(atan(v(3)/rhop)) 
            alpha = angle(v(1), v(2))
         endif
      endif
      return
      end  subroutine carsphe 
!******************************************************
      function arc(phi1,phi2,xlam1,xlam2)
!******************************************************
!    Arclength in degrees between two points on the unit sphere    
!    Input : angular coordinates in degrees of the two points      }
!
!    units :   degrees
!
!     Author      : F. Mignard OCA/CERGA
!
!*** INPUT
!      phi1   : latitude  first  point in deg
!      phi2   : latitude  second point in deg
!      xlam1  : longitude first  point in deg
!      xlam2  : longitude second point in deg
!
!*** OUTPUT
!
!      arc    : angular distance between the two points in deg  0<= arc <= 180
!      non singular expression used, accurate even for very small arcs
!
!******************************************************
      implicit  none

      real(kind=dp), intent(in)   :: phi1, phi2, xlam1, xlam2
      real(kind=dp)               :: arc
      real(kind=dp)               :: dphi, dlam, ssp, ssl
!******************************************************

      dphi = (phi2-phi1)*0.5d0
      dlam = (xlam2-xlam1)*0.5d0

      ssp   = sind(dphi)
      ssl   = sind(dlam)

      arc = 2*deg(asin(sqrt(ssp*ssp +cosd(phi1)*cosd(phi2)*ssl*ssl)))

      return
      end  function arc
!******************************************************
      subroutine rota(v_in,angle,iaxe, v_out)
!******************************************************
!
!
!    Application of a canonical rotation to a vector
!
!
! Author      : F. Mignard OCA/CERGA
!
!*** INPUT
!
!    v_in     : input 3D vector  array(3)
!    angle    : angle of rotation in degrees
!    iaxe     : 1 (=x) , 2 (=y) , 3(=z) for the axis of rotation
!
!***OUTPUT
!
!    v_out     : output 3D vector  array(3)
! 
!
!    remark   : the routine may be called with the same input and output vector like
!              call rota(v,angle, iaxe, v). 
! 
!  convention : the reference frame is rotated, not the vector  : so one has
!               the coordinate of the same vector in the old and new frame.
!
!********************************************************
      implicit none

      real(kind=dp), dimension(3), intent(in)     :: v_in
      real(kind=dp),               intent(in)     :: angle
      integer,                     intent(in)     :: iaxe

      real(kind=dp), dimension(3), intent(out)    :: v_out

      real(kind=dp), dimension(3)                 :: v
      real(kind=dp)                               :: cc,ss                         

!********************************************************
      cc = cosd(angle)
      ss = sind(angle)
      v = v_in                                   ! allow to call :  call rota(V,angle, iaxe, V)
      if((iaxe >3).or.(iaxe <1)) then
         write(*,*)  'axis value in rota : ', iaxe
         write(*, *) 'execution terminated'
         stop
      else
      select case (iaxe)
      case(1)
         v_out(1) =  v(1)
         v_out(2) =  cc*v(2)+ss*v(3)
         v_out(3) = -ss*v(2)+cc*v(3)
      case(2)
         v_out(1) =  cc*v(1)-ss*v(3)
         v_out(2) =  v(2)
         v_out(3) =  ss*v(1)+cc*v(3)
      case(3)             
         v_out(1) =  cc*v(1)+ss*v(2)
         v_out(2) = -ss*v(1)+cc*v(2)
         v_out(3) =  v(3)
      endselect
      endif
      return
      end subroutine rota
!******************************************************
      subroutine pvect(v1,v2,v)
!******************************************************
!
!     vector product : pvect = v1 X v2
!
! author  F. Mignard OCA/CERGA
!
!***  INPUT
!
!     v1    : first input 3D vector
!     v2    : second input 3D vector
!
!***  OUTPUT
!
!     v     : output vector  
!******************************************************
      implicit none
      
      real(kind=dp), intent(in)   :: v1(3), v2(3)
      real(kind=dp), intent(out)  :: v(3)

      v(1) = v1(2)*v2(3)-v1(3)*v2(2)
      v(2) = v1(3)*v2(1)-v1(1)*v2(3)
      v(3) = v1(1)*v2(2)-v1(2)*v2(1)

      return
      end  subroutine pvect
!*********************************************************************     
      Subroutine  jd_date(xjd, iyear, imonth, day)
!*********************************************************************     
!


!       Computation of the date for a given julian date
!       The julian date is in the forme jjjjjj.xxxxx..
!       and the date : day imonth iyear  with day in decimal form.
!       This program accounts for the Gregorian reformation 
!

!       F. Mignard   March 1997
!
!*Intput
!       xjd   julian day starting at noon
!
!*Output 
!       iyear    year   
!       imonth   month
!       day      decimal day starting at 0 h
!
!*********************************************************************     
!
      implicit none

      real(kind=dp), intent(in)    :: xjd
      real(kind=dp), intent(out)   :: day
      integer,       intent(out)   :: iyear, imonth

      integer, parameter           :: idur400  = 146097   ! duration in days
      integer, parameter           :: idur100  =  36524
      integer, parameter           :: idur4    =   1461
      integer, parameter           :: idur1    =    365     
      integer, parameter           :: idurm    =    306   ! 10*30.6 for the mean duration of a month

      real(kind=dp)                :: fpjd
      integer                      :: jd, nn        
       
!*********************************************************************     
      jd   = nint(xjd)
      fpjd = xjd +0.5d0- jd

!      fpjd = nint(1d8*fpjd)/1d8   ! to skip in double precision the extra digits generated by xjd - int(xjd)
      jd   = jd -114053
!
!     jd = 2299160.5  = 15/10/1582 at 0h
!       
       
      if(xjd.ge.2299160.5d0) then
         call euclid(jd,idur400, nn,jd)
         iyear = -4400 +400*nn
          
         if(jd.eq.(idur400-1)) then
            nn= 3
            jd = 36524
         else
            call euclid(jd,idur100, nn,jd)
            iyear = iyear +100*nn
         endif
      else
         iyear = -4400
         jd    =  jd +35
      endif
       
      call euclid(jd,idur4, nn,jd)
      iyear  = iyear + 4*nn
       
      if(jd.eq.(idur4-1)) then
         nn  = 3
         jd  = 365
      else
         call euclid(jd,idur1, nn,jd)
      endif
      iyear = iyear +nn
        
! 
!       jd is the number of the day in the year, starting on 1 March
!       computation of the month
!

      jd  = 10*jd +4
      call euclid(jd,idurm, imonth,nn)       
      day = int(nn/10.d0) +1.0d0 + fpjd
!
!     return to the year starting  on 1 January
!
      imonth = imonth -9
      if (imonth.le.0) then
         imonth = imonth +12
      else
         iyear  = iyear +1
      endif
       
       
      return
      end Subroutine  jd_date
!*********************************************************************     
       Subroutine euclid( ip, iq, ib, ir)
!*********************************************************************     
!
!*Rol       Euclidian division  ip = ib*iq + ir
!
!*Input
!       ip, iq : integer
!
!*Output
!       ib, ir : integer  with 0<= ir < iq
!
!*********************************************************************     
      implicit none

      integer, intent(in)     :: ip, iq
      integer, intent(out)    :: ib, ir

      ib = ip / iq
      ir = modulo(ip,iq)
        
      return
      end  subroutine euclid
!************************************************************************
      subroutine carosc(gm,pos, vit,semiaxe,eccent,gamma,gomega,pomega,anom);
!************************************************************************
!
! Transformation from position and velocity vectors to osculating elements  
!
! The units are set by the choice of gm
!
! Solar system motion :
! AU, AU/day   with  gm = k^2  (k = Gauss constant)
! k = 0.01720209895, gm = 2.9591220829e-4 
! au, au/year si gm =4pi^2  
!
! Earth satellites
! km, km/s  with  gm =398600.44 
!
! angular units  : degrees
!
!  Author  : F. Mignard
!
!*** INPUT
!
!    gm        : gravitational constant
!    pos       : array(3)  of the position vector (au or km)
!    vit       : array(3)  of the velocity vector (au/day, au:yr, km/s ==> see gm)
!
!*** OUTPUT
!
!    semiaxe   : semi major axis (au ou km according to gm)
!    eccent    : eccentricity
!    gamma     : inclination to reference plane  (deg)
!    gomega    : longitude of the ascending node (deg)
!    pomega    : argument of pericenter          (deg)
!    anom      : mean anomaly                    (deg)
! 
!******************************************************
!
      implicit none

      real(kind=dp), dimension(3), intent(in)  :: pos, vit
      real(kind=dp)              , intent(in)  :: gm
      real(kind=dp)              , intent(out) :: semiaxe,eccent,gamma,gomega,pomega,anom

      real(kind=dp), dimension(3)              :: runge, sigma 
      real(kind=dp)                            :: v2, r, c, anomv, anome, som, com, omega
      integer                                  :: i

!******************************************************

      v2 = dot_product(vit, vit)
      r  = sqrt(dot_product(pos, pos))
      
!
! angular momentum
!
      call pvect(pos, vit,sigma)
      c = sqrt(dot_product(sigma, sigma))
!
! runge vector
!

      call pvect(vit, sigma,runge)
      do i = 1 , 3  
         runge(i) = -gm / r * pos(i) + runge(i)
      enddo
!
! Semi major axis and eccentricity
!
      semiaxe   = -gm / (v2 - 2 * gm / r)
      eccent  = sqrt(abs(1d0 - c * c / (gm * semiaxe)))
!
! Node and inclination
!
      call carsphe(sigma, c, omega, gamma)
      gomega = modulo(omega + 90d0, round)
      gamma = 90 - gamma
      if(gamma == 0d0) then             ! zero inclination orbit
         gomega = 0.0d0                 ! conventional longitude of node
      endif
!
! Argument of periastron
!

      if(gamma==0) then                 ! zero inclination  ==> longitude of periastron
         pomega = angle(runge(1), runge(2))
      else
         pomega = angle(-runge(1) * sigma(2) + runge(2) * sigma(1), runge(3) * c)
      endif
      if (eccent < 1.0d-06) then        ! circular orbit
         pomega =  0.0d0                ! conventional periastron
      endif
      pomega = modulo(pomega, round)
!
! Anomalies
!

      anomv = angle(dot_product(pos, runge) / r, -c * dot_product(vit, runge) / gm)
      anome = 2 * atan(sqrt((1 - eccent) / (1 + eccent)) * tan(rad(anomv / 2d0)))
      anom  = modulo(deg(anome - eccent * sin(anome)), round)

      if(eccent.lt.1d-6) then           ! circular orbit pomega = 0
         com    = cosd(gomega)
         som    = sind(gomega)
         eccent = 0d0
         anom   = angle(pos(1)*com +pos(2)*som,(-pos(1)*som+ pos(2)*com)*c/sigma(3)) 
      endif

      return
      end   subroutine carosc
!************************************************************************
      subroutine oscar(gm, semiaxe,eccent,gamma,gomega,pomega,anom, pos, vit)
!************************************************************************
! Transformation from osculating elements to position and velocity vectors
!
! The units are set by the choice of gm
!
! Solar system motion :
! AU, AU/day   with  gm = k^2  (k = Gauss constant)
! k = 0.01720209895, gm = 2.9591220829e-4 
! au, au/year si gm =4pi^2  
!
! Earth satellites
! km, km/s  with  gm =398600.44 
!
! angular units  : degrees
!
!  Author  : F. Mignard
!
!*** INPUT
!
!    gm        : gravitational constant
!    semiaxe   : semi major axis (au ou km according to gm)
!    eccent    : eccentricity
!    gamma     : inclination to reference plane  (deg)
!    gomega    : longitude of the ascending node (deg)
!    pomega    : argument of pericenter          (deg)
!    anom      : mean anomaly                    (deg)
! 
!*** OUTPUT
!
!    pos       : array(3)  of the position vector (au or km)
!    vit       : array(3)  of the velocity vector (au/day, au:yr, km/s ==> see gm)
! 
!******************************************************
!
      implicit none

      real(kind=dp)              , intent(in)   :: gm
      real(kind=dp)              , intent(in)   :: semiaxe,eccent,gamma,gomega,pomega,anom
      real(kind=dp), dimension(3), intent(out)  :: pos, vit

      real(kind=dp), dimension(3)               :: pos1, pos2, vit1, vit2
      real(kind=dp)                             :: xk, xn, e2, anex, rsura,anov, ce, se, ca, sa
            
!******************************************************
!
!     Kepler equation
!           
      xk = sqrt(gm)
      xn = xk / semiaxe / sqrt(semiaxe)            !radians per unit of time
      e2 = eccent*eccent
      call kepler(eccent, anom, anex, rsura, anov,ce,se,ca,sa)

!
!     position and velocity vectors in the orbit
!
      
      pos(1) = semiaxe * rsura * ca
      pos(2) = semiaxe * rsura * sa
      pos(3) = 0

      vit(1) = -xn * semiaxe * se / rsura
      vit(2) =  xn * semiaxe * sqrt((1d0-eccent)*(1d0+eccent)) * ce / rsura
      vit(3) = 0
!
!     position and velocity vector in the reference axes
!
      call rota(pos,  -pomega,3,pos1)
      call rota(pos1, -gamma, 1,pos2)
      call rota(pos2, -gomega,3,pos)

      call rota(vit,  -pomega,3,vit1)
      call rota(vit1, -gamma, 1,vit2)
      call rota(vit2, -gomega,3,vit)

      return
      end  subroutine oscar
!************************************************************************
      subroutine posvit(gm,semiaxe,eccent,anom,pos_0,vit_0, pos_1, vit_1)
!************************************************************************
!
! propagation on a keplerian orbit  from periastron to any other time
! algorithm optimized for ephemeris computation
! no trig lines involved (except in kepler equation)
! the reference frame is arbitrary and could be different from the
! reference system used to give the orbital elements
!
! See lecture notes of F. Mignard for the expressions
!
! The units are set by the choice of gm
!
! Solar system motion :
! AU, AU/day   with  gm = k^2  (k = Gauss constant)
! k = 0.01720209895, gm = 2.9591220829e-4 
! au, au/year si gm =4pi^2  
!
! Earth satellites
! km, km/s  with  gm =398600.44 
!
! angular units  : degrees
!
! Author      : F. Mignard OCA/CERGA
!
!*** INPUT
!
!    gm       : gravitational constant
!    semiaxe  : semi major axis
!    eccent   : eccentricity
!    anom     : mean anomaly in degrees
!    pos_0    : initial position vector at periastron
!    vit_0    : initial velocity vector at periastron
!
!*** OUTPUT
!
!    pos_1    : final position vector at t_1
!    vit_1    : final velocity vector at t_1
!
!
!******************************************************
!
      implicit none

      real(kind=dp)              , intent(in)   :: gm
      real(kind=dp)              , intent(in)   :: semiaxe,eccent,anom
      real(kind=dp), dimension(3), intent(in)   :: pos_0, vit_0
      real(kind=dp), dimension(3), intent(out)  :: pos_1, vit_1

      real(kind=dp)                             :: xk, xn, anex, rsura,anov, ce, se, ca, sa
      real(kind=dp)                             :: ume, f, g, fp, gp 

!******************************************************

!
!     mean motion in rad/ unit of time
!           
      xk = sqrt(gm)
      
      xn = xk / semiaxe / sqrt(semiaxe)

!
!     Kepler equation
!

      call kepler(eccent,anom, anex, rsura, anov,ce,se,ca,sa)

      ume = 1-eccent

      f = (ce-eccent)/ume
      g = ume*se/xn
      
      pos_1 = f*pos_0 + g*vit_0               ! fortran 90

      fp  = -xn*se/(1-eccent*ce)/ume
      gp  =  ce*ume/(1-eccent*ce)

      vit_1 = fp*pos_0 + gp*vit_0             ! fortran 90

      return
      end subroutine posvit
!******************************************************
      subroutine kepler (e, anom, anex, rsura, anov,ce,se, ca, sa)
!******************************************************
!
!
! Solution of the kepler equation
! angles in input and output are in degrees
! Newton-Raphson method with adapted starting point for small M
! Converges in few steps ( < ~ 4) for all M and e <1.
!
! Author      : F. Mignard OCA/CERGA
!
!*** INPUT
!
!    e        : eccentricity  (assumed in 0..1)
!    anom     : mean anomaly in degrees
!
!*** OUTPUT
!
!    anex     : eccentric anomaly in degrees
!    rsura    : r/a
!    anov     : true anomaly in degrees
!    ce       : cos eccentric anomaly
!    se       : sin eccentric anomaly
!    ca       : cos true anomaly
!    sa       : sin true anomaly
! 
!******************************************************
  
      implicit none
  
      real(kind=dp), intent(in)       ::  e, anom
      real(kind=dp), intent(out)      ::  anex, rsura, anov, ce, se, ca, sa
  
      real(kind=dp), parameter        :: petit   = 1d-12

      real(kind=dp)                   :: xm, epsi
      integer                         :: iter

      logical flag

!******************************************************
      xm    =  rad(modulo(anom,round)) ! xm in 0, deupi
      flag  = .false.
      if(xm > pi) then
       xm   = deupi - xm               ! solution for argument in 0 - pi . 
       flag = .true.
      endif
      
      if(xm <0.70*(1-0.85*e)) then     ! what a small M is  depends on e
         anex = xm/(1-0.95*e)          ! optimized from simulations for small M and large e
      else  
         anex = xm + 0.85*e            ! Danby starting value    
      endif
      
      epsi = 1.0
      iter = 0  
      do while ((abs(epsi).gt.petit).and.(iter <10))     ! only 3 to 4 iterations needed in most cases
          ce   = cos(anex)
          se   = sin(anex)
          epsi = (xm + e * se - anex) / (1 - e * ce)
          anex = anex + epsi
          iter = iter +1
      enddo

      if(flag) then                    ! restore  anex  in the correct half circle
         anex  = deupi - anex
      endif
!
!    auxiliary quantities
!
      ce = cos(anex)
      se = sin(anex)

      rsura = 1d0 - e * ce
      ca    = (ce-e)/(1-e*ce)
      sa    = sqrt((1d0-e)*(1d0+e))*se /(1-e*ce)
      anov  = angle(ca, sa)
      
!
!     conversion to degrees
!      
      anex = deg(anex)
      return
      End  subroutine kepler 
!******************************************************
      function xmag_mp(hmag,rearth,rsun,phase)
!******************************************************
!
!
! Apparent magnitude of a minor planet allowing for the phase
! Standard formula applied (see Ann. BDL)
! or Lambert diffusion with phase
!
! units : au,  degrees, magnitude
!
! Author      : F. Mignard OCA/CERGA
!
!*** INPUT
!
!    hmag     : absolute magnitude at 1 au from the sun and 1 au from the earth
!    rearth   : distance to the earth in au
!    rsun     : distance to the sun in au
!    phase    : phase angle in degrees
!
!*** OUTPUT
!
!    xmag_mp  : apparent magnitude
!
!******************************************************
      implicit none

      real   , parameter :: xpi= 3.141592
      real   , parameter :: g  = 0.15
      real   , parameter :: a1 = 3.33
      real   , parameter :: a2 = 1.87
      real   , parameter :: b1 = 0.63
      real   , parameter :: b2 = 1.22

      real(kind=dp), intent(in)     :: hmag,rearth,rsun,phase
      real(kind=dp)                 :: xmag_mp

      real(kind=dp)                 :: xmag, tphas, phi1, phi2
 
!******************************************************

      xmag   = hmag +5d0*log10(rearth*rsun)

      tphas  = tand(0.5d0*phase)
      phi1   = exp(-a1*(tphas)**b1)
      phi2   = exp(-a2*(tphas)**b2)

!    
!     Bowell
!
      xmag   = xmag -2.5d0* log10((1d0-g)*phi1+g*phi2)
!
!     Lambert
!
!     xmag    = xmag -2.5d0*log10((sind(phase)+cosd(phase)*(xpi-rad(phase)))/xpi)

      xmag_mp = xmag
      return
      end   function xmag_mp
!******************************************************
      subroutine sun(xjd,xlong,dis, pos,vit)
!******************************************************
!     Low precision solar coordinates  for 1980 - 2020
!     Simplified implementation for simulation work.
!     accuracy  = 0.005 deg
!     Frame   : ecliptic  equinox J2000
!     check 'parameter' for mean equinox of date
!     geometric longitude (remove aberration (0.0056932 deg) for apparent longitude)
!     
!
!     author F. Mignard OCA/CERGA
!
!***  INPUT
!
!      xjd   : date in julian day
!
!***  OUTPUT 
!
!      xlong : longitude of the sun in degrees
!      dis   : earth - sun distance in au
!      pos   : position vector (pos(3))   in au
!      vit   : velocity vector of the sun (vit(3)) in au/day
!******************************************************

! 
!******************************************************
!
      implicit none
!*****************************************************************************
!
!   Parameters
!
      real(kind=dp), parameter  ::   xl_0     =   280.4665d0        ! mean geometric long at J2000
      real(kind=dp), parameter  ::   xl_1     = 0.98560903d0        ! dl/dt in deg/day
      real(kind=dp), parameter  ::   xm_0     =    357.529d0        ! mean anomaly at J2000
      real(kind=dp), parameter  ::   xm_1     = 0.98560020d0        ! dM/dt in deg/day
      real(kind=dp), parameter  ::   xe       =    0.01671d0        ! e
      real(kind=dp), parameter  ::   xe2      = 0.00013964d0        ! e^2/2
      real(kind=dp), parameter  ::   xed_1    =     1.9148d0        ! 2e in deg
      real(kind=dp), parameter  ::   xed_2    =     0.0200d0        ! 5e^2/4 in deg
      real(kind=dp), parameter  ::   v_0      =   0.017203d0        ! mean speed of the earth in au/day


!*****************************************************************************
!
!   Variables
!

      real(kind=dp)  xjd, xlong, dis, pos(3), vit(3)
      real(kind=dp)  xl, xm, sm, cm, cl, sl

!*****************************************************************************

      xl = xl_0 + xl_1*(xjd-xjd2000)                    ! mean longitude
      xm = xm_0 + xm_1*(xjd-xjd2000)                    ! mean anomaly


      sm = sind(xm)
      cm = cosd(xm)

      xlong    = xl + sm*(xed_1 + 2*xed_2*cm)           ! longitude to O(e^3)
      xlong    = modulo(xlong, round) 

      dis   =  1 + xe2 - xe*cm - xe2*(cm*cm-sm*sm)

      cl     = cosd(xlong)
      sl     = sind(xlong)

      pos(1) = dis*cl
      pos(2) = dis*sl
      pos(3) = 0

      vit(1) = v_0*(xe*sm*cl - sl/dis)                  ! to O(e^2)
      vit(2) = v_0*(xe*sm*sl + cl/dis)
      vit(3) = 0d0

      return
      end    subroutine sun  
!***************************************************************
      subroutine  parabolic (t1,t2,t3,pos1,pos2,pos3,aa,bb,cc)
!***************************************************************
!
!      Parabolic interpolation of a position vector
!      Positions given at t1,t2,t3 as pos1(t1), pos2(t2), pos3(t3)
!      The program returns  the newtonian form :
!      pos(t) = a + b(t-t1) + c/2(t-1)(t-t2)
!      This a direction vectorial interpolation
!
!      Author  : F. Mignard   March 2001, August 2005
!
!******************************************************
!
!***  INPUT
!
!      t1         :independant variables at t1
!      t2         :independant variables at t2
!      t3         :independant variables at t3
!      pos1       :position vector at t1
!      pos2       :position vector at t2
!      pos3       :position vector at t3
! 
!***  OUTPUT       pos(t) = aa + bb(t-t1) + cc/2(t-t1)(t-t2)
!
!      aa         : first divided difference  aa(3) (aa = pos1)
!      bb         : second divided difference bb(3)
!      cc         : third divided difference  cc(3)
!
!******************************************************

      implicit none

      real(kind=dp),    intent(in)    :: t1, t2, t3
      real(kind=dp),    intent(in)    :: pos1(3),pos2(3),pos3(3)
      real(kind=dp),    intent(out)   :: aa(3), bb(3), cc(3)

      real(kind=dp)                   :: coef

!******************************************************

      aa =  pos1
      bb = (pos2-pos1)/(t2-t1)

      coef = 2d0/((t3-t1)*(t3-t2))
      cc   = coef*(pos3-pos1 - (t3-t1)*bb)
      
      return
      end subroutine  parabolic 
!************************************************************************
      subroutine  mindist(t1,t2,t3,pos1,pos2,pos3,tau,dmin,speed,flag)
!************************************************************************
!
!      Minimum distance to the origin of a trajectory interpolated
!      by a second degree polynomial.
!      Positions given at t1,t2,t3 as pos1(t1), pos2(t2), pos3(t3)
!      The program returns  the minimum distance to the origin and the time :
!      if dmin is reached over  [t1:t3] tmin is given with the distance
!      if dmin is found outside  [t1:t3] the closest of the two extreme points is given
!
!      Author  : F. Mignard   March 2001, August 2005
!
!******************************************************
!
!***  INPUT
!
!      t1         : independant variables at t1
!      t2         : independant variables at t2
!      t3         : independant variables at t3
!      pos1       : position vector at t1
!      pos2       : position vector at t2
!      pos3       : position vector at t3
! 
!***  OUTPUT        
!
!      tau        : value of t at dmin
!      dmin       : minimal value of pos(tau)
!      speed      : velocity (modulus) at minimum distance
!      flag       : true if tau is within [t1:t3] and extremum is a minimum ;  otherwise false
!
!******************************************************

      implicit none


      real(kind=dp),    intent(in)    :: t1, t2, t3
      real(kind=dp),    intent(in)    :: pos1(3),pos2(3),pos3(3)
      real(kind=dp),    intent(out)   :: tau, dmin, speed
      logical,          intent(out)   :: flag 
     

      real(kind=dp),    dimension(3)  :: u, v, g 
      integer                         :: iret                 

      logical                         :: flagmin
!******************************************************
!
!     interpolation over three positions
!
      call parabolic (t1,t2,t3,pos1,pos2,pos3,u,v,g)

!
!     here :: pos(t) = u +v(t-t1) +g/2(t-t1)(t-t2)
!
!     shift to obtain the polynomial in standard form - origin at t1

      v =  v - 0.5d0*(t2-t1)*g

!
!     now :: pos(t) =  u + v(t-t1) + g/2(t-t1)^2
!
      call minparab (u,v,g,t1,t3,tau,dmin,speed,flagmin,iret)
!
!     return to the initial time origin used in the call
!
      tau = t1 + tau
!
!     Solution with a minimum within the interval of time used in the interpolation
!
      if( (tau > min(t1,t2,t3)).and.(tau < max(t1,t2,t3)).and.(iret ==0).and.(flagmin))then
          flag = .true.
      else
          flag = .false.
      endif 

      return
      end  subroutine  mindist
!************************************************************************
      subroutine  minparab (u,v,g,tbeg,tend,tau,dmin,speed,flagmin,iret)
!************************************************************************
!
!      Minimum distance to the origin of a trajectory interpolated
!      by a second degree polynomial between tbeg and tend
!      r(t) = u + v*t + g/2*t^2
!      r,u,v,g  are 3D vectors
!
!      Author  : F. Mignard   March 2001, August 2005
!
!******************************************************
!
!***  INPUT
!
!      u         : first vector of the interpolation
!      v         : second vector of the interpolation
!      g         : third vector of the interpolation
!      tbeg      : start time
!      tend      : end time

!***  OUTPUT       
!
!      tau       : value of t at dmin
!      dmin      : min or max value of r(tau)
!      speed     : velocity at min distance
!      flagmin   : true if minimum ; false if maximum
!      iret      : return code (0 : normal, -1 : no minimum found in the interval tbeg, tend)
!
!************************************************************

      implicit none


      real(kind=dp),    intent(in)    :: u(3),v(3),g(3)
      real(kind=dp),    intent(in)    :: tbeg, tend

      real(kind=dp),    intent(out)   :: tau, dmin, speed
      logical,          intent(out)   :: flagmin 
      integer,          intent(out)   :: iret                 
    

      real(kind=dp),    dimension(3)  :: gg, w, pos
 
      real(kind=dp)                   :: ug, v2, uv, deltap, step, deltat, xtau
      real(kind=dp)                   :: w2, rg
      integer                         :: k, iter


      logical                         :: flag

      real(kind=dp),    parameter     :: petit   = 1d-6
      integer      ,    parameter     :: itermax = 6  ! max number of iteration in Newton-Raphson
      integer      ,    parameter     :: npas    = 6 
!*************************************************************


      ug  = u(1)*g(1)+u(2)*g(2)+u(3)*g(3)
      v2  = v(1)*v(1)+v(2)*v(2)+v(3)*v(3)
      uv  = u(1)*v(1)+u(2)*v(2)+u(3)*v(3)
      gg  = 0.5d0*g

!
!     Approximate location of the minimum distance between tbeg and tend
!
      deltap = uv
      k = 0
      flag = .false.
      step = (tend-tbeg)/npas
      do while ((.not. flag).and.(k<npas)) 
           k= k+1
           xtau  =  k*step
           pos   =  u + xtau*(v +xtau*gg)
           w     =  v + xtau*g
           deltat =  pos(1)*w(1)+pos(2)*w(2)+pos(3)*w(3)
           if((deltat*deltap) <0) then            ! a min or max is within tbeg-tend
              tau = xtau- 0.5*step                
              flag = .true.                       ! minimum bracketed between tbeg and tend
           endif
           deltap = deltat
      enddo

      deltat = 1d0
      iter   = 0  

!     remark : if flag =.false.  ==> there is no minimum of distance between tbeg and tend. 
!              then the next block of precise search is not activated
!
!     Newton-Raphson loop  for the solution in t of pos(t). d(pos(t))/dt = 0
!
      if(flag) then                             ! a min or max is within tbeg-tend
          
         do while ((abs(deltat).gt.petit).and.(iter <itermax))     ! only 3 to 4 iterations needed in most cases
            pos    =  u +tau*(v +tau*gg)
            w      =  v +tau*g
            w2     =  w(1)*w(1) +w(2)*w(2)+w(3)*w(3)
            rg     =  pos(1)*g(1)+pos(2)*g(2)+pos(3)*g(3)
            deltat =  pos(1)*w(1)+pos(2)*w(2)+pos(3)*w(3)
            deltat =  deltat/(w2+rg)
            tau    =  tau - deltat
            iter   =  iter +1
         enddo

         pos    =  u +tau*(v + tau*gg)
         dmin   =  sqrt(dot_product(pos,pos))
         speed  =  sqrt(w2)

         if (iter <itermax) then 
            iret =  0
         else
            iret = -1
         endif
      !
      !     minimum or maximum : r" >0 ==> minimum
      !
         if((w2+rg)>0) then 
            flagmin = .true.
         else
            flagmin = .false.
         endif
      else
         iret = -1
      endif 

      return
      end subroutine  minparab
!****************************************************
      subroutine walmax(x0,x1,x2,y0,y1,y2,xmax,ymax)
!****************************************************
!
!!    The program returns the abscissa of the max (or min) of y(x)
!!    and the max (or min) of y(x) 
!!    from a three point parabolic interpolation
!!    The three abscissae need not be regularly spaced or ordered
!!    
!!
!******************************************************
!
!***  INPUT
!*AUT     F. Mignard OCA/CERGA
!*VER     Version 2, December 1999
!
!*INPUT
!
!         x0,x1,x2   : The three abscissae  (order irrelevant)
!         y0,y1,y2   : The corresponding values of y(x)
!
!*OUTPUT
!
!         xmax  : Abscissa of the max (or min) of y(x) from parabolic interpolation
!         ymax  : The max (or min) of y(x) from parabolic interpolation
!!
!*EXTERNAL
!           no external called
!!
!******************************************************
!
      implicit none


      real(kind=dp),    intent(in)    :: x0, x1, x2
      real(kind=dp),    intent(in)    :: y0, y1, y2

      real(kind=dp),    intent(out)   :: xmax, ymax

      real(kind=dp)                   :: xx0, xx2, yy0, yy2

!******************************************************
!
!!    Shift of the origin of abscissae and ordinates
!      
      xx0 = x0-x1
      xx2 = x2-x1

      yy0 = y0-y1
      yy2 = y2-y1

      xmax = x1 + 0.5d0*(xx2**2*yy0-xx0**2*yy2)/(xx2*yy0-xx0*yy2)
      ymax = y1 + 0.5d0*(xx2**2*yy0-xx0**2*yy2)/(xx2**2*xx0-xx0**2*xx2)*(xmax-x1)
      return
      end subroutine walmax
!******************************************************
      SUBROUTINE valmax(x0,x1,x2,y0,y1,y2,xmax,ymax)
!******************************************************
!
!
!!    The program returns the abscissa of the max (or min) of y(x)
!!    and the max (or min) of y(x) 
!!    from a three point parabolic interpolation
!!    The three abscissae need not be regularly spaced or ordered
!!    Interpolation as y(x) = a +b(x-x0) +c/2(x-x0)(x-x1)
!!    a= y0 ; b = (y1-y0)/(x1-x0), c = (y2-y0-b(x2-x0))/((x2-x0)(x2-x1))
!!    
!!
!
!*AUT     F. Mignard OCA/CERGA
!*VER     Version 3, March 2001
!
!*INPUT
!
!         x0,x1,x2   : The three abscissae  (order irrelevant)
!         y0,y1,y2   : The corresponding values of y(x)
!
!*OUTPUT
!
!         xmax  : Abscissa of the max (or min) of y(x) from parabolic interpolation
!         ymax  : The max (or min) of y(x) from parabolic interpolation
!!
!*EXTERNAL
!           no external called
!********************************************************************************
      implicit none


      real(kind=dp),    intent(in)    :: x0, x1, x2
      real(kind=dp),    intent(in)    :: y0, y1, y2

      real(kind=dp),    intent(out)   :: xmax, ymax

      real(kind=dp)                   :: xx1, xx2, xx21,  yy1, yy2, b, c

!********************************************************************************
!
!!    Shift of the origin of abscissae and ordinates
!      
      xx1  = x1-x0
      xx2  = x2-x0
      xx21 = x2-x1

      yy1 = y1-y0
      yy2 = y2-y0

      b   = yy1/xx1
      c   = 2*(yy2-b*xx2)/(xx2*xx21)

      xmax =  -b/c + 0.5*(x0+x1)
      ymax =  y0 +(xmax-x0)*(b+0.5*c*(xmax-x1))

      return
      end SUBROUTINE valmax
!******************************
      function xnorm(vect)
!******************************
!
!     return the  norm of a  vector vect
!
      implicit none

       
      real(kind=dp),    intent(in)    :: vect(3)

      real(kind=dp)                   :: xnorm


      xnorm = sqrt(dot_product(vect,vect))

      return
      end  function xnorm
!**************************************************************************
      function seconds(x)
!**************************************************************************
!     This function returns the elapsed time since the time x
!     x : number of seconds since 0h in the system clock
!     seconds(0.0d0) : number of seconds elapsed since 0h of the system clock
!     accuracy : 0.001 s
!
!     F. Mignard  OCA/Cassiopee
!
!     INPUT
!        x     : time offset since 0h in seconds
!
!     OUTPUT
!     seconds  : elapsed time since x in seconds
!
!***************************************************************************
      implicit none

      integer,   dimension(8)   :: ivalues
      real(kind=dp)             :: seconds, x

      call date_and_time(values=ivalues)

      seconds = 3600d0*ivalues(5)+60d0*ivalues(6)+ivalues(7) +0.001d0*ivalues(8) - x

      return
      end function seconds
!******************************************************
      function obliquity(datjd)
!******************************************************
!
!     Obliquity of the ecliptic at the JD date datjd
!     unit  : degrees
!     F. Mignard  August 2001
!
!     INPUT
!        datjd     : date in julian days
!
!     OUTPUT
!        obliquity : mean obliquity in degrees at datjd
!******************************************************
!
!      use constantes

!      use  sergelib   ! changed for N. Rambaux  17/10/06 but not tested  FM

      implicit none

      real(kind = dp), intent(in)    :: datjd
      real(kind = dp)                :: obliquity 
      real(kind = dp)                :: t

      t = (datjd - (xjd2000 )) / century    ! parameters  referered to J2000

!      obliquity =  84381.410d0/3600d0 -(46.80956*t + 0.000152*t*t+0.0019989*t*t*t)/3600d0
!      obliquity =  84381.4118988d0/3600d0 -( 46.80972*t + 0.001998*t*t*t)/3600d0  ! used in the ephemeride version to LL for GAIA only (not the planets)

      obliquity =  84381.4119d0/3600d0 -(46.80956*t + 0.000152*t*t+0.0019989*t*t*t)/3600d0   !used for the GAIA Chebyshev

      return
      end function obliquity

!******************************************************
      subroutine equtoecl(datjd, poseq, posecl)
!******************************************************
!
!    Transformation of a vector from the equatorial frame to the ecliptic frame
!
!  Author  : F. Mignard OCA/CERGA
!
!
!*** INPUT
!       datjd   : JD of the date (used to compute the obliquity)
!       poseq   : input vector in equatorial frame
!
!*** OUTPUT
!       posecl  : output vector in ecliptic frame
!
!******************************************************
!

      implicit none
      real(kind = dp), parameter                  :: phi = 0.05542d0  !Chapront et al. 2002 gamma to O_icrs in arcsec

      real(kind = dp), dimension(3), intent(inout) :: poseq 
      real(kind = dp), dimension(3), intent(out)   :: posecl

      real(kind = dp)                             :: epsilon, datjd,phid

      phid    = phi/3600d0
 
      epsilon = obliquity(datjd)

      call rota(poseq,-phid,3,poseq)

      call rota(poseq,epsilon,1,posecl)

      return
      end  subroutine equtoecl
!******************************************************
      subroutine ecltoequ(datjd, posecl, poseq)
!******************************************************
!
!    Transformation of a vector from the ecliptic frame to the equatorial frame
!
!  Author  : F. Mignard OCA/CERGA
!
!
!*** INPUT
!       datjd   : JD of the date (used to compute the obliquity)
!       poseq   : input vector in ecliptic frame
!
!*** OUTPUT
!       posecl  : output vector in equatorial frame
!
!******************************************************
!

      implicit none
      real(kind = dp), parameter :: phi = 0.05542d0  !Chapront et al. 2002 gamma to O_icrs in arcsec

      real(kind = dp), dimension(3), intent(in)   :: posecl 
      real(kind = dp), dimension(3), intent(out)  :: poseq

      real(kind = dp)                             :: epsilon, datjd, phid

      phid    = phi/3600d0
      epsilon = obliquity(datjd)

      call rota(posecl,-epsilon,1,poseq)

      call rota(poseq,phid,3,poseq)                  ! not include this statement for the  version 2003 and 2004 of ephemeris for GAIA

      return
      end subroutine ecltoequ

 end module approachlib
