
      Program close_approaches
      use approachlib                  !module with constants and procedures

!      use planetes
!      use constantes                  !module with constants
!     **************************************************************
!      This program searches the close approaches between asteroids.
!     It starts from a list of orbital elements at a given epoch and 
!     follows the motion between two epochs. Distances are determined and 
!     the minimums are located for every pair selected.
!
!     F. Mignard  March     2001  V1
!                 September 2002  V2 with dynamical allocation
!                 May       2003  V3 with filtering on the perturber mass
!                 August    2005  V4 F77==> F90 + module with subroutines
!                 May       2007  V5 numerical integration of the orbits
!                 February  2014  Stand-alone with a single fortran module
!            
!
!     Method : For a given pair of planets one fits the relative motion 
!     over 50 days to a 3D parabolic motion (in vector form). For each interval
!     one computes the maximum and minimum distance with this approximated path.
!     If a minimum is found and if it lies in the period of 50 days under consideration
!     the minimum is output for further investigation.
!
!     The core of the progam is the routine mindist which makes the interpolation
!     and searches the minimum.
!     
!
!     Planets are selected as being perturbers (the big ones) or perturbed (the small ones)
!     
!     There are two modes to run the program :
!
!     a - propagation of position with a 2 body problem from osculating elements
!     b - full numerical integration with the major perturbations of the planets
!    
!     a : good for systematic explorations of thousands of planets . Very fast
!     b : to refine or confirm some close approaches. Runs rather slowly 
!
!     In practice, 2 body problem is very good over 10 years and locate properly the close
!     approaches even over 50 years.  The geometry of the approach is not very sensitive to
!     the orbital perturbation contrarily to the timing. Date may be wrong by  several days
!     when osculating elements are used over 10 years instead of numerical integration. 
!
!     For each close approach selected, one determines the relative speed, the angular deflection
!     using the impulse model, and some other astrometric signaturew which aim to measure the 
!     efficiency of the encounter.
!           
!     **************************************************************
!
      implicit none
!
!     General settings 
!
      real(kind=dp),    parameter    :: step   = 50d0        ! step in days to interpolate the asteroid orbits. Do not change

!     Period of time where closest approaches are searched

      real(kind=dp),    parameter    :: tbeg   = 2013.5d0    ! starting date of the exploration
      real(kind=dp),    parameter    :: tend   = 2020.0d0    ! final date of the exploration
      real(kind=dp),    parameter    :: tref   = 2000.0d0    ! origin of time (epoch  in years) inside the program to refer dates
      real(kind=dp),    parameter    :: xjdref = xjd2000 + (tref-2000.0d0)*year    ! origin of time (epoch  in JD) inside the program to refer dates


!     input file with the osculating elements  :  must agree with the interval tbeg - tend. No check in the program
!
      character*20,     parameter    :: fichin =  'oscul_aster_2012.txt' ! assumes file available in the same directory as the project
      
!
!     Units for input and ouput files
!
      integer,          parameter    :: idat   = 10          ! unit of the file with osculating elements
      integer,          parameter    :: iout   = 11          ! unit of the output file
      integer,          parameter    :: inear  = 12          ! unit of the output file
      integer,          parameter    :: istat  = 13          ! unit of the stat output file
!
!     Exploitation settings to determine the number of deflectors and perturbers
!     This must be adapted to each run
!
      integer,          parameter    :: nbig_0 = 1           ! first deflector
!      integer,          parameter    :: nbig_1 = 5000        ! last deflector
      integer,          parameter    :: nbig_1 = 500         ! last deflector : testing for delivery to Pedro
      integer,          parameter    :: nall_0 = 1           ! first perturbed
 !     integer,          parameter    :: nall_1 = 300000        ! last perturbed 
      integer,          parameter    :: nall_1 = 3000        ! last perturbed : testing for delivery to Pedro
      integer,          parameter    :: nall   = max(nall_1,nbig_1)! max size of the main arrays

!
!     Setting to define and select useful close approaches 
!
      real(kind=dp)   , parameter    :: dlim   = 0.50d0      ! close approaches considered only if dmin < dlim  in au
      real(kind=dp)   , parameter    :: veryclose = 0.10d0   ! close approaches considered only if dmin < dlim  in au
      real(kind=dp)   , parameter    :: tetlim = 1.0d0       ! min deflection in mas to be selected in the output
      real(kind=dp)   , parameter    :: xmass_l= 0.2d-13     ! minimum mass of a pertuber for the output
      real(kind=dp)   , parameter    :: hmaglim= 18.5d0      ! maximum absolute mag for an observation by Gaia
      real(kind=dp)   , parameter    :: xmaglim= 21.0d0      ! maximum of an observation by Gaia
      real(kind=dp)   , parameter    :: astrom = 3.0d0       ! astrometric threshold in mas to select a close approach
      real(kind=dp)   , parameter    :: shiftlim = 10.0d0    ! shift between perturbed and unperturbed motion large than shiftlim to be selected as an efficient approach

!     the program may use numerical integration for accurate (but slower) determination
!     this option is disabled in this version. Imode = 1 should be kept as the integrator is not
!     included in the library. (FM 11/02/2014)
!
      integer,          parameter    :: imode  =1           ! imode = 1 :: osculating elements ; 2 :: integration


!
!     various settings for the output of statistical results.
!
      real(kind=dp)   , parameter    :: xd1    = 0.5d0       ! 1st bin of min dist for the statistics (au)
      real(kind=dp)   , parameter    :: xd2    = 0.2d0       ! 1st bin of min dist for the statistics
      real(kind=dp)   , parameter    :: xd3    = 0.1d0       ! 1st bin of min dist for the statistics
      real(kind=dp)   , parameter    :: xd4    = 0.05d0      ! 2nd bin of min dist for the statistics
      real(kind=dp)   , parameter    :: xd5    = 0.02d0      ! 3rd bin of min dist for the statistics
      real(kind=dp)   , parameter    :: xd6    = 0.01d0      ! 4th bin of min dist for the statistics
      real(kind=dp)   , parameter    :: xt1    = 2.0d0       ! 1st bin of deflection for the statistics (mas)
      real(kind=dp)   , parameter    :: xt2    = 5.0d0       ! 1st bin of deflection for the statistics
      real(kind=dp)   , parameter    :: xt3    = 10.0d0      ! 2nd bin of deflection for the statistics
      real(kind=dp)   , parameter    :: xt4    = 50.0d0      ! 3rd bin of deflection for the statistics
      real(kind=dp)   , parameter    :: xt5    = 100.0d0     ! 4th bin of deflection for the statistics
      real(kind=dp)   , parameter    :: xt6    = 200.0d0     ! 4th bin of deflection for the statistics

      real(kind=dp)   , parameter    :: binwidth = 30.0      ! number of day per bin to generate the rate of close approaches
!
!     Variables used in the program
!
      real(kind=dp), dimension(3) :: pos1, pos2, pos3,pos 
      real(kind=dp), dimension(3) :: qos1, qos2
      real(kind=dp), dimension(3) :: vit1,vit2,vitr,vit
      real(kind=dp), dimension(3) :: v_unit, dvit1,dvit2
      character*15                :: name(nall)
      character*10                :: nature

      real(kind=dp)               ::  semi(nall) , eccent(nall),anom(nall),xn(nall),hmag(nall)
      real(kind=dp)               ::  gamma(nall), gomega(nall),pomega(nall)
      real(kind=dp)               ::  xmass(nall)
      real(kind=dp)               ::  pos_ini(3,nall),vit_ini(3,nall)
      integer                     ::  numdist(nbig_1 - nbig_0 + 1,10) = 0, numteta(nbig_1 - nbig_0 + 1,10) = 0
      integer                     ::  numclose(nbig_1 - nbig_0 + 1)= 0, num_per_bin(floor( (tend-tbeg)*year/binwidth)+1)=0

      real(kind=dp), allocatable  ::  pos_t(:,:,:), vit_t(:,:,:) 
      integer, allocatable        ::  nummer(:)
      real(kind=dp)               ::  deb, epochp, radius,  xdays_0, tdeb
      real(kind=dp)               ::  xjd, xjd_0, xdays1, xdays2, xdays3,  danom, dist, dist1, dist2
      real(kind=dp)               ::  ttau, dmin, velocity, speed, dteta, tt
      real(kind=dp)               ::  xlong, dis, delta1, delta2, xphase1, xphase2, xmag1, xmag2 
      real(kind=dp)               ::  xmass_t, dteta1, dteta2, dur, rho, xlongu, xbetu, xlongp, xbetp, shift1, shift2
      real(kind=dp)               ::  aa1, ee1, gg1, gom1, pom1, xanom1, xnn1, day
      real(kind=dp)               ::  aa2, ee2, gg2, gom2, pom2, xanom2, xnn2, xanom

      integer                     ::  ival(8)
      integer                     ::  nstep, nsize, icase, kast, iast, nmin, ir, ibin, ibmax
      integer                     ::  i, k, l, kast1, kast2, iast1, iast2, iyear, imonth

      logical                     ::  flag, flfar, first

!

! end of declarations
!******************************************************************************************
!
!     input data with the osculating elements
!
      open(idat, file=fichin,form='formatted',status = 'old')
!
!     output file
!
      open(unit=iout,  file = 'resdist.txt', status = 'unknown')
      open(unit=inear, file = 'resnear.txt', status = 'unknown')
      open(unit=istat, file = 'resstat.txt', status = 'unknown')
!
!     housekeeping info for the output
!
      call date_and_time(VALUES = ival)
      write(iout,45)
      write(iout,47)   ival(3),ival(2),ival(1), ival(5), ival(6),ival(7)
      write(iout,45)

!
!     output of the program settings
!
      write(iout,60)   tbeg, tend
      write(iout,62)   dlim, tetlim
      write(iout,63)   astrom
      write(iout,631)  shiftlim
      write(iout,64)   xmass_l
      write(iout,66)   nbig_0, nbig_1
      write(iout,68)   nall_0, nall_1

      write(inear,45)
      write(inear,47)   ival(3),ival(2),ival(1), ival(5), ival(6),ival(7)
      write(inear,45)

!
!     output of the program settings
!
      write(inear,60)   tbeg, tend
      write(inear,62)   dlim, tetlim
      write(inear,63)    astrom
      write(inear,64)   xmass_l
      write(inear,66)   nbig_0, nbig_1
      write(inear,68)   nall_0, nall_1

      write(inear,*)
      write(inear,*)
      write(inear,250)

      deb = seconds(0d0)
      read(10,*)         ! header of the input file
      read(10,*) epochp  ! epoch in JD for the osculating elements
 
!
!     number of steps in the exploration
! 
      nstep = (tend-tbeg)*year/step
      
!
!     number of different asteroids in the shopping list
!
      if(nbig_1 < nall_0) then
          nsize = nbig_1 - nbig_0 + nall_1 - nall_0 + 2
          icase = 1
      else
          nsize = nall_1 - nbig_0 + 1
          icase = 2
      endif
      allocate(pos_t(3,2*nstep+1,nsize),vit_t(3,2*nstep+1,nsize))
      allocate(nummer(nsize))                     ! this array contains the IDs of the nsize asteroids
 !     allocate(idast(nsize))

      print *,  'nsize :  ', nsize
!
!     array for the indirect addressing of asteroids
!
      do kast = 1, nsize
         if(icase == 1) then      ! non overlapping sets  of asteroids
              if(iast < nbig_1) then
                  iast = nbig_0 - 1 + kast
              else
                  iast = nbig_0 -1 + kast + nall_0 - nbig_1 - 1
              endif
         elseif(icase ==2) then   ! sets overlap
              iast =   nbig_0 -1 + kast 
         endif
 !        nummer(kast) = iast      ! id of the kast_th asteroid
      enddo

      nmin   = min(nbig_0,nall_0)!

!**********************************************************************
!     reading the orbital data
!
ir = 0
10    continue
         ir = ir+1
         read(10, *, end = 1000) nummer(ir), semi(ir), eccent(ir), gamma(ir), gomega(ir), pomega(ir), anom(ir), hmag(ir),&
         radius, xmass(ir), name(ir)
         xn(ir) = raddeg*(sqrt(gm)/semi(ir) /sqrt(semi(ir)))
         if(imode==1) then   ! Keplerian motion
            call oscar(gm,semi(ir),eccent(ir),gamma(ir), gomega(ir), pomega(ir),&
                   0d0,pos_ini(:,ir), vit_ini(:,ir))
         else                ! position and velocity at epoch for numerical integration
            call oscar(gm,semi(ir),eccent(ir),gamma(ir), gomega(ir), pomega(ir),&
                   anom(ir),pos_ini(:,ir), vit_ini(:,ir))
         endif

         if(ir >= nall) go to 1000                                   ! comment to read all the records
         go to 10
1000  continue
      close(10)              ! closing link to input file
      print *,  'end reading orbital data'
 !     print *, ir
!      print *, nummer(1), nummer(10), nummer(ir-1)
!      stop
    
!
!**********************************************************************
!     computation of the positions and velocity of the asteroids over the period of exploration
!     this is done once for all and requires important memory storage
!     parabolic interpolation needs three points per time step 
!
      xjd_0 =   xjdref + (tbeg-tref)*year 
      do kast = 1, nsize
 !        iast = nummer(kast)
         iast = kast
         if(hmag(iast) < hmaglim) then       ! skip very faint targets not obervable by Gaia
         pos1 = pos_ini(:,iast)
         vit1 = vit_ini(:,iast)
         tdeb = epochp  ! in JD
         if(modulo(kast,100)==0) print *, 'iast =', iast
         do i = 1 , 2*nstep+1
            xjd    = xjd_0 + (i-1)*0.5*step             ! time sampling
            if(imode==1) then                                 
               danom  = xn(iast)*(xjd-epochp) + anom(iast)                       ! mean anomaly at date
               call posvit(gm,semi(iast),eccent(iast),danom,pos_ini(:,iast),vit_ini(:,iast),&
                          pos_t(:,i,kast), vit_t(:,i,kast))
            else
!               write(*,*) ' Numerical integration mode disabled'
!               write(*,*) ' Change imode to 1'
!               write(*,*) ' Program stopped'
!               stop
!               call update_bs(tdeb, pos1, vit1, xjd,pos_t(:,i,kast), vit_t(:,i,kast))
               tdeb = xjd
               pos1 = pos_t(:,i,kast)
               vit1 = vit_t(:,i,kast)
            endif

         enddo
         endif
      enddo
!
!**********************************************************************
!     Start of the 3-D parabolic interpolation
!
      xdays_0 = (tbeg-tref)*year ! in days since the reference epoch
      do kast1 = 1, nbig_1 - nbig_0 + 1
!         iast1 = nummer(kast1)
         iast1 = kast1
         if(xmass(iast1) > xmass_l) then
            print *, 'iast1',  iast1
            flfar = .true.
!           do iast2 = iast1+1, nall                ! this gives (1,2), (1,3) ..., (2,3), (2,4) ...,(3,4).. 
            do kast2 = 1, nsize                     ! this gives (1,2), (1,3) ..., (2,1), (2,3) ..., (3,1), (3,2) ...
!               iast2 = nummer(kast2)
               iast2 = kast2
               if(hmag(iast2) < hmaglim) then       ! skip very faint targets not obervable by Gaia
                  if(kast2 /= kast1) then 
                     do  i = 1, nstep

                        xdays1 = xdays_0 + (i-1)*step                                     ! position at t1
                        pos1 = pos_t(:, 2*i-1,kast2) -  pos_t(:, 2*i-1,kast1) 

                        xdays2 = xdays1  +   step*0.5                                     ! position at t2 = t1+0.5*step
                        pos2 = pos_t(:, 2*i,kast2)   -  pos_t(:, 2*i,kast1) 

                        xdays3 = xdays1  +    step                                        ! position at t3 = t1+step
                        pos3 = pos_t(:, 2*i+1,kast2) -  pos_t(:, 2*i+1,kast1) 

                        call  mindist(xdays1,xdays2,xdays3,pos1,pos2,pos3,ttau,dmin,velocity,flag)  ! search the minimum distance  ttau in days since reference epoch

!
!                  General statistics per deflector
!
                        if (flag) then           !minimum found in [t1, t3]
                           speed = velocity*audtokms                                     ! speed in km/s ; audtokms= 1731 = ua/d to km/s
                           dteta = 35d0*(xmass(iast1)+xmass(iast2))*1e10/dmin/speed**2   ! deflection in mas with dist in au, speed in km/s , m in solar mass
                           if(dmin < xd1)   numdist(iast1,1)  = numdist(iast1,1)+1
                           if(dmin < xd2)   numdist(iast1,2)  = numdist(iast1,2)+1
                           if(dmin < xd3)   numdist(iast1,3)  = numdist(iast1,3)+1
                           if(dmin < xd4)   numdist(iast1,4)  = numdist(iast1,4)+1
                           if(dmin < xd5)   numdist(iast1,5)  = numdist(iast1,5)+1
                           if(dmin < xd6)   numdist(iast1,6)  = numdist(iast1,6)+1

                           if(dmin < dlim ) then
                              if(dteta > xt1)  numteta(iast1,1)  = numteta(iast1,1)+1
                              if(dteta > xt2)  numteta(iast1,2)  = numteta(iast1,2)+1
                              if(dteta > xt3)  numteta(iast1,3)  = numteta(iast1,3)+1
                              if(dteta > xt4)  numteta(iast1,4)  = numteta(iast1,4)+1
                              if(dteta > xt5)  numteta(iast1,5)  = numteta(iast1,5)+1
                              if(dteta > xt6)  numteta(iast1,6)  = numteta(iast1,6)+1
                           endif
                        endif
!
!**********************************************************************
!      flag : true if minimum found in [t1, t3]
!
     
                        if((flag).and.(dteta > tetlim).and.(dmin < dlim)) then        ! dteta >tetlim , dmin < dlim                      
!
!      additional computations for the outptut : distance, speed, deflection ...
!
                           call jd_date(ttau+xjdref, iyear, imonth, day)


                           danom  = xn(iast1)*(ttau+xjdref-epochp) + anom(iast1)                       ! mean anomaly at date
                           call oscar(gm,semi(iast1),eccent(iast1),gamma(iast1), gomega(iast1), pomega(iast1),danom,qos1,vit1)
                                
!                          call posvit(gm,semi(iast1),eccent(iast1),danom,pos_ini(:,iast1),vit_ini(:,iast1), qos1, vit1)

                           danom  = xn(iast2)*(ttau+xjdref-epochp) + anom(iast2)                       ! mean anomaly at date
                           call oscar(gm,semi(iast2),eccent(iast2),gamma(iast2), gomega(iast2), pomega(iast2),danom,qos2,vit2)
                                

!                          call posvit(gm,semi(iast2),eccent(iast2),danom,pos_ini(:,iast2),vit_ini(:,iast2), qos2, vit2)
                           pos3 = qos2-qos1
                           vitr = vit2-vit1
!
!      heliocentric distance
!
                           dist1=  sqrt(dot_product(qos1,qos1))       
                           dist2=  sqrt(dot_product(qos2,qos2))   
!
!      geocentric distance
!    
                           call sun(ttau+xjdref,xlong,dis, pos,vit)
                           delta1 = sqrt(dot_product(pos+qos1,pos+qos1))    
                           delta2 = sqrt(dot_product(pos+qos2,pos+qos2))     
!
!       phase
!
                           xphase1 = deg(acos(dot_product(qos1, pos+qos1)/(delta1*dist1)))
                           xphase2 = deg(acos(dot_product(qos2, pos+qos2)/(delta2*dist2)))

!
!       magnitude
!
                           xmag1 = xmag_mp(hmag(iast1), delta1, dist1,xphase1)
                           xmag2 = xmag_mp(hmag(iast2), delta2, dist2,xphase2)

                           speed = velocity*audtokms                                     ! speed in km/s ; audtokms = 1731.46 = ua/d to km/s
                           dist  = sqrt(dot_product(pos3,pos3))                          ! min distance
                           dteta = 36d0*(xmass(iast1)+xmass(iast2))*1e10/dist/speed**2   ! deflection in mas with dist in au, speed in km/s , m in solar mass
!
!       change in the velocity vector and change of the orbital elements  
!
                           xmass_t = (xmass(iast1)+xmass(iast2))
                           v_unit  = pos3/dist                                            ! unit vector ast1 to ast2
                           dvit1   =   xmass(iast2)/xmass_t*speed*dteta/radmas/audtokms*v_unit   ! velocity vector change of ast1
                           dvit2   = - xmass(iast1)/xmass_t*speed*dteta/radmas/audtokms*v_unit   ! velocity vector change of ast2
                           dteta1  =  xnorm(dvit1)/xnorm(vit1)*radmas                     ! deflection of ast1  in mas
                           dteta2  =  xnorm(dvit2)/xnorm(vit2)*radmas                     ! deflection of ast2  in mas
                           vit1 = vit1 + dvit1
                           vit2 = vit2 + dvit2

!
! Positional propagation after the close approach with or without interaction
!
                           dur = 5d0                                          ! dur in years for the positional propagation with and without perturbation
 
! perturber
                           call carosc(gm,qos1,vit1,aa1,ee1,gg1,gom1,pom1,xanom1)    ! new orbital elements after impulse for iast1
                           xnn1 = raddeg*(sqrt(gm)/aa1 /sqrt(aa1))

                           danom  = xn(iast1)*(dur*year+ttau+xjdref-epochp) + anom(iast1)                       ! mean anomaly at date
                           call oscar(gm,semi(iast1),eccent(iast1),gamma(iast1), gomega(iast1), pomega(iast1),danom,pos, vit)                              

                           call carsphe(pos,rho, xlongu, xbetu)                ! dur years without perturbation
                           xanom = xanom1 + xnn1*year*dur                        ! change over dur years
                           call oscar(gm,aa1,ee1,gg1,gom1,pom1,xanom,pos, vit)
                           call carsphe(pos,rho, xlongp, xbetp)                ! dur years with perturbation

                           shift1 = arc(xbetu,xbetp,xlongu,xlongp)*3.6e6/dur   ! positional difference in mas after dur years with and w/o perturbation
 
! perturbed body
                           call carosc(gm,qos2,vit2,aa2,ee2,gg2,gom2,pom2,xanom2)    ! new orbital elements after impulse for iast2
                           xnn2 = raddeg*(sqrt(gm)/aa2 /sqrt(aa2))

                           danom  = xn(iast2)*(dur*year+ttau+xjdref-epochp) + anom(iast2)                       ! mean anomaly at date
                           call oscar(gm,semi(iast2),eccent(iast2),gamma(iast2), gomega(iast2), pomega(iast2),danom,pos, vit)
                               
                           call carsphe(pos,rho, xlongu, xbetu)                ! dur years without perturbation
                           xanom = xanom2 + xnn2*year*dur                        ! change over dur years
                           call oscar(gm,aa2,ee2,gg2,gom2,pom2,xanom,pos, vit)
                           call carsphe(pos,rho, xlongp, xbetp)                ! dur years with perturbation

                           shift2 = arc(xbetu,xbetp,xlongu,xlongp)*3.6e6/dur   ! positional difference in mas after dur years with and w/o perturbation

!
!      output   :: various testing for acceptance/rejection a feasible. User must adpat.
! 
!                           if(((dteta1 > astrom).or.(dteta2 >astrom)).and.(xmag2<20).and.(dmin<dlim)) then                                                     !deflection > threshold
 !                          if(((dteta1 > astrom).or.(dteta2 >astrom)).and.(xmag2<21)) then        !deflection > threshold
                           if(((shift1 > shiftlim).or.(shift2 >shiftlim)).and.(max(xmag2, xmag1) < xmaglim)) then        !deflection > threshold
 !                          if((dteta2 >astrom).and.(xmag2<21)) then                                                     !deflection > threshold
                              if(flfar) then                                                ! to skip one line between two objects
                                 flfar = .false.
                                 write(iout,*)
                                 write(iout,250)
!                                 write(inear,*)
!                                 write(inear,250)
                              endif
                              if(xmass(iast2) > xmass_l) then
                                 nature   = ' perturber'
                              else
                                 nature   = ' target   ' 
                              endif
                              write(iout,100)  nummer(iast1), name(iast1),  nummer(iast2),name(iast2), nature,&
                              ttau+xjdref, int(day), imonth, iyear, dmin, speed,dteta, dteta1, dteta2, shift1, shift2, xmag1,xmag2

                              if(dmin < veryclose) then
                                 write(inear,100)  nummer(iast1), name(iast1),  nummer(iast2),name(iast2),nature,&
                                 ttau+xjdref, int(day), imonth, iyear, dmin, speed,dteta,  dteta1, dteta2,shift1, shift2,xmag1,xmag2
                              endif
                              numclose(iast1) = numclose(iast1)+1  ! number of close approaches selected per asteroids
                              ibin = (ttau  -(tbeg-tref)*year)/binwidth +1
                              num_per_bin(ibin) =  num_per_bin(ibin) +1

!                              write(iout,150)  iast1, name(iast1), (aa1-semi(iast1))*xau, (ee1-eccent(iast1))*radmas,(gg1-gamma(iast1))*degmas,(gom1-gomega(iast1))*degmas,(pom1-pomega(iast1))*degmas
!                              write(iout,150)  iast2, name(iast2), (aa2-semi(iast2))*xau, (ee2-eccent(iast2))*radmas,(gg2-gamma(iast2))*degmas,(gom2-gomega(iast2))*degmas,(pom2-pomega(iast2))*degmas
                           endif ! astrometrically significant deflection
                        endif    ! d< dlim,  dteta > tetlim
                     enddo       ! loop over the time
                  endif
               endif ! Hmag less than faintest object observable
            enddo    ! loop over perturbed planets
         endif ! mass less than lower mass for perturbing object.
      enddo    ! loop over the perturbers
!
!*********** Main exploration over **************
!***************************************************
!
!     Ouput of the statistics for this run
!
      write(istat, *) '                   Overall  Statistics '
      write(istat, *) '                   ------------------- '


      write(istat, *)
      write(istat, *)
      write(istat, *)' Number of close approaches per planets '
      write(istat, *)

      write(istat,540)       ! statistics for the close approaches
      do k = 1, nbig_1 - nbig_0 + 1
            write(istat,600) k,name(k),semi(k), numclose(k)
      enddo


      write(istat, *)
      write(istat, *)

      write(istat, *) ' Number of close approaches with smallest distance < d_lim  (au) '
      write(istat, *)

      write(istat,550) xd1, xd2,xd3, xd4, xd5,xd6     ! statistics for the smallest distances
      do k = 1, nbig_1 - nbig_0 + 1
         if(numdist(k,1) >0) then 
            write(istat,600) k,name(k),semi(k), (numdist(k,l), l=1,6)
         endif
      enddo

      write(istat, *)
      write(istat, *)
      write(istat, 555) dlim
      write(istat, *)

      write(istat,560) xt1, xt2,xt3, xt4, xt5,xt6     ! statistics for the angular deflections
      do k = 1, nbig_1 - nbig_0 + 1
         if(numteta(k,1)> 0) then
            write(istat,600) k,name(k),semi(k), (numteta(k,l), l=1,6)
         endif
      enddo

      ibmax = floor( (tend-tbeg)*year/binwidth)+1
      write(istat, *)
      write(istat, *)
      write(istat, *)' Time distribution of the close approaches'
      write(istat,'(10x, "bins of", f5.0, "days")') binwidth
      write(istat, *)

 
      do k = 1, ibmax 
            tt = tbeg +(k-0.5)*binwidth/year
            write(istat,610) k,tt, num_per_bin(k)
      enddo


      print * , seconds(deb)
!**************************************************************************************
!
!     Formats
!


45    FORMAT(/,'******************************************* ',/)
47    format( '  Run  made  on  ' , i2.2,'-',I2.2,'-',i4, '  at  ', i2.2,':',i2.2':',i2.2)
60    format(//, ' Starting epoch  :', f10.2,/, ' Final    epoch  :', f10.2)
62    format(/ , ' Close approches  less than :' f6.2, ' au', /, ' Deflection in CDM larger than :' f6.2, ' mas')
63    format(/ , ' Deflection of perturbed planets in  heliocentric frame larger than :' f6.2, ' mas')
631   format(/ , ' Shift after 5 years larger than : ', f6.2, 'mas')
64    format(/ , ' Bodies  larger than    :', e10.2,' M_s')
66    format(/ , ' Deflectors are the planets  :' i4, ' to ', i8)
68    format(    ' Targets    are the planets  :' i4, ' to ', i8,//)
50    format( '  Study of the asteroids '  i5,  ' and '  , i5)
100   format(i5,1x,A12,i8,1x, a12, a10, F13.3,i4.2,'/',i2.2,'/',i4,f9.5, f8.2, 5f10.2,2f6.1 )
150   format(i5,1x,A12,6f10.4)
200   format(3f10.4)
250   format('  id1  name            id2   name      type            JD          date       d_min    V(km/s)   teta      astr1     astr2   shift1   shift2   mag1  mag2')
350   format(2f14.8,2f12.8,2f12.7)
352   format(3f13.9)
355   format(4f10.5 ,f12.4)
500   format(f13.2,3f10.3)
540   format(26x, ' number of Close approaches ',/)
550   format(26x, '   d<',f5.2,'     d<',f5.2,'     d<',f5.2,'     d<',f5.2,'     d<',f5.2,'     d<',f5.2,/)
555   format(' Number of close approaches with deflection  > t_lim (in mas) and  distance < ', f4.1, 'au')
560   format(26x, '  t>',f4.1,'    t>',f4.1,'    t>',f4.1,'    t>',f5.0,'    t>',f5.0,'    t>',f5.0,/)
600   format(i5,1x,a12,F6.2,10(2x,i8,2x))
610   format(i5,1x, f10.2,i8)

!*****************************************************************************************
      end

 