      program NsatInHost

      parameter(MAXHALOS = 1100000)
      parameter(NCOLUMNS = 38)
      parameter(Rfac     = 2.0)
      parameter(xMmin    = 1.e+01)

      real V(NCOLUMNS,MAXHALOS)
      real          BOX, Msat, Mhost, rr, gg, bb
      character*512 cdummy, infile

      write(*,'(A)')
     &'======================================================'
      write(*,'(A)')
     &'  read *_halos and count satellites of specific host'
      write(*,'(A)')
     &'======================================================'

      write(*,'(A,$)')' Please give name of *.AHF_halos file     => '
      read(*,'(A)')infile
      print*,infile(1:80)
      write(*,'(A,$)')' Please give boxsize [Mpc/h]              => '
      read*,BOX
      print*,BOX
      write(*,'(A,$)')' Please give id (C-notation) of host halo => '
      read*,ihost
      print*,ihost
      ! convert to FORTRAN index
      ihost = ihost + 1

      open(11,file=infile)
      open(12,file="new_halos")


      read(11,*)cdummy
      write(12,'(A)')cdummy
      do i=1,MAXHALOS
         read(11,*,end=666)(V(k,i),k=1,NCOLUMNS)
      enddo
 666  nhalos = i-1
      close(11)
      print*
      print*,'o found nhalos     = ',nhalos

      Xhost    = V(3,ihost)
      Yhost    = V(4,ihost)
      Zhost    = V(5,ihost)
      Rhost    = V(10,ihost)/1000.
      Mhost    = V(9,ihost)
      
      print*,'  host information = ',Xhost,Yhost,Zhost,Rhost,Mhost

      ! write host halo
      write(12,111)(V(k,ihost),k=1,NCOLUMNS)

      Nsat = 0
      Msat = 0.0
      do i=1,nhalos

         if (i .NE. ihost)then
            dX = V(3,i)-Xhost
            dY = V(4,i)-Yhost
            dZ = V(5,i)-Zhost
            
            if(dX .GT.  BOX/2.) dX = BOX-dX
            if(dY .GT.  BOX/2.) dY = BOX-dY
            if(dZ .GT.  BOX/2.) dZ = BOX-dZ
            if(dX .LT. -BOX/2.) dX = BOX+dX
            if(dY .LT. -BOX/2.) dY = BOX+dY
            if(dZ .LT. -BOX/2.) dZ = BOX+dZ
            
            Dist = sqrt(dX**2 + dY**2 + dZ**2) + V(10,i)/1000.
            
            if(Dist .LE. Rfac*Rhost .AND. V(9,i) .GT. xMmin) then
               
               write(12,111)(V(k,i),k=1,NCOLUMNS)

 111           FORMAT(2f16.0,6f16.8,g16.8,22f16.8,f16.0,2g18.8,4f16.8)
               
               Nsat = Nsat + 1
               Msat = Msat + V(9,i)
            endif

         endif

      enddo

      print*
      print*,'o no. of satellites in host #',ihost-1,'       = ',Nsat
      print*,'o total mass in satellites            = ',Msat
      print*,'o fraction of host mass in satellites = ',Msat/Mhost

      STOP
      end
         
