program cell_hig_2_rapid

!RIV_ID. The unique integer identifying a given river reach.
!DOWN_ID. The unique integer identifying the unique reach located directly downstream of RIV_ID.
!NB_UP.	The number of river reaches located directly upstream of RIV_ID.
!UP1. The unique integer of a reach (if	it exists) that is located directly upstream of RIV_ID.
!UP2. The unique integer of a reach (if	it exists) that is located directly upstream of RIV_ID and that differs from UP1.
! ...
!UP(n). The unique integer of a reach (if it exists) that is located directly upstream of RIV_ID and that differs from UP1, UP2, ..., UP(n-1).


 integer, parameter      :: N=1948
 integer                 :: I, J, C
 integer, dimension(N)   :: RIV_ID, DOWN_ID, IDM
 integer, dimension(N)   :: SB
 integer, dimension(N)   :: COUNT
 integer, dimension(N)   :: IDUMMY7, IDUMMY8 
 real, dimension(N)      :: RDUMMY2, RDUMMY3, RDUMMY5, RDUMMY6, RDUMMY9, RDUMMY10
 integer, dimension(N,6) :: UP
 
 integer, dimension(N)   :: DOWN_ID_inv
 integer, dimension(N,6) :: UP_inv
 

 open(20,file='cell_5km.hig',form='formatted')

 read(20,*)

 do I=1,N

   read(20,*) RIV_ID(I), RDUMMY2(I), RDUMMY3(I), SB(I), RDUMMY5(I), RDUMMY6(I), IDUMMY7(I), IDUMMY8(i), RDUMMY9(I), RDUMMY10(I), IDM(I)

!  print*,    RIV_ID(I), RDUMMY2(I), RDUMMY3(I), SB(I), RDUMMY5(I), RDUMMY6(I), IDUMMY7(I), IDUMMY8(I), RDUMMY9(I), RDUMMY10(I), IDM(I)

 enddo
 
 COUNT=0
 
 do I=1,N
 
    do J=1,N
    
       if (RIV_ID(I)==IDM(J)) then
       
!         print*, I, RIV_ID(I), IDM(J), J
	  COUNT(I)=COUNT(I)+1
	  UP(I,COUNT(I))=J
	  
       endif
       
    enddo
 
!   print*, I, COUNT(I)
    
    do C=1,COUNT(I)   
    DOWN_ID(UP(I,C))= RIV_ID(I)
    enddo
    
 enddo
 
 
 
 open(30,file='rapid_connect_cell_5km_hig.csv',form='formatted')

 open(40,file='rapid_connect_cell_5km_hig_inv.csv',form='formatted')
 
 write(30,*) "Maximum number of upstream reaches: ", MAXVAL(COUNT)

 write(30,*) "RIV_ID(I)   DOWN_ID(I) NB_UP(I)   UP(I,1)    UP(I,2)    UP(I,3)    UP(I,4)    UP(I,5)    UP(I,6)   "
 
 do I=1,N

! print'(8I6)',    RIV_ID(I),  COUNT(I), UP(I,1), UP(I,2), UP(I,3), UP(I,4), UP(I,5), UP(I,6)
  
! write(30,'(I10,A10,7I11)')    RIV_ID(I), "DOWN_ID", COUNT(I), UP(I,1), UP(I,2), UP(I,3), UP(I,4), UP(I,5), UP(I,6)

  write(30,'(I10,I10,7I11)')    RIV_ID(I), DOWN_ID(I), COUNT(I), UP(I,1), UP(I,2), UP(I,3), UP(I,4), UP(I,5), UP(I,6)
 
  if (DOWN_ID(I) == 0) then
    DOWN_ID_inv(I)=0
  else
    DOWN_ID_inv(I)=(N-DOWN_ID(I))+1
  endif
  
  do C=1,MAXVAL(COUNT)

    if (UP(I,C) == 0) then
      UP_inv(I,C)=0
    else
      UP_inv(I,C)=(N-UP(I,C))+1
    endif  
  
  enddo
 
  write(40,'(I10,I10,7I11)')    (N-RIV_ID(I))+1, DOWN_ID_inv(I), COUNT(I), UP_inv(I,1), UP_inv(I,2), UP_inv(I,3), UP_inv(I,4), UP_inv(I,5), UP_inv(I,6)

 enddo

end program cell_hig_2_rapid
