source: branches/ORCHIDEE_2_2/ORCHIDEE/src_sechiba/routing.f90 @ 5811

Last change on this file since 5811 was 5613, checked in by josefine.ghattas, 6 years ago

Added reading of variable pond from floodplains.nc, see ticket #441

A Jornet

  • Property svn:keywords set to Revision Date HeadURL Date Author Revision
File size: 369.8 KB
Line 
1! =================================================================================================================================
2! MODULE       : routing
3!
4! CONTACT      : orchidee-help _at_ listes.ipsl.fr
5!
6! LICENCE      : IPSL (2006)
7! This software is governed by the CeCILL licence see ORCHIDEE/ORCHIDEE_CeCILL.LIC
8!
9!>\BRIEF       This module routes the water over the continents into the oceans and computes the water
10!!             stored in floodplains or taken for irrigation.
11!!
12!!\n DESCRIPTION: None
13!!
14!! RECENT CHANGE(S): None
15!!
16!! REFERENCE(S) :
17!!
18!! SVN          :
19!! $HeadURL$
20!! $Date$
21!! $Revision$
22!! \n
23!_ ================================================================================================================================
24!
25!
26! Histoire Salee
27!---------------
28! La douce riviere
29! Sortant de son lit
30! S'est jetee ma chere
31! dans les bras mais oui
32! du beau fleuve
33!
34! L'eau coule sous les ponts
35! Et puis les flots s'emeuvent
36! - N'etes vous pas au courant ?
37! Il parait que la riviere
38! Va devenir mer
39!                       Roland Bacri
40!
41
42
43MODULE routing
44
45  USE ioipsl   
46  USE xios_orchidee
47  USE ioipsl_para 
48  USE constantes
49  USE time, ONLY : one_day, dt_sechiba
50  USE constantes_soil
51  USE pft_parameters
52  USE sechiba_io_p
53  USE interpol_help
54  USE grid
55  USE mod_orchidee_para
56
57
58  IMPLICIT NONE
59  PRIVATE
60  PUBLIC :: routing_main, routing_initialize, routing_finalize, routing_clear
61
62!! PARAMETERS
63  INTEGER(i_std), PARAMETER                                  :: nbasmax=5                   !! The maximum number of basins we wish to have per grid box (truncation of the model) (unitless)
64  INTEGER(i_std), SAVE                                       :: nbvmax                      !! The maximum number of basins we can handle at any time during the generation of the maps (unitless)
65!$OMP THREADPRIVATE(nbvmax)
66  REAL(r_std), SAVE                                          :: fast_tcst = 3.0             !! Property of the fast reservoir, (day/m)
67!$OMP THREADPRIVATE(fast_tcst)
68  REAL(r_std), SAVE                                          :: slow_tcst = 25.0            !! Property of the slow reservoir, (day/m)
69!$OMP THREADPRIVATE(slow_tcst)
70  REAL(r_std), SAVE                                          :: stream_tcst = 0.24          !! Property of the stream reservoir, (day/m)
71!$OMP THREADPRIVATE(stream_tcst)
72  REAL(r_std), SAVE                                          :: flood_tcst = 4.0            !! Property of the floodplains reservoir, (day/m)
73!$OMP THREADPRIVATE(flood_tcst)
74  REAL(r_std), SAVE                                          :: swamp_cst = 0.2             !! Fraction of the river transport that flows to the swamps (unitless;0-1)
75!$OMP THREADPRIVATE(swamp_cst)
76  !
77  !  Relation between volume and fraction of floodplains
78  !
79  REAL(r_std), SAVE                                          :: beta = 2.0                  !! Parameter to fix the shape of the floodplain (>1 for convex edges, <1 for concave edges) (unitless)
80!$OMP THREADPRIVATE(beta)
81  REAL(r_std), SAVE                                          :: betap = 0.5                 !! Ratio of the basin surface intercepted by ponds and the maximum surface of ponds (unitless;0-1)
82!$OMP THREADPRIVATE(betap)
83  REAL(r_std), SAVE                                          :: floodcri = 2000.0           !! Potential height for which all the basin is flooded (mm)
84!$OMP THREADPRIVATE(floodcri)
85  !
86  !  Relation between maximum surface of ponds and basin surface, and drainage (mm/j) to the slow_res
87  !
88  REAL(r_std), PARAMETER                                     :: pond_bas = 50.0             !! [DISPENSABLE] - not used
89  REAL(r_std), SAVE                                          :: pondcri = 2000.0            !! Potential height for which all the basin is a pond (mm)
90!$OMP THREADPRIVATE(pondcri)
91  !
92  REAL(r_std), PARAMETER                                     :: maxevap_lake = 7.5/86400.   !! Maximum evaporation rate from lakes (kg/m^2/s)
93  !
94  REAL(r_std),SAVE                                           :: dt_routing                  !! Routing time step (s)
95!$OMP THREADPRIVATE(dt_routing)
96  !
97  INTEGER(i_std), SAVE                                       :: diagunit = 87               !! Diagnostic file unit (unitless)
98!$OMP THREADPRIVATE(diagunit)
99  !
100  ! Logicals to control model configuration
101  !
102  LOGICAL, SAVE                                              :: dofloodinfilt = .FALSE.     !! Logical to choose if floodplains infiltration is activated or not (true/false)
103!$OMP THREADPRIVATE(dofloodinfilt)
104  LOGICAL, SAVE                                              :: doswamps = .FALSE.          !! Logical to choose if swamps are activated or not (true/false)
105!$OMP THREADPRIVATE(doswamps)
106  LOGICAL, SAVE                                              :: doponds = .FALSE.           !! Logical to choose if ponds are activated or not (true/false)
107!$OMP THREADPRIVATE(doponds)
108  !
109  ! The variables describing the basins and their routing, need to be in the restart file.
110  !
111  INTEGER(i_std), SAVE                                       :: num_largest                 !! Number of largest river basins which should be treated as independently as rivers
112                                                                                            !! (not flow into ocean as diffusion coastal flow) (unitless)
113!$OMP THREADPRIVATE(num_largest)
114  REAL(r_std), SAVE                                          :: time_counter                !! Time counter (s)
115!$OMP THREADPRIVATE(time_counter)
116  REAL(r_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)     :: routing_area_loc            !! Surface of basin (m^2)
117!$OMP THREADPRIVATE(routing_area_loc)
118  REAL(r_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)     :: topo_resid_loc              !! Topographic index of the retention time (m)
119!$OMP THREADPRIVATE(topo_resid_loc)
120  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: route_togrid_loc            !! Grid into which the basin flows (unitless)
121!$OMP THREADPRIVATE(route_togrid_loc)
122  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: route_tobasin_loc           !! Basin in to which the water goes (unitless)
123!$OMP THREADPRIVATE(route_tobasin_loc)
124  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: route_nbintobas_loc         !! Number of basin into current one (unitless)
125!$OMP THREADPRIVATE(route_nbintobas_loc)
126  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: global_basinid_loc          !! ID of basin (unitless)
127!$OMP THREADPRIVATE(global_basinid_loc)
128  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: hydrodiag_loc               !! Variable to diagnose the hydrographs
129!$OMP THREADPRIVATE(hydrodiag_loc)
130  REAL(r_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:)       :: hydroupbasin_loc            !! The area upstream of the gauging station (m^2)
131!$OMP THREADPRIVATE(hydroupbasin_loc)
132  !
133  ! parallelism
134  REAL(r_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)     :: routing_area_glo            !! Surface of basin (m^2)
135!$OMP THREADPRIVATE(routing_area_glo)
136  REAL(r_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)     :: topo_resid_glo              !! Topographic index of the retention time (m)
137!$OMP THREADPRIVATE(topo_resid_glo)
138  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: route_togrid_glo            !! Grid into which the basin flows (unitless)
139!$OMP THREADPRIVATE(route_togrid_glo)
140  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: route_tobasin_glo           !! Basin in to which the water goes (unitless)
141!$OMP THREADPRIVATE(route_tobasin_glo)
142  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: route_nbintobas_glo         !! Number of basin into current one (unitless)
143!$OMP THREADPRIVATE(route_nbintobas_glo)
144  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: global_basinid_glo          !! ID of basin (unitless)
145!$OMP THREADPRIVATE(global_basinid_glo)
146  INTEGER(i_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:,:)  :: hydrodiag_glo               !! Variable to diagnose the hydrographs
147!$OMP THREADPRIVATE(hydrodiag_glo)
148  REAL(r_std), SAVE, ALLOCATABLE, TARGET, DIMENSION(:)       :: hydroupbasin_glo            !! The area upstream of the gauging station (m^2)
149!$OMP THREADPRIVATE(hydroupbasin_glo)
150  !
151  REAL(r_std), SAVE, POINTER, DIMENSION(:,:)                 :: routing_area                !! Surface of basin (m^2)
152!$OMP THREADPRIVATE(routing_area)
153  REAL(r_std), SAVE, POINTER, DIMENSION(:,:)                 :: topo_resid                  !! Topographic index of the retention time (m)
154!$OMP THREADPRIVATE(topo_resid)
155  INTEGER(i_std), SAVE, POINTER, DIMENSION(:,:)              :: route_togrid                !! Grid into which the basin flows (unitless)
156!$OMP THREADPRIVATE(route_togrid)
157  INTEGER(i_std), SAVE, POINTER, DIMENSION(:,:)              :: route_tobasin               !! Basin in to which the water goes (unitless)
158!$OMP THREADPRIVATE(route_tobasin)
159  INTEGER(i_std), SAVE, POINTER, DIMENSION(:,:)              :: route_nbintobas             !! Number of basin into current one (unitless)
160!$OMP THREADPRIVATE(route_nbintobas)
161  INTEGER(i_std), SAVE, POINTER, DIMENSION(:,:)              :: global_basinid              !! ID of basin (unitless)
162!$OMP THREADPRIVATE(global_basinid)
163  INTEGER(i_std), SAVE, POINTER, DIMENSION(:,:)              :: hydrodiag                   !! Variable to diagnose the hydrographs
164!$OMP THREADPRIVATE(hydrodiag)
165  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: slowflow_diag               !! Diagnostic slow flow hydrographs (kg/dt)
166!$OMP THREADPRIVATE(slowflow_diag) 
167  REAL(r_std), SAVE, POINTER, DIMENSION(:)                   :: hydroupbasin                !! The area upstream of the gauging station (m^2)
168!$OMP THREADPRIVATE(hydroupbasin)
169  !
170  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: irrigated                   !! Area equipped for irrigation in each grid box (m^2)
171!$OMP THREADPRIVATE(irrigated)
172  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: floodplains                 !! Maximal surface which can be inundated in each grid box (m^2)
173!$OMP THREADPRIVATE(floodplains)
174  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: swamp                       !! Maximal surface of swamps in each grid box (m^2)
175!$OMP THREADPRIVATE(swamp)
176  !
177  ! The reservoirs, also to be put into the restart file.
178  !
179  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)             :: fast_reservoir              !! Water amount in the fast reservoir (kg)
180!$OMP THREADPRIVATE(fast_reservoir)
181  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)             :: slow_reservoir              !! Water amount in the slow reservoir (kg)
182!$OMP THREADPRIVATE(slow_reservoir)
183  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)             :: stream_reservoir            !! Water amount in the stream reservoir (kg)
184!$OMP THREADPRIVATE(stream_reservoir)
185  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)             :: flood_reservoir             !! Water amount in the floodplains reservoir (kg)
186!$OMP THREADPRIVATE(flood_reservoir)
187  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: lake_reservoir              !! Water amount in the lake reservoir (kg)
188!$OMP THREADPRIVATE(lake_reservoir)
189  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: pond_reservoir              !! Water amount in the pond reservoir (kg)
190!$OMP THREADPRIVATE(pond_reservoir)
191  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:)             :: flood_frac_bas              !! Flooded fraction per basin (unitless;0-1)
192!$OMP THREADPRIVATE(flood_frac_bas)
193  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: pond_frac                   !! Pond fraction per grid box (unitless;0-1)
194!$OMP THREADPRIVATE(pond_frac)
195  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: flood_height                !! Floodplain height (mm)
196!$OMP THREADPRIVATE(flood_height)
197  !
198  ! The accumulated fluxes.
199  !
200  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: floodout_mean               !! Accumulated flow out of floodplains (kg/m^2/dt)
201!$OMP THREADPRIVATE(floodout_mean)
202  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: runoff_mean                 !! Accumulated runoff (kg/m^2/dt)
203!$OMP THREADPRIVATE(runoff_mean)
204  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: drainage_mean               !! Accumulated drainage (kg/m^2/dt)
205!$OMP THREADPRIVATE(drainage_mean)
206  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: transpot_mean               !! Mean potential transpiration from the plants (kg/m^2/dt)
207!$OMP THREADPRIVATE(transpot_mean)
208  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: precip_mean                 !! Accumulated precipitation (kg/m^2/dt)
209!$OMP THREADPRIVATE(precip_mean)
210  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: humrel_mean                 !! Mean soil moisture stress, mean root extraction potential (unitless)
211!$OMP THREADPRIVATE(humrel_mean)
212  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: totnobio_mean               !! Mean last total fraction of no bio (unitless;0-1)
213!$OMP THREADPRIVATE(totnobio_mean)
214  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: vegtot_mean                 !! Mean potentially vegetated fraction (unitless;0-1)
215!$OMP THREADPRIVATE(vegtot_mean)
216  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: k_litt_mean                 !! Mean averaged conductivity for saturated infiltration in the 'litter' layer (kg/m^2/dt)
217!$OMP THREADPRIVATE(k_litt_mean)
218  !
219  ! The averaged outflow fluxes.
220  !
221  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: lakeinflow_mean              !! Mean lake inflow (kg/m^2/dt)
222!$OMP THREADPRIVATE(lakeinflow_mean)
223  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: returnflow_mean              !! Mean water flow from lakes and swamps which returns to the grid box.
224                                                                                             !! This water will go back into the hydrol module to allow re-evaporation (kg/m^2/dt)
225!$OMP THREADPRIVATE(returnflow_mean)
226  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: reinfiltration_mean          !! Mean water flow which returns to the grid box (kg/m^2/dt)
227!$OMP THREADPRIVATE(reinfiltration_mean)
228  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: irrigation_mean              !! Mean irrigation flux.
229                                                                                             !! This is the water taken from the reservoirs and beeing put into the upper layers of the soil (kg/m^2/dt)
230!$OMP THREADPRIVATE(irrigation_mean)
231  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: riverflow_mean               !! Mean Outflow of the major rivers.
232                                                                                             !! The flux will be located on the continental grid but this should be a coastal point (kg/dt)
233!$OMP THREADPRIVATE(riverflow_mean)
234  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: coastalflow_mean             !! Mean outflow on coastal points by small basins.
235                                                                                             !! This is the water which flows in a disperse way into the ocean (kg/dt)
236!$OMP THREADPRIVATE(coastalflow_mean)
237  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: floodtemp                    !! Temperature to decide if floodplains work (K)
238!$OMP THREADPRIVATE(floodtemp)
239  INTEGER(i_std), SAVE                                       :: floodtemp_lev                !! Temperature level to decide if floodplains work (K)
240!$OMP THREADPRIVATE(floodtemp_lev)
241  !
242  ! Diagnostic variables ... well sort of !
243  !
244  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: irrig_netereq                !! Irrigation requirement (water requirements by the crop for its optimal growth (kg/m^2/dt)
245!$OMP THREADPRIVATE(irrig_netereq)
246  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: hydrographs                  !! Hydrographs at the outflow of the grid box for major basins (kg/dt)
247!$OMP THREADPRIVATE(hydrographs)
248  !
249  ! Diagnostics for the various reservoirs we use (Kg/m^2)
250  !
251  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: fast_diag                    !! Diagnostic for the fast reservoir (kg/m^2)
252!$OMP THREADPRIVATE(fast_diag)
253  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: slow_diag                    !! Diagnostic for the slow reservoir (kg/m^2)
254!$OMP THREADPRIVATE(slow_diag)
255  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: stream_diag                  !! Diagnostic for the stream reservoir (kg/m^2)
256!$OMP THREADPRIVATE(stream_diag)
257  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: flood_diag                   !! Diagnostic for the floodplain reservoir (kg/m^2)
258!$OMP THREADPRIVATE(flood_diag)
259  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: pond_diag                    !! Diagnostic for the pond reservoir (kg/m^2)
260!$OMP THREADPRIVATE(pond_diag)
261  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: lake_diag                    !! Diagnostic for the lake reservoir (kg/m^2)
262!$OMP THREADPRIVATE(lake_diag)
263
264  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:)               :: mask_coast                   !! Mask with coastal gridcells on local grid(1/0)
265!$OMP THREADPRIVATE(mask_coast)
266  REAL(r_std), SAVE                                          :: max_lake_reservoir           !! Maximum limit of water in lake_reservoir [kg/m2]
267  !$OMP THREADPRIVATE(max_lake_reservoir)
268  INTEGER(i_std), SAVE                                       :: nb_coast_gridcells           !! Number of gridcells which can receive coastalflow
269
270
271CONTAINS
272  !!  =============================================================================================================================
273  !! SUBROUTINE:         routing_initialize
274  !!
275  !>\BRIEF               Initialize the routing module
276  !!
277  !! DESCRIPTION:        Initialize the routing module. Read from restart file or read the routing.nc file to initialize the
278  !!                     routing scheme.
279  !!
280  !! RECENT CHANGE(S)
281  !!
282  !! REFERENCE(S)
283  !!
284  !! FLOWCHART   
285  !! \n
286  !_ ==============================================================================================================================
287
288  SUBROUTINE routing_initialize( kjit,       nbpt,           index,                 &
289                                rest_id,     hist_id,        hist2_id,   lalo,      &
290                                neighbours,  resolution,     contfrac,   stempdiag, &
291                                returnflow,  reinfiltration, irrigation, riverflow, &
292                                coastalflow, flood_frac,     flood_res )
293       
294    IMPLICIT NONE
295   
296    !! 0.1 Input variables
297    INTEGER(i_std), INTENT(in)     :: kjit                 !! Time step number (unitless)
298    INTEGER(i_std), INTENT(in)     :: nbpt                 !! Domain size (unitless)
299    INTEGER(i_std), INTENT(in)     :: index(nbpt)          !! Indices of the points on the map (unitless)
300    INTEGER(i_std),INTENT(in)      :: rest_id              !! Restart file identifier (unitless)
301    INTEGER(i_std),INTENT(in)      :: hist_id              !! Access to history file (unitless)
302    INTEGER(i_std),INTENT(in)      :: hist2_id             !! Access to history file 2 (unitless)
303    REAL(r_std), INTENT(in)        :: lalo(nbpt,2)         !! Vector of latitude and longitudes (beware of the order !)
304
305    INTEGER(i_std), INTENT(in)     :: neighbours(nbpt,NbNeighb) !! Vector of neighbours for each grid point
306                                                           !! (1=N, 2=NE, 3=E, 4=SE, 5=S, 6=SW, 7=W, 8=NW) (unitless)
307    REAL(r_std), INTENT(in)        :: resolution(nbpt,2)   !! The size of each grid box in X and Y (m)
308    REAL(r_std), INTENT(in)        :: contfrac(nbpt)       !! Fraction of land in each grid box (unitless;0-1)
309    REAL(r_std), INTENT(in)        :: stempdiag(nbpt,nslm) !! Diagnostic soil temperature profile
310
311    !! 0.2 Output variables
312    REAL(r_std), INTENT(out)       :: returnflow(nbpt)     !! The water flow from lakes and swamps which returns to the grid box.
313                                                           !! This water will go back into the hydrol module to allow re-evaporation (kg/m^2/dt)
314    REAL(r_std), INTENT(out)       :: reinfiltration(nbpt) !! Water flow from ponds and floodplains which returns to the grid box (kg/m^2/dt)
315    REAL(r_std), INTENT(out)       :: irrigation(nbpt)     !! Irrigation flux. This is the water taken from the reservoirs and beeing put into the upper layers of the soil (kg/m^2/dt)
316    REAL(r_std), INTENT(out)       :: riverflow(nbpt)      !! Outflow of the major rivers. The flux will be located on the continental grid but this should be a coastal point (kg/dt)
317
318    REAL(r_std), INTENT(out)       :: coastalflow(nbpt)    !! Outflow on coastal points by small basins. This is the water which flows in a disperse way into the ocean (kg/dt)
319    REAL(r_std), INTENT(out)       :: flood_frac(nbpt)     !! Flooded fraction of the grid box (unitless;0-1)
320    REAL(r_std), INTENT(out)       :: flood_res(nbpt)      !! Diagnostic of water amount in the floodplains reservoir (kg)
321   
322    !! 0.3 Local variables
323    REAL(r_std), DIMENSION(nbp_glo):: mask_coast_glo       !! Mask with coastal gridcells on global grid (1/0)
324    LOGICAL                        :: init_irrig           !! Logical to initialize the irrigation (true/false)
325    LOGICAL                        :: init_flood           !! Logical to initialize the floodplains (true/false)
326    LOGICAL                        :: init_swamp           !! Logical to initialize the swamps (true/false)
327    INTEGER                        :: ig, ib, rtg, rtb     !! Index
328    INTEGER                        :: ier                  !! Error handeling
329!_ ================================================================================================================================
330
331    !
332    ! do initialisation
333    !
334    nbvmax = 440
335    ! Here we will allocate the memory and get the fixed fields from the restart file.
336    ! If the info is not found then we will compute the routing map.
337    !
338
339    CALL routing_init (kjit, nbpt, index, returnflow, reinfiltration, irrigation, &
340         riverflow, coastalflow, flood_frac, flood_res, stempdiag, rest_id)
341
342    routing_area => routing_area_loc 
343    topo_resid => topo_resid_loc
344    route_togrid => route_togrid_loc
345    route_tobasin => route_tobasin_loc
346    global_basinid => global_basinid_loc
347    hydrodiag => hydrodiag_loc
348   
349    ! This routine computes the routing map if the route_togrid_glo is undefined. This means that the
350    ! map has not been initialized during the restart process..
351    !
352    !! Reads in the map of the basins and flow directions to construct the catchments of each grid box
353    !
354    IF ( COUNT(route_togrid_glo .GE. undef_int) .GT. 0 ) THEN
355       CALL routing_basins_p(nbpt, lalo, neighbours, resolution, contfrac)
356    ENDIF
357
358    !! Create a mask containing all possible coastal gridcells and count total number of coastal gridcells
359    IF (is_root_prc) THEN
360       mask_coast_glo(:)=0
361       DO ib=1,nbasmax
362          DO ig=1,nbp_glo
363             rtg = route_togrid_glo(ig,ib)
364             rtb = route_tobasin_glo(ig,ib)
365             ! Coastal gridcells are stored in nbasmax+2
366             IF (rtb == nbasmax+2) THEN
367                mask_coast_glo(rtg) = 1
368             END IF
369          END DO
370       END DO
371       nb_coast_gridcells=SUM(mask_coast_glo)
372       IF (printlev>=3) WRITE(numout,*) 'Number of coastal gridcells = ', nb_coast_gridcells
373    ENDIF
374    CALL bcast(nb_coast_gridcells)
375
376    ALLOCATE(mask_coast(nbpt), stat=ier)
377    IF (ier /= 0) CALL ipslerr_p(3,'routing_inititalize','Pb in allocate for mask_coast','','')
378    CALL scatter(mask_coast_glo, mask_coast)
379    CALL xios_orchidee_send_field("mask_coast",mask_coast)
380
381
382    !
383    ! Do we have what we need if we want to do irrigation
384    !! Initialisation of flags for irrigated land, flood plains and swamps
385    !
386    init_irrig = .FALSE.
387    IF ( do_irrigation ) THEN
388       IF (COUNT(irrigated .GE. undef_sechiba-1) > 0) init_irrig = .TRUE.
389    END IF
390   
391    init_flood = .FALSE.
392    IF ( do_floodplains ) THEN
393       IF (COUNT(floodplains .GE. undef_sechiba-1) > 0) init_flood = .TRUE.
394    END IF
395   
396    init_swamp = .FALSE.
397    IF ( doswamps ) THEN
398       IF (COUNT(swamp .GE. undef_sechiba-1) > 0 ) init_swamp = .TRUE.
399    END IF
400       
401    !! If we have irrigated land, flood plains or swamps then we need to interpolate the 0.5 degree
402    !! base data set to the resolution of the model.
403   
404    IF ( init_irrig .OR. init_flood .OR. init_swamp ) THEN
405       CALL routing_irrigmap(nbpt, index, lalo, neighbours, resolution, &
406            contfrac, init_irrig, irrigated, init_flood, floodplains, init_swamp, swamp, hist_id, hist2_id)
407    ENDIF
408   
409    IF ( do_irrigation ) THEN
410       CALL xios_orchidee_send_field("irrigmap",irrigated)
411       
412       IF (printlev >= 3) WRITE(numout,*) 'Verification : range of irrigated : ', MINVAL(irrigated), MAXVAL(irrigated) 
413       IF ( .NOT. almaoutput ) THEN
414          CALL histwrite_p(hist_id, 'irrigmap', 1, irrigated, nbpt, index)
415       ELSE
416          CALL histwrite_p(hist_id, 'IrrigationMap', 1, irrigated, nbpt, index)
417       ENDIF
418       IF ( hist2_id > 0 ) THEN
419          IF ( .NOT. almaoutput ) THEN
420             CALL histwrite_p(hist2_id, 'irrigmap', 1, irrigated, nbpt, index)
421          ELSE
422             CALL histwrite_p(hist2_id, 'IrrigationMap', 1, irrigated, nbpt, index)
423          ENDIF
424       ENDIF
425    ENDIF
426   
427    IF ( do_floodplains ) THEN
428       CALL xios_orchidee_send_field("floodmap",floodplains)
429       
430       IF (printlev>=3) WRITE(numout,*) 'Verification : range of floodplains : ', MINVAL(floodplains), MAXVAL(floodplains) 
431       IF ( .NOT. almaoutput ) THEN
432          CALL histwrite_p(hist_id, 'floodmap', 1, floodplains, nbpt, index)
433       ELSE
434          CALL histwrite_p(hist_id, 'FloodplainsMap', 1, floodplains, nbpt, index)
435       ENDIF
436       IF ( hist2_id > 0 ) THEN
437          IF ( .NOT. almaoutput ) THEN
438             CALL histwrite_p(hist2_id, 'floodmap', 1, floodplains, nbpt, index)
439          ELSE
440             CALL histwrite_p(hist2_id, 'FloodplainsMap', 1, floodplains, nbpt, index)
441          ENDIF
442       ENDIF
443    ENDIF
444   
445    IF ( doswamps ) THEN
446       CALL xios_orchidee_send_field("swampmap",swamp)
447       
448       IF (printlev>=3) WRITE(numout,*) 'Verification : range of swamp : ', MINVAL(swamp), MAXVAL(swamp) 
449       IF ( .NOT. almaoutput ) THEN
450          CALL histwrite_p(hist_id, 'swampmap', 1, swamp, nbpt, index)
451       ELSE
452          CALL histwrite_p(hist_id, 'SwampMap', 1, swamp, nbpt, index)
453       ENDIF
454       IF ( hist2_id > 0 ) THEN
455          IF ( .NOT. almaoutput ) THEN
456             CALL histwrite_p(hist2_id, 'swampmap', 1, swamp, nbpt, index)
457          ELSE
458             CALL histwrite_p(hist2_id, 'SwampMap', 1, swamp, nbpt, index)
459          ENDIF
460       ENDIF
461    ENDIF
462   
463    !! This routine gives a diagnostic of the basins used.
464    CALL routing_diagnostic_p(nbpt, index, lalo, resolution, contfrac, hist_id, hist2_id)
465   
466  END SUBROUTINE routing_initialize
467
468!! ================================================================================================================================
469!! SUBROUTINE   : routing_main
470!!
471!>\BRIEF          This module routes the water over the continents (runoff and
472!!                drainage produced by the hydrol module) into the oceans.
473!!
474!! DESCRIPTION (definitions, functional, design, flags):
475!! The routing scheme (Polcher, 2003) carries the water from the runoff and drainage simulated by SECHIBA
476!! to the ocean through reservoirs, with some delay. The routing scheme is based on
477!! a parametrization of the water flow on a global scale (Miller et al., 1994; Hagemann
478!! and Dumenil, 1998). Given the global map of the main watersheds (Oki et al., 1999;
479!! Fekete et al., 1999; Vorosmarty et al., 2000) which delineates the boundaries of subbasins
480!! and gives the eight possible directions of water flow within the pixel, the surface
481!! runoff and the deep drainage are routed to the ocean. The time-step of the routing is one day.
482!! The scheme also diagnoses how much water is retained in the foodplains and thus return to soil
483!! moisture or is taken out of the rivers for irrigation. \n
484!!
485!! RECENT CHANGE(S): None
486!!
487!! MAIN OUTPUT VARIABLE(S):
488!! The result of the routing are 3 fluxes :
489!! - riverflow   : The water which flows out from the major rivers. The flux will be located
490!!                 on the continental grid but this should be a coastal point.
491!! - coastalflow : This is the water which flows in a disperse way into the ocean. Essentially these
492!!                 are the outflows from all of the small rivers.
493!! - returnflow  : This is the water which flows into a land-point - typically rivers which end in
494!!                 the desert. This water will go back into the hydrol module to allow re-evaporation.
495!! - irrigation  : This is water taken from the reservoir and is being put into the upper
496!!                 layers of the soil.
497!! The two first fluxes are in kg/dt and the last two fluxes are in kg/(m^2dt).\n
498!!
499!! REFERENCE(S) :
500!! - Miller JR, Russell GL, Caliri G (1994)
501!!   Continental-scale river flow in climate models.
502!!   J. Clim., 7:914-928
503!! - Hagemann S and Dumenil L. (1998)
504!!   A parametrization of the lateral waterflow for the global scale.
505!!   Clim. Dyn., 14:17-31
506!! - Oki, T., T. Nishimura, and P. Dirmeyer (1999)
507!!   Assessment of annual runoff from land surface models using total runoff integrating pathways (TRIP)
508!!   J. Meteorol. Soc. Jpn., 77, 235-255
509!! - Fekete BM, Charles V, Grabs W (2000)
510!!   Global, composite runoff fields based on observed river discharge and simulated water balances.
511!!   Technical report, UNH/GRDC, Global Runoff Data Centre, Koblenz
512!! - Vorosmarty, C., B. Fekete, B. Meybeck, and R. Lammers (2000)
513!!   Global system of rivers: Its role in organizing continental land mass and defining land-to-ocean linkages
514!!   Global Biogeochem. Cycles, 14, 599-621
515!! - Vivant, A-C. (?? 2002)
516!!   Développement du schéma de routage et des plaines d'inondation, MSc Thesis, Paris VI University
517!! - J. Polcher (2003)
518!!   Les processus de surface a l'echelle globale et leurs interactions avec l'atmosphere
519!!   Habilitation a diriger les recherches, Paris VI University, 67pp.
520!!
521!! FLOWCHART    :
522!! \latexonly
523!! \includegraphics[scale=0.75]{routing_main_flowchart.png}
524!! \endlatexonly
525!! \n
526!_ ================================================================================================================================
527
528SUBROUTINE routing_main(kjit, nbpt, index, &
529       & lalo, neighbours, resolution, contfrac, totfrac_nobio, veget_max, floodout, runoff, &
530       & drainage, transpot, precip_rain, humrel, k_litt, flood_frac, flood_res, &
531       & stempdiag, reinf_slope, returnflow, reinfiltration, irrigation, riverflow, coastalflow, rest_id, hist_id, hist2_id)
532
533    IMPLICIT NONE
534
535    !! 0.1 Input variables
536    INTEGER(i_std), INTENT(in)     :: kjit                 !! Time step number (unitless)
537    INTEGER(i_std), INTENT(in)     :: nbpt                 !! Domain size (unitless)
538    INTEGER(i_std),INTENT(in)      :: rest_id              !! Restart file identifier (unitless)
539    INTEGER(i_std),INTENT(in)      :: hist_id              !! Access to history file (unitless)
540    INTEGER(i_std),INTENT(in)      :: hist2_id             !! Access to history file 2 (unitless)
541    INTEGER(i_std), INTENT(in)     :: index(nbpt)          !! Indices of the points on the map (unitless)
542    REAL(r_std), INTENT(in)        :: lalo(nbpt,2)         !! Vector of latitude and longitudes (beware of the order !)
543    INTEGER(i_std), INTENT(in)     :: neighbours(nbpt,NbNeighb)   !! Vector of neighbours for each grid point (1=N, 2=NE, 3=E, 4=SE, 5=S, 6=SW, 7=W, 8=NW) (unitless)
544    REAL(r_std), INTENT(in)        :: resolution(nbpt,2)   !! The size of each grid box in X and Y (m)
545    REAL(r_std), INTENT(in)        :: contfrac(nbpt)       !! Fraction of land in each grid box (unitless;0-1)
546    REAL(r_std), INTENT(in)        :: totfrac_nobio(nbpt)  !! Total fraction of no-vegetation (continental ice, lakes ...) (unitless;0-1)
547    REAL(r_std), INTENT(in)        :: veget_max(nbpt,nvm)  !! Maximal fraction of vegetation (unitless;0-1)
548    REAL(r_std), INTENT(in)        :: floodout(nbpt)       !! Grid-point flow out of floodplains (kg/m^2/dt)
549    REAL(r_std), INTENT(in)        :: runoff(nbpt)         !! Grid-point runoff (kg/m^2/dt)
550    REAL(r_std), INTENT(in)        :: drainage(nbpt)       !! Grid-point drainage (kg/m^2/dt)
551    REAL(r_std), INTENT(in)        :: transpot(nbpt,nvm)   !! Potential transpiration of the vegetation (kg/m^2/dt)
552    REAL(r_std), INTENT(in)        :: precip_rain(nbpt)    !! Rainfall (kg/m^2/dt)
553    REAL(r_std), INTENT(in)        :: k_litt(nbpt)         !! Averaged conductivity for saturated infiltration in the 'litter' layer (kg/m^2/dt)
554    REAL(r_std), INTENT(in)        :: humrel(nbpt,nvm)     !! Soil moisture stress, root extraction potential (unitless)
555    REAL(r_std), INTENT(in)        :: stempdiag(nbpt,nslm) !! Diagnostic soil temperature profile
556    REAL(r_std), INTENT(in)        :: reinf_slope(nbpt)    !! Coefficient which determines the reinfiltration ratio in the grid box due to flat areas (unitless;0-1)
557
558    !! 0.2 Output variables
559    REAL(r_std), INTENT(out)       :: returnflow(nbpt)     !! The water flow from lakes and swamps which returns to the grid box.
560                                                           !! This water will go back into the hydrol module to allow re-evaporation (kg/m^2/dt)
561    REAL(r_std), INTENT(out)       :: reinfiltration(nbpt) !! Water flow from ponds and floodplains which returns to the grid box (kg/m^2/dt)
562    REAL(r_std), INTENT(out)       :: irrigation(nbpt)     !! Irrigation flux. This is the water taken from the reservoirs and beeing put into the upper layers of the soil (kg/m^2/dt)
563    REAL(r_std), INTENT(out)       :: riverflow(nbpt)      !! Outflow of the major rivers. The flux will be located on the continental grid but this should be a coastal point (kg/dt)
564    REAL(r_std), INTENT(out)       :: coastalflow(nbpt)    !! Outflow on coastal points by small basins. This is the water which flows in a disperse way into the ocean (kg/dt)
565    REAL(r_std), INTENT(out)       :: flood_frac(nbpt)     !! Flooded fraction of the grid box (unitless;0-1)
566    REAL(r_std), INTENT(out)       :: flood_res(nbpt)      !! Diagnostic of water amount in the floodplains reservoir (kg)
567
568    !! 0.3 Local variables
569    CHARACTER(LEN=30)              :: var_name             !! To store variables names for I/O (unitless)
570    REAL(r_std), DIMENSION(1)      :: tmp_day              !!
571    REAL(r_std), DIMENSION(nbpt)   :: return_lakes         !! Water from lakes flowing back into soil moisture (kg/m^2/dt)
572
573    INTEGER(i_std)                 :: ig, jv               !! Indices (unitless)
574    REAL(r_std), DIMENSION(nbpt)   :: tot_vegfrac_nowoody  !! Total fraction occupied by grass (0-1,unitless)
575
576    REAL(r_std), DIMENSION(nbpt)   :: fast_diag_old        !! Reservoir in the beginning of the time step
577    REAL(r_std), DIMENSION(nbpt)   :: slow_diag_old        !! Reservoir in the beginning of the time step
578    REAL(r_std), DIMENSION(nbpt)   :: stream_diag_old      !! Reservoir in the beginning of the time step
579    REAL(r_std), DIMENSION(nbpt)   :: lake_diag_old        !! Reservoir in the beginning of the time step
580    REAL(r_std), DIMENSION(nbpt)   :: pond_diag_old        !! Reservoir in the beginning of the time step
581    REAL(r_std), DIMENSION(nbpt)   :: flood_diag_old       !! Reservoir in the beginning of the time step
582
583    !! For water budget check in the three routing reservoirs (positive if input > output)
584    !! Net fluxes averaged over each grid cell in kg/m^2/dt
585    REAL(r_std), DIMENSION(nbpt)   :: netflow_stream_diag  !! Input - Output flow to stream reservoir
586    REAL(r_std), DIMENSION(nbpt)   :: netflow_fast_diag    !! Input - Output flow to fast reservoir
587    REAL(r_std), DIMENSION(nbpt)   :: netflow_slow_diag    !! Input - Output flow to slow reservoir
588
589
590!_ ================================================================================================================================
591
592    ! Save reservoirs in beginning of time step to calculate the water budget
593    fast_diag_old   = fast_diag
594    slow_diag_old   = slow_diag
595    stream_diag_old = stream_diag
596    lake_diag_old   = lake_diag
597    pond_diag_old   = pond_diag
598    flood_diag_old  = flood_diag
599
600    !
601    !! Computes the variables averaged between routing time steps and which will be used in subsequent calculations
602    !
603    floodout_mean(:) = floodout_mean(:) + floodout(:)
604    runoff_mean(:) = runoff_mean(:) + runoff(:)
605    drainage_mean(:) = drainage_mean(:) + drainage(:)
606    floodtemp(:) = stempdiag(:,floodtemp_lev)
607    precip_mean(:) =  precip_mean(:) + precip_rain(:)
608    !
609    !! Computes the total fraction occupied by the grasses and the crops for each grid cell
610    tot_vegfrac_nowoody(:) = zero
611    DO jv  = 1, nvm
612       IF ( (jv /= ibare_sechiba) .AND. .NOT.(is_tree(jv)) ) THEN
613          tot_vegfrac_nowoody(:) = tot_vegfrac_nowoody(:) + veget_max(:,jv) 
614       END IF
615    END DO
616
617    DO ig = 1, nbpt
618       IF ( tot_vegfrac_nowoody(ig) .GT. min_sechiba ) THEN
619          DO jv = 1,nvm
620             IF ( (jv /= ibare_sechiba) .AND. .NOT.(is_tree(jv)) ) THEN
621                transpot_mean(ig) = transpot_mean(ig) + transpot(ig,jv) * veget_max(ig,jv)/tot_vegfrac_nowoody(ig) 
622             END IF
623          END DO
624       ELSE
625          IF (MAXVAL(veget_max(ig,2:nvm)) .GT. min_sechiba) THEN
626             DO jv = 2, nvm
627                transpot_mean(ig) = transpot_mean(ig) + transpot(ig,jv) * veget_max(ig,jv)/ SUM(veget_max(ig,2:nvm))
628             ENDDO
629          ENDIF
630       ENDIF
631    ENDDO
632
633    !
634    ! Averaged variables (i.e. *dt_sechiba/dt_routing). This accounts for the difference between the shorter
635    ! timestep dt_sechiba of other parts of the model and the long dt_routing timestep (set to one day at present)
636    !
637    totnobio_mean(:) = totnobio_mean(:) + totfrac_nobio(:)*dt_sechiba/dt_routing
638    k_litt_mean(:) = k_litt_mean(:) + k_litt(:)*dt_sechiba/dt_routing
639    !
640    ! Only potentially vegetated surfaces are taken into account. At the start of
641    ! the growing seasons we will give more weight to these areas.
642    !
643    DO jv=2,nvm
644       DO ig=1,nbpt
645          humrel_mean(ig) = humrel_mean(ig) + humrel(ig,jv)*veget_max(ig,jv)*dt_sechiba/dt_routing
646          vegtot_mean(ig) = vegtot_mean(ig) + veget_max(ig,jv)*dt_sechiba/dt_routing
647       ENDDO
648    ENDDO
649    !
650    time_counter = time_counter + dt_sechiba 
651    !
652    ! If the time has come we do the routing.
653    !
654    IF ( NINT(time_counter) .GE. NINT(dt_routing) ) THEN 
655       !
656       !! Computes the transport of water in the various reservoirs
657       !
658       CALL routing_flow(nbpt, dt_routing, lalo, floodout_mean, runoff_mean, drainage_mean, &
659            & vegtot_mean, totnobio_mean, transpot_mean, precip_mean, humrel_mean, k_litt_mean, floodtemp, reinf_slope, &
660            & lakeinflow_mean, returnflow_mean, reinfiltration_mean, irrigation_mean, riverflow_mean, &
661            & coastalflow_mean, hydrographs, slowflow_diag, flood_frac, flood_res, &
662            & netflow_stream_diag, netflow_fast_diag, netflow_slow_diag)
663       !
664       !! Responsible for storing the water in lakes
665       !
666       CALL routing_lake(nbpt, dt_routing, lakeinflow_mean, humrel_mean, return_lakes)
667       !
668       returnflow_mean(:) = returnflow_mean(:) + return_lakes(:)
669
670       time_counter = zero
671       !
672       floodout_mean(:) = zero
673       runoff_mean(:) = zero
674       drainage_mean(:) = zero
675       transpot_mean(:) = zero
676       precip_mean(:) = zero
677       !
678       humrel_mean(:) = zero
679       totnobio_mean(:) = zero
680       k_litt_mean(:) = zero
681       vegtot_mean(:) = zero
682
683       ! Change the units of the routing fluxes from kg/dt_routing into kg/dt_sechiba
684       hydrographs(:) = hydrographs(:)/dt_routing*dt_sechiba
685       slowflow_diag(:) = slowflow_diag(:)/dt_routing*dt_sechiba
686
687       ! Change the units of the routing fluxes from kg/m^2/dt_routing into kg/m^2/dt_sechiba
688       returnflow_mean(:) = returnflow_mean(:)/dt_routing*dt_sechiba
689       reinfiltration_mean(:) = reinfiltration_mean(:)/dt_routing*dt_sechiba
690       irrigation_mean(:) = irrigation_mean(:)/dt_routing*dt_sechiba
691       irrig_netereq(:) = irrig_netereq(:)/dt_routing*dt_sechiba
692       
693       ! Change units as above but at the same time transform the kg/dt_routing to m^3/dt_sechiba
694       riverflow_mean(:) = riverflow_mean(:)/dt_routing*dt_sechiba/mille
695       coastalflow_mean(:) = coastalflow_mean(:)/dt_routing*dt_sechiba/mille
696
697       ! Water budget residu of the three routing reservoirs (in kg/m^2/s)
698       ! Note that these diagnostics are done using local variables only calculated
699       ! during the time steps when the routing is calculated
700       CALL xios_orchidee_send_field("wbr_stream",(stream_diag - stream_diag_old - netflow_stream_diag)/dt_routing)
701       CALL xios_orchidee_send_field("wbr_fast",  (fast_diag   - fast_diag_old - netflow_fast_diag)/dt_routing)
702       CALL xios_orchidee_send_field("wbr_slow",  (slow_diag   - slow_diag_old - netflow_slow_diag)/dt_routing)
703       CALL xios_orchidee_send_field("wbr_lake",  (lake_diag   - lake_diag_old - &
704                                                   lakeinflow_mean + return_lakes)/dt_routing)
705    ENDIF
706
707    !
708    ! Return the fraction of routed water for this time step.
709    !
710    returnflow(:) = returnflow_mean(:)
711    reinfiltration(:) = reinfiltration_mean(:)
712    irrigation(:) = irrigation_mean(:)
713    riverflow(:) = riverflow_mean(:)
714    coastalflow(:) = coastalflow_mean(:)
715
716    !
717    ! Write diagnostics
718    !
719
720    ! Water storage in reservoirs [kg/m^2]
721    CALL xios_orchidee_send_field("fastr",fast_diag)
722    CALL xios_orchidee_send_field("slowr",slow_diag)
723    CALL xios_orchidee_send_field("streamr",stream_diag)
724    CALL xios_orchidee_send_field("laker",lake_diag)
725    CALL xios_orchidee_send_field("pondr",pond_diag)
726    CALL xios_orchidee_send_field("floodr",flood_diag)
727    CALL xios_orchidee_send_field("floodh",flood_height)
728
729    ! Difference between the end and the beginning of the routing time step [kg/m^2]
730    CALL xios_orchidee_send_field("delfastr",   fast_diag   - fast_diag_old)
731    CALL xios_orchidee_send_field("delslowr",   slow_diag   - slow_diag_old)
732    CALL xios_orchidee_send_field("delstreamr", stream_diag - stream_diag_old)
733    CALL xios_orchidee_send_field("dellaker",   lake_diag   - lake_diag_old)
734    CALL xios_orchidee_send_field("delpondr",   pond_diag   - pond_diag_old)
735    CALL xios_orchidee_send_field("delfloodr",  flood_diag  - flood_diag_old)
736
737    ! Water fluxes converted from kg/m^2/dt_sechiba into kg/m^2/s
738    CALL xios_orchidee_send_field("irrigation",irrigation/dt_sechiba)
739    CALL xios_orchidee_send_field("netirrig",irrig_netereq/dt_sechiba)
740    CALL xios_orchidee_send_field("riversret",returnflow/dt_sechiba)
741    CALL xios_orchidee_send_field("reinfiltration",reinfiltration/dt_sechiba)
742
743    ! Transform from kg/dt_sechiba into m^3/s
744    CALL xios_orchidee_send_field("hydrographs",hydrographs/mille/dt_sechiba)
745    CALL xios_orchidee_send_field("slowflow",slowflow_diag/mille/dt_sechiba) ! previous id name: Qb
746    CALL xios_orchidee_send_field("coastalflow",coastalflow/dt_sechiba)
747    CALL xios_orchidee_send_field("riverflow",riverflow/dt_sechiba)
748
749    IF ( .NOT. almaoutput ) THEN
750       !
751       CALL histwrite_p(hist_id, 'riversret', kjit, returnflow, nbpt, index)
752       IF (do_floodplains .OR. doponds) THEN
753          CALL histwrite_p(hist_id, 'reinfiltration', kjit, reinfiltration, nbpt, index)
754       ENDIF
755       CALL histwrite_p(hist_id, 'hydrographs', kjit, hydrographs/mille, nbpt, index)
756       !
757       CALL histwrite_p(hist_id, 'fastr', kjit, fast_diag, nbpt, index)
758       CALL histwrite_p(hist_id, 'slowr', kjit, slow_diag, nbpt, index)
759       CALL histwrite_p(hist_id, 'streamr', kjit, stream_diag, nbpt, index)
760       IF ( do_floodplains ) THEN
761          CALL histwrite_p(hist_id, 'floodr', kjit, flood_diag, nbpt, index)
762          CALL histwrite_p(hist_id, 'floodh', kjit, flood_height, nbpt, index)
763       ENDIF
764       CALL histwrite_p(hist_id, 'pondr', kjit, pond_diag, nbpt, index)
765       CALL histwrite_p(hist_id, 'lakevol', kjit, lake_diag, nbpt, index)
766       !
767       IF ( do_irrigation ) THEN
768          CALL histwrite_p(hist_id, 'irrigation', kjit, irrigation, nbpt, index)
769          CALL histwrite_p(hist_id, 'returnflow', kjit, returnflow, nbpt, index)
770          CALL histwrite_p(hist_id, 'netirrig', kjit, irrig_netereq, nbpt, index)
771       ENDIF
772       !
773    ELSE
774       CALL histwrite_p(hist_id, 'SurfStor', kjit, flood_diag+pond_diag+lake_diag, nbpt, index)
775       CALL histwrite_p(hist_id, 'Dis', kjit, hydrographs/mille, nbpt, index)
776       !
777       CALL histwrite_p(hist_id, 'slowr', kjit, slow_diag, nbpt, index)
778       CALL histwrite_p(hist_id, 'fastr', kjit, fast_diag, nbpt, index)
779       CALL histwrite_p(hist_id, 'streamr', kjit, stream_diag, nbpt, index)
780       CALL histwrite_p(hist_id, 'lakevol', kjit, lake_diag, nbpt, index)
781       CALL histwrite_p(hist_id, 'pondr', kjit, pond_diag, nbpt, index)
782       !
783       IF ( do_irrigation ) THEN
784          CALL histwrite_p(hist_id, 'Qirrig', kjit, irrigation, nbpt, index)
785          CALL histwrite_p(hist_id, 'Qirrig_req', kjit, irrig_netereq, nbpt, index)
786       ENDIF
787       !
788    ENDIF
789    IF ( hist2_id > 0 ) THEN
790       IF ( .NOT. almaoutput ) THEN
791          !
792          CALL histwrite_p(hist2_id, 'riversret', kjit, returnflow, nbpt, index)
793          IF (do_floodplains .OR. doponds) THEN
794             CALL histwrite_p(hist2_id, 'reinfiltration', kjit, reinfiltration, nbpt, index)
795          ENDIF
796          CALL histwrite_p(hist2_id, 'hydrographs', kjit, hydrographs/mille, nbpt, index)
797          !
798          CALL histwrite_p(hist2_id, 'fastr', kjit, fast_diag, nbpt, index)
799          CALL histwrite_p(hist2_id, 'slowr', kjit, slow_diag, nbpt, index)
800          IF ( do_floodplains ) THEN
801             CALL histwrite_p(hist2_id, 'floodr', kjit, flood_diag, nbpt, index)
802             CALL histwrite_p(hist2_id, 'floodh', kjit, flood_height, nbpt, index)
803          ENDIF
804          CALL histwrite_p(hist2_id, 'pondr', kjit, pond_diag, nbpt, index)
805          CALL histwrite_p(hist2_id, 'streamr', kjit, stream_diag, nbpt, index)
806          CALL histwrite_p(hist2_id, 'lakevol', kjit, lake_diag, nbpt, index)
807          !
808          IF ( do_irrigation ) THEN
809             CALL histwrite_p(hist2_id, 'irrigation', kjit, irrigation, nbpt, index)
810             CALL histwrite_p(hist2_id, 'returnflow', kjit, returnflow, nbpt, index)
811             CALL histwrite_p(hist2_id, 'netirrig', kjit, irrig_netereq, nbpt, index)
812          ENDIF
813          !
814       ELSE
815          !
816          CALL histwrite_p(hist2_id, 'SurfStor', kjit, flood_diag+pond_diag+lake_diag, nbpt, index)
817          CALL histwrite_p(hist2_id, 'Dis', kjit, hydrographs/mille, nbpt, index)
818          !
819       ENDIF
820    ENDIF
821    !
822    !
823  END SUBROUTINE routing_main
824 
825  !!  =============================================================================================================================
826  !! SUBROUTINE:         routing_finalize
827  !!
828  !>\BRIEF               Write to restart file
829  !!
830  !! DESCRIPTION:        Write module variables to restart file
831  !!
832  !! RECENT CHANGE(S)
833  !!
834  !! REFERENCE(S)
835  !!
836  !! FLOWCHART   
837  !! \n
838  !_ ==============================================================================================================================
839
840  SUBROUTINE routing_finalize( kjit, nbpt, rest_id, flood_frac, flood_res )
841   
842    IMPLICIT NONE
843   
844    !! 0.1 Input variables
845    INTEGER(i_std), INTENT(in)     :: kjit                 !! Time step number (unitless)
846    INTEGER(i_std), INTENT(in)     :: nbpt                 !! Domain size (unitless)
847    INTEGER(i_std),INTENT(in)      :: rest_id              !! Restart file identifier (unitless)
848    REAL(r_std), INTENT(in)        :: flood_frac(nbpt)     !! Flooded fraction of the grid box (unitless;0-1)
849    REAL(r_std), INTENT(in)        :: flood_res(nbpt)      !! Diagnostic of water amount in the floodplains reservoir (kg)
850   
851    !! 0.2 Local variables
852    REAL(r_std), DIMENSION(1)      :: tmp_day             
853
854!_ ================================================================================================================================
855   
856    !
857    ! Write restart variables
858    !
859    tmp_day(1) = time_counter
860    IF (is_root_prc) CALL restput (rest_id, 'routingcounter', 1, 1, 1, kjit, tmp_day)
861
862    CALL restput_p (rest_id, 'routingarea', nbp_glo, nbasmax, 1, kjit, routing_area, 'scatter',  nbp_glo, index_g)
863    CALL restput_p (rest_id, 'routetogrid', nbp_glo, nbasmax, 1, kjit, REAL(route_togrid,r_std), 'scatter', &
864         nbp_glo, index_g)
865    CALL restput_p (rest_id, 'routetobasin', nbp_glo, nbasmax, 1, kjit, REAL(route_tobasin,r_std), 'scatter', &
866         nbp_glo, index_g)
867    CALL restput_p (rest_id, 'basinid', nbp_glo, nbasmax, 1, kjit, REAL(global_basinid,r_std), 'scatter', &
868         nbp_glo, index_g)
869    CALL restput_p (rest_id, 'topoindex', nbp_glo, nbasmax, 1, kjit, topo_resid, 'scatter',  nbp_glo, index_g)
870    CALL restput_p (rest_id, 'fastres', nbp_glo, nbasmax, 1, kjit, fast_reservoir, 'scatter',  nbp_glo, index_g)
871    CALL restput_p (rest_id, 'slowres', nbp_glo, nbasmax, 1, kjit, slow_reservoir, 'scatter',  nbp_glo, index_g)
872    CALL restput_p (rest_id, 'streamres', nbp_glo, nbasmax, 1, kjit, stream_reservoir, 'scatter',nbp_glo,index_g)
873    CALL restput_p (rest_id, 'floodres', nbp_glo, nbasmax, 1, kjit, flood_reservoir, 'scatter',  nbp_glo, index_g)
874    CALL restput_p (rest_id, 'floodh', nbp_glo, 1, 1, kjit, flood_height, 'scatter',  nbp_glo, index_g)
875    CALL restput_p (rest_id, 'flood_frac_bas', nbp_glo, nbasmax, 1, kjit, flood_frac_bas, 'scatter',  nbp_glo, index_g)
876    CALL restput_p (rest_id, 'pond_frac', nbp_glo, 1, 1, kjit, pond_frac, 'scatter',  nbp_glo, index_g)
877    CALL restput_p (rest_id, 'flood_frac', nbp_glo, 1, 1, kjit, flood_frac, 'scatter',  nbp_glo, index_g)
878    CALL restput_p (rest_id, 'flood_res', nbp_glo, 1, 1, kjit, flood_res, 'scatter', nbp_glo, index_g)
879
880    CALL restput_p (rest_id, 'lakeres', nbp_glo, 1, 1, kjit, lake_reservoir, 'scatter',  nbp_glo, index_g)
881    CALL restput_p (rest_id, 'pondres', nbp_glo, 1, 1, kjit, pond_reservoir, 'scatter',  nbp_glo, index_g)
882
883    CALL restput_p (rest_id, 'lakeinflow', nbp_glo, 1, 1, kjit, lakeinflow_mean, 'scatter',  nbp_glo, index_g)
884    CALL restput_p (rest_id, 'returnflow', nbp_glo, 1, 1, kjit, returnflow_mean, 'scatter',  nbp_glo, index_g)
885    CALL restput_p (rest_id, 'reinfiltration', nbp_glo, 1, 1, kjit, reinfiltration_mean, 'scatter',  nbp_glo, index_g)
886    CALL restput_p (rest_id, 'riverflow', nbp_glo, 1, 1, kjit, riverflow_mean, 'scatter',  nbp_glo, index_g)
887    CALL restput_p (rest_id, 'coastalflow', nbp_glo, 1, 1, kjit, coastalflow_mean, 'scatter',  nbp_glo, index_g)
888    CALL restput_p (rest_id, 'hydrographs', nbp_glo, 1, 1, kjit, hydrographs, 'scatter',  nbp_glo, index_g)
889    CALL restput_p (rest_id, 'slowflow_diag', nbp_glo, 1, 1, kjit, slowflow_diag, 'scatter',  nbp_glo, index_g)
890    !
891    ! Keep track of the accumulated variables
892    !
893    CALL restput_p (rest_id, 'floodout_route', nbp_glo, 1, 1, kjit, floodout_mean, 'scatter',  nbp_glo, index_g)
894    CALL restput_p (rest_id, 'runoff_route', nbp_glo, 1, 1, kjit, runoff_mean, 'scatter',  nbp_glo, index_g)
895    CALL restput_p (rest_id, 'drainage_route', nbp_glo, 1, 1, kjit, drainage_mean, 'scatter',  nbp_glo, index_g)
896    CALL restput_p (rest_id, 'transpot_route', nbp_glo, 1, 1, kjit, transpot_mean, 'scatter',  nbp_glo, index_g)
897    CALL restput_p (rest_id, 'precip_route', nbp_glo, 1, 1, kjit, precip_mean, 'scatter',  nbp_glo, index_g)
898    CALL restput_p (rest_id, 'humrel_route', nbp_glo, 1, 1, kjit, humrel_mean, 'scatter',  nbp_glo, index_g)
899    CALL restput_p (rest_id, 'totnobio_route', nbp_glo, 1, 1, kjit, totnobio_mean, 'scatter',  nbp_glo, index_g)
900    CALL restput_p (rest_id, 'k_litt_route', nbp_glo, 1, 1, kjit, k_litt_mean, 'scatter',  nbp_glo, index_g)
901    CALL restput_p (rest_id, 'vegtot_route', nbp_glo, 1, 1, kjit, vegtot_mean, 'scatter',  nbp_glo, index_g)
902
903    IF ( do_irrigation ) THEN
904       CALL restput_p (rest_id, 'irrigated', nbp_glo, 1, 1, kjit, irrigated, 'scatter',  nbp_glo, index_g)
905       CALL restput_p (rest_id, 'irrigation', nbp_glo, 1, 1, kjit, irrigation_mean, 'scatter',  nbp_glo, index_g)
906    ENDIF
907
908    IF ( do_floodplains ) THEN
909       CALL restput_p (rest_id, 'floodplains', nbp_glo, 1, 1, kjit, floodplains, 'scatter',  nbp_glo, index_g)
910    ENDIF
911    IF ( doswamps ) THEN
912       CALL restput_p (rest_id, 'swamp', nbp_glo, 1, 1, kjit, swamp, 'scatter',  nbp_glo, index_g)
913    ENDIF
914 
915  END SUBROUTINE routing_finalize
916
917!! ================================================================================================================================
918!! SUBROUTINE   : routing_init
919!!
920!>\BRIEF         This subroutine allocates the memory and get the fixed fields from the restart file.
921!!
922!! DESCRIPTION (definitions, functional, design, flags) : None
923!!
924!! RECENT CHANGE(S): None
925!!
926!! MAIN OUTPUT VARIABLE(S):
927!!
928!! REFERENCES   : None
929!!
930!! FLOWCHART    :None
931!! \n
932!_ ================================================================================================================================
933
934  SUBROUTINE routing_init(kjit, nbpt, index, returnflow, reinfiltration, irrigation, &
935       &                  riverflow, coastalflow, flood_frac, flood_res, stempdiag, rest_id)
936    !
937    IMPLICIT NONE
938    !
939    ! interface description
940    !
941!! INPUT VARIABLES
942    INTEGER(i_std), INTENT(in)                   :: kjit           !! Time step number (unitless)
943    INTEGER(i_std), INTENT(in)                   :: nbpt           !! Domain size (unitless)
944    INTEGER(i_std), DIMENSION (nbpt), INTENT(in) :: index          !! Indices of the points on the map (unitless)
945    REAL(r_std), DIMENSION(nbpt,nslm),INTENT(in) :: stempdiag      !! Temperature profile in soil
946    INTEGER(i_std), INTENT(in)                   :: rest_id        !! Restart file identifier (unitless)
947    !
948!! OUTPUT VARIABLES
949    REAL(r_std), DIMENSION (nbpt),INTENT(out)    :: returnflow     !! The water flow from lakes and swamps which returns into the grid box.
950                                                                   !! This water will go back into the hydrol module to allow re-evaporation (kg/m^2/dt)
951    REAL(r_std), DIMENSION (nbpt),INTENT(out)    :: reinfiltration !! Water flow from ponds and floodplains which returns to the grid box (kg/m^2/dt)
952    REAL(r_std), DIMENSION (nbpt),INTENT(out)    :: irrigation     !! Irrigation flux. This is the water taken from the reservoirs and beeing put into the upper layers of the soil.(kg/m^2/dt)
953    REAL(r_std), DIMENSION (nbpt),INTENT(out)    :: riverflow      !! Outflow of the major rivers. The flux will be located on the continental grid but this should be a coastal point (kg/dt)
954    REAL(r_std), DIMENSION (nbpt),INTENT(out)    :: coastalflow    !! Outflow on coastal points by small basins. This is the water which flows in a disperse way into the ocean (kg/dt)
955    REAL(r_std), DIMENSION (nbpt),INTENT(out)    :: flood_frac     !! Flooded fraction of the grid box (unitless;0-1)
956    REAL(r_std), DIMENSION (nbpt),INTENT(out)    :: flood_res      !! Diagnostic of water amount in the floodplains reservoir (kg)
957    !
958!! LOCAL VARIABLES
959    CHARACTER(LEN=80)                            :: var_name       !! To store variables names for I/O (unitless)
960    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: tmp_real_g     !! A temporary real array for the integers
961    REAL(r_std), DIMENSION(1)                    :: tmp_day        !!
962    REAL(r_std)                                  :: ratio          !! Diagnostic ratio to check that dt_routing is a multiple of dt_sechiba (unitless)
963    REAL(r_std)                                  :: totarea        !! Total area of basin (m^2)
964    INTEGER(i_std)                               :: ier, ig, ib, ipn(1) !! Indices (unitless)
965
966!_ ================================================================================================================================
967    !
968    !
969    ! These variables will require the configuration infrastructure
970    !
971    !Config Key   = DT_ROUTING
972    !Config If    = RIVER_ROUTING
973    !Config Desc  = Time step of the routing scheme
974    !Config Def   = one_day
975    !Config Help  = This values gives the time step in seconds of the routing scheme.
976    !Config         It should be multiple of the main time step of ORCHIDEE. One day
977    !Config         is a good value.
978    !Config Units = [seconds]
979    !
980    dt_routing = one_day
981    CALL getin_p('DT_ROUTING', dt_routing)
982    !
983    !Config Key   = ROUTING_RIVERS
984    !Config If    = RIVER_ROUTING
985    !Config Desc  = Number of rivers
986    !Config Def   = 50
987    !Config Help  = This parameter chooses the number of largest river basins
988    !Config         which should be treated as independently as rivers and not
989    !Config         flow into the oceans as diffusion coastal flow.
990    !Config Units = [-]
991    num_largest = 50
992    CALL getin_p('ROUTING_RIVERS', num_largest)
993    !
994    !Config Key   = DO_FLOODINFILT
995    !Config Desc  = Should floodplains reinfiltrate into the soil
996    !Config If    = RIVER_ROUTING
997    !Config Def   = n
998    !Config Help  = This parameters allows the user to ask the model
999    !Config         to take into account the flood plains reinfiltration
1000    !Config         into the soil moisture. It then can go
1001    !Config         back to the slow and fast reservoirs
1002    !Config Units = [FLAG]
1003    !
1004    dofloodinfilt = .FALSE.
1005    CALL getin_p('DO_FLOODINFILT', dofloodinfilt)
1006    !
1007    !Config Key   = DO_SWAMPS
1008    !Config Desc  = Should we include swamp parameterization
1009    !Config If    = RIVER_ROUTING
1010    !Config Def   = n
1011    !Config Help  = This parameters allows the user to ask the model
1012    !Config         to take into account the swamps and return
1013    !Config         the water into the bottom of the soil. It then can go
1014    !Config         back to the atmopshere. This tried to simulate
1015    !Config         internal deltas of rivers.
1016    !Config Units = [FLAG]
1017    !
1018    doswamps = .FALSE.
1019    CALL getin_p('DO_SWAMPS', doswamps)
1020    !
1021    !Config Key   = DO_PONDS
1022    !Config Desc  = Should we include ponds
1023    !Config If    = RIVER_ROUTING
1024    !Config Def   = n
1025    !Config Help  = This parameters allows the user to ask the model
1026    !Config         to take into account the ponds and return
1027    !Config         the water into the soil moisture. It then can go
1028    !Config         back to the atmopshere. This tried to simulate
1029    !Config         little ponds especially in West Africa.
1030    !Config Units = [FLAG]
1031    !
1032    doponds = .FALSE.
1033    CALL getin_p('DO_PONDS', doponds)
1034
1035
1036    !Config Key   = SLOW_TCST
1037    !Config Desc  = Time constant for the slow reservoir
1038    !Config If    = RIVER_ROUTING
1039    !Config Def   = 25.0
1040    !Config Help  = This parameters allows the user to fix the
1041    !Config         time constant (in days) of the slow reservoir
1042    !Config         in order to get better river flows for
1043    !Config         particular regions.
1044    !Config Units = [days]
1045    !
1046!> A value for property of each reservoir (in day/m) is given to compute a time constant (in day)
1047!> for each reservoir (product of tcst and topo_resid).
1048!> The value of tcst has been calibrated for the three reservoirs over the Senegal river basin only,
1049!> during the 1 degree NCEP Corrected by Cru (NCC) resolution simulations (Ngo-Duc et al., 2005, Ngo-Duc et al., 2006) and
1050!> generalized for all the basins of the world. The "slow reservoir" and the "fast reservoir"
1051!> have the highest value in order to simulate the groundwater.
1052!> The "stream reservoir", which represents all the water of the stream, has the lowest value.
1053!> Those figures are the same for all the basins of the world.
1054!> The value of slow_tcst is equal to fast_tcst when CWRR is activated.
1055!> This assumption should be re-discussed.
1056    !
1057    CALL getin_p('SLOW_TCST', slow_tcst)
1058    !
1059    !Config Key   = FAST_TCST
1060    !Config Desc  = Time constant for the fast reservoir
1061    !Config If    = RIVER_ROUTING
1062    !Config Def   = 3.0
1063    !Config Help  = This parameters allows the user to fix the
1064    !Config         time constant (in days) of the fast reservoir
1065    !Config         in order to get better river flows for
1066    !Config         particular regions.
1067    !Config Units = [days]
1068    CALL getin_p('FAST_TCST', fast_tcst)
1069   
1070    !Config Key   = STREAM_TCST
1071    !Config Desc  = Time constant for the stream reservoir
1072    !Config If    = RIVER_ROUTING
1073    !Config Def   = 0.24
1074    !Config Help  = This parameters allows the user to fix the
1075    !Config         time constant (in days) of the stream reservoir
1076    !Config         in order to get better river flows for
1077    !Config         particular regions.
1078    !Config Units = [days]
1079    CALL getin_p('STREAM_TCST', stream_tcst)
1080   
1081    !Config Key   = FLOOD_TCST
1082    !Config Desc  = Time constant for the flood reservoir
1083    !Config If    = RIVER_ROUTING
1084    !Config Def   = 4.0
1085    !Config Help  = This parameters allows the user to fix the
1086    !Config         time constant (in days) of the flood reservoir
1087    !Config         in order to get better river flows for
1088    !Config         particular regions.
1089    !Config Units = [days]
1090    CALL getin_p('FLOOD_TCST', flood_tcst)
1091   
1092    !Config Key   = SWAMP_CST
1093    !Config Desc  = Fraction of the river that flows back to swamps
1094    !Config If    = RIVER_ROUTING
1095    !Config Def   = 0.2
1096    !Config Help  = This parameters allows the user to fix the
1097    !Config         fraction of the river transport
1098    !Config         that flows to swamps
1099    !Config Units = [-]
1100    CALL getin_p('SWAMP_CST', swamp_cst)
1101   
1102    !Config Key   = FLOOD_BETA
1103    !Config Desc  = Parameter to fix the shape of the floodplain 
1104    !Config If    = RIVER_ROUTING
1105    !Config Def   = 2.0
1106    !Config Help  = Parameter to fix the shape of the floodplain
1107    !Config         (>1 for convex edges, <1 for concave edges)
1108    !Config Units = [-]
1109    CALL getin_p("FLOOD_BETA", beta)
1110    !
1111    !Config Key   = POND_BETAP
1112    !Config Desc  = Ratio of the basin surface intercepted by ponds and the maximum surface of ponds
1113    !Config If    = RIVER_ROUTING
1114    !Config Def   = 0.5
1115    !Config Help  =
1116    !Config Units = [-]
1117    CALL getin_p("POND_BETAP", betap)   
1118    !
1119    !Config Key   = FLOOD_CRI
1120    !Config Desc  = Potential height for which all the basin is flooded
1121    !Config If    = DO_FLOODPLAINS or DO_PONDS
1122    !Config Def   = 2000.
1123    !Config Help  =
1124    !Config Units = [mm]
1125    CALL getin_p("FLOOD_CRI", floodcri)
1126    !
1127    !Config Key   = POND_CRI
1128    !Config Desc  = Potential height for which all the basin is a pond
1129    !Config If    = DO_FLOODPLAINS or DO_PONDS
1130    !Config Def   = 2000.
1131    !Config Help  =
1132    !Config Units = [mm]
1133    CALL getin_p("POND_CRI", pondcri)
1134
1135    !Config Key   = MAX_LAKE_RESERVOIR
1136    !Config Desc  = Maximum limit of water in lake_reservoir
1137    !Config If    = RIVER_ROUTING
1138    !Config Def   = 7000
1139    !Config Help  =
1140    !Config Units = [kg/m2(routing area)]
1141    max_lake_reservoir = 7000
1142    CALL getin_p("MAX_LAKE_RESERVOIR", max_lake_reservoir)
1143
1144    !
1145    !
1146    ! In order to simplify the time cascade check that dt_routing
1147    ! is a multiple of dt_sechiba
1148    !
1149    ratio = dt_routing/dt_sechiba
1150    IF ( ABS(NINT(ratio) - ratio) .GT. 10*EPSILON(ratio)) THEN
1151       WRITE(numout,*) 'WARNING -- WARNING -- WARNING -- WARNING'
1152       WRITE(numout,*) "The chosen time step for the routing is not a multiple of the"
1153       WRITE(numout,*) "main time step of the model. We will change dt_routing so that"
1154       WRITE(numout,*) "this condition os fulfilled"
1155       dt_routing = NINT(ratio) * dt_sechiba
1156       WRITE(numout,*) 'THE NEW DT_ROUTING IS : ', dt_routing
1157    ENDIF
1158    !
1159    IF ( dt_routing .LT. dt_sechiba) THEN
1160       WRITE(numout,*) 'WARNING -- WARNING -- WARNING -- WARNING'
1161       WRITE(numout,*) 'The routing timestep can not be smaller than the one'
1162       WRITE(numout,*) 'of the model. We reset its value to the model''s timestep.'
1163       WRITE(numout,*) 'The old DT_ROUTING is : ', dt_routing
1164       dt_routing = dt_sechiba
1165       WRITE(numout,*) 'THE NEW DT_ROUTING IS : ', dt_routing
1166    ENDIF
1167    !
1168    var_name ="routingcounter"
1169    IF (is_root_prc) THEN
1170       CALL ioconf_setatt('UNITS', 's')
1171       CALL ioconf_setatt('LONG_NAME','Time counter for the routing scheme')
1172       CALL restget (rest_id, var_name, 1, 1, 1, kjit, .TRUE., tmp_day)
1173       IF (tmp_day(1) == val_exp) THEN
1174          ! The variable was not found in restart file, initialize to zero
1175          time_counter = zero
1176       ELSE
1177          ! Take the value from restart file
1178          time_counter = tmp_day(1) 
1179       ENDIF
1180    ENDIF
1181    CALL bcast(time_counter)
1182
1183   
1184    ALLOCATE (routing_area_loc(nbpt,nbasmax), stat=ier)
1185    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for routing_area_loc','','')
1186
1187    ALLOCATE (routing_area_glo(nbp_glo,nbasmax))
1188    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for routing_area_glo','','')
1189    var_name = 'routingarea'
1190    IF (is_root_prc) THEN
1191       CALL ioconf_setatt('UNITS', 'm^2')
1192       CALL ioconf_setatt('LONG_NAME','Area of basin')
1193       CALL restget (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., routing_area_glo, "gather", nbp_glo, index_g)
1194    ENDIF
1195    CALL scatter(routing_area_glo,routing_area_loc)
1196    routing_area=>routing_area_loc
1197
1198    ALLOCATE (tmp_real_g(nbp_glo,nbasmax), stat=ier)
1199    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for tmp_real_g','','')
1200
1201    ALLOCATE (route_togrid_loc(nbpt,nbasmax), stat=ier)
1202    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for route_togrid_loc','','')
1203    ALLOCATE (route_togrid_glo(nbp_glo,nbasmax), stat=ier)      ! used in global in routing_flow
1204    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for route_togrid_glo','','')
1205
1206    IF (is_root_prc) THEN
1207       var_name = 'routetogrid'
1208       CALL ioconf_setatt('UNITS', '-')
1209       CALL ioconf_setatt('LONG_NAME','Grid into which the basin flows')
1210       CALL restget (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., tmp_real_g, "gather", nbp_glo, index_g)
1211       route_togrid_glo(:,:) = undef_int
1212       WHERE ( tmp_real_g .LT. val_exp )
1213          route_togrid_glo = NINT(tmp_real_g)
1214    ENDWHERE
1215    ENDIF
1216    CALL bcast(route_togrid_glo)                      ! used in global in routing_flow
1217    CALL scatter(route_togrid_glo,route_togrid_loc)
1218    route_togrid=>route_togrid_loc
1219    !
1220    ALLOCATE (route_tobasin_loc(nbpt,nbasmax), stat=ier)
1221    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for route_tobasin_loc','','')
1222
1223    ALLOCATE (route_tobasin_glo(nbp_glo,nbasmax), stat=ier)
1224    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for route_tobasin_glo','','')
1225
1226    IF (is_root_prc) THEN
1227       var_name = 'routetobasin'
1228       CALL ioconf_setatt('UNITS', '-')
1229       CALL ioconf_setatt('LONG_NAME','Basin in to which the water goes')
1230       CALL restget (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., tmp_real_g, "gather", nbp_glo, index_g)
1231       route_tobasin_glo = undef_int
1232       WHERE ( tmp_real_g .LT. val_exp )
1233         route_tobasin_glo = NINT(tmp_real_g)
1234      ENDWHERE
1235    ENDIF
1236    CALL scatter(route_tobasin_glo,route_tobasin_loc)
1237    route_tobasin=>route_tobasin_loc
1238    !
1239    ! nbintobasin
1240    !
1241    ALLOCATE (route_nbintobas_loc(nbpt,nbasmax), stat=ier)
1242    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for route_nbintobas_loc','','')
1243    ALLOCATE (route_nbintobas_glo(nbp_glo,nbasmax), stat=ier)
1244    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for route_nbintobas_glo','','')
1245
1246    IF (is_root_prc) THEN
1247       var_name = 'routenbintobas'
1248       CALL ioconf_setatt('UNITS', '-')
1249       CALL ioconf_setatt('LONG_NAME','Number of basin into current one')
1250       CALL restget (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., tmp_real_g, "gather", nbp_glo, index_g)
1251       route_nbintobas_glo = undef_int
1252       WHERE ( tmp_real_g .LT. val_exp )
1253         route_nbintobas_glo = NINT(tmp_real_g)
1254      ENDWHERE
1255    ENDIF
1256    CALL scatter(route_nbintobas_glo,route_nbintobas_loc)
1257    route_nbintobas=>route_nbintobas_loc
1258    !
1259    ALLOCATE (global_basinid_loc(nbpt,nbasmax), stat=ier)
1260    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for global_basinid_loc','','')
1261    ALLOCATE (global_basinid_glo(nbp_glo,nbasmax), stat=ier)
1262    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for global_basinid_glo','','')
1263
1264    IF (is_root_prc) THEN
1265       var_name = 'basinid'
1266       CALL ioconf_setatt('UNITS', '-')
1267       CALL ioconf_setatt('LONG_NAME','ID of basin')
1268       CALL restget (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., tmp_real_g, "gather", nbp_glo, index_g)
1269       global_basinid_glo = undef_int
1270       WHERE ( tmp_real_g .LT. val_exp )
1271          global_basinid_glo = NINT(tmp_real_g)
1272       ENDWHERE
1273    ENDIF
1274    CALL scatter(global_basinid_glo,global_basinid_loc)
1275    global_basinid=>global_basinid_loc
1276    !
1277    ALLOCATE (topo_resid_loc(nbpt,nbasmax), stat=ier)
1278    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for topo_resid_loc','','')
1279    ALLOCATE (topo_resid_glo(nbp_glo,nbasmax), stat=ier)
1280    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for topo_resid_glo','','')
1281
1282    IF (is_root_prc) THEN
1283       var_name = 'topoindex'
1284       CALL ioconf_setatt('UNITS', 'm')
1285       CALL ioconf_setatt('LONG_NAME','Topographic index of the residence time')
1286       CALL restget (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., topo_resid_glo, "gather", nbp_glo, index_g)
1287    ENDIF
1288    CALL scatter(topo_resid_glo,topo_resid_loc)
1289    topo_resid=>topo_resid_loc
1290
1291    ALLOCATE (fast_reservoir(nbpt,nbasmax), stat=ier)
1292    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for fast_reservoir','','')
1293    var_name = 'fastres'
1294    CALL ioconf_setatt_p('UNITS', 'Kg')
1295    CALL ioconf_setatt_p('LONG_NAME','Water in the fast reservoir')
1296    CALL restget_p (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., fast_reservoir, "gather", nbp_glo, index_g)
1297    CALL setvar_p (fast_reservoir, val_exp, 'NO_KEYWORD', zero)
1298
1299    ALLOCATE (slow_reservoir(nbpt,nbasmax), stat=ier)
1300    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for slow_reservoir','','')
1301    var_name = 'slowres'
1302    CALL ioconf_setatt_p('UNITS', 'Kg')
1303    CALL ioconf_setatt_p('LONG_NAME','Water in the slow reservoir')
1304    CALL restget_p (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., slow_reservoir, "gather", nbp_glo, index_g)
1305    CALL setvar_p (slow_reservoir, val_exp, 'NO_KEYWORD', zero)
1306
1307    ALLOCATE (stream_reservoir(nbpt,nbasmax), stat=ier)
1308    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for stream_reservoir','','')
1309    var_name = 'streamres'
1310    CALL ioconf_setatt_p('UNITS', 'Kg')
1311    CALL ioconf_setatt_p('LONG_NAME','Water in the stream reservoir')
1312    CALL restget_p (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., stream_reservoir, "gather", nbp_glo, index_g)
1313    CALL setvar_p (stream_reservoir, val_exp, 'NO_KEYWORD', zero)
1314
1315    ALLOCATE (flood_reservoir(nbpt,nbasmax), stat=ier)
1316    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for flood_reservoir','','')
1317    var_name = 'floodres'
1318    CALL ioconf_setatt_p('UNITS', 'Kg')
1319    CALL ioconf_setatt_p('LONG_NAME','Water in the flood reservoir')
1320    CALL restget_p (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., flood_reservoir, "gather", nbp_glo, index_g)
1321    CALL setvar_p (flood_reservoir, val_exp, 'NO_KEYWORD', zero)
1322
1323    ALLOCATE (flood_frac_bas(nbpt,nbasmax), stat=ier)
1324    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for flood_frac_bas','','')
1325    var_name = 'flood_frac_bas'
1326    CALL ioconf_setatt_p('UNITS', '-')
1327    CALL ioconf_setatt_p('LONG_NAME','Flooded fraction per basin')
1328    CALL restget_p (rest_id, var_name, nbp_glo, nbasmax, 1, kjit, .TRUE., flood_frac_bas, "gather", nbp_glo, index_g)
1329    CALL setvar_p (flood_frac_bas, val_exp, 'NO_KEYWORD', zero)
1330
1331    ALLOCATE (flood_height(nbpt), stat=ier)
1332    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for flood_height','','')
1333    var_name = 'floodh'
1334    CALL ioconf_setatt_p('UNITS', '-')
1335    CALL ioconf_setatt_p('LONG_NAME','')
1336    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., flood_height, "gather", nbp_glo, index_g)
1337    CALL setvar_p (flood_height, val_exp, 'NO_KEYWORD', zero)
1338   
1339    ALLOCATE (pond_frac(nbpt), stat=ier)
1340    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for pond_frac','','')
1341    var_name = 'pond_frac'
1342    CALL ioconf_setatt_p('UNITS', '-')
1343    CALL ioconf_setatt_p('LONG_NAME','Pond fraction per grid box')
1344    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., pond_frac, "gather", nbp_glo, index_g)
1345    CALL setvar_p (pond_frac, val_exp, 'NO_KEYWORD', zero)
1346   
1347    var_name = 'flood_frac'
1348    CALL ioconf_setatt_p('UNITS', '-')
1349    CALL ioconf_setatt_p('LONG_NAME','Flooded fraction per grid box')
1350    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., flood_frac, "gather", nbp_glo, index_g)
1351    CALL setvar_p (flood_frac, val_exp, 'NO_KEYWORD', zero)
1352   
1353    var_name = 'flood_res'
1354    CALL ioconf_setatt_p('UNITS','mm')
1355    CALL ioconf_setatt_p('LONG_NAME','Flooded quantity (estimation)')
1356    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., flood_res, "gather", nbp_glo, index_g)
1357    CALL setvar_p (flood_res, val_exp, 'NO_KEYWORD', zero)
1358!    flood_res = zero
1359   
1360    ALLOCATE (lake_reservoir(nbpt), stat=ier)
1361    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for lake_reservoir','','')
1362    var_name = 'lakeres'
1363    CALL ioconf_setatt_p('UNITS', 'Kg')
1364    CALL ioconf_setatt_p('LONG_NAME','Water in the lake reservoir')
1365    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., lake_reservoir, "gather", nbp_glo, index_g)
1366    CALL setvar_p (lake_reservoir, val_exp, 'NO_KEYWORD', zero)
1367   
1368    ALLOCATE (pond_reservoir(nbpt), stat=ier)
1369    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for pond_reservoir','','')
1370    var_name = 'pondres'
1371    CALL ioconf_setatt_p('UNITS', 'Kg')
1372    CALL ioconf_setatt_p('LONG_NAME','Water in the pond reservoir')
1373    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., pond_reservoir, "gather", nbp_glo, index_g)
1374    CALL setvar_p (pond_reservoir, val_exp, 'NO_KEYWORD', zero)
1375    !
1376    ! Map of irrigated areas
1377    !
1378    IF ( do_irrigation ) THEN
1379       ALLOCATE (irrigated(nbpt), stat=ier)
1380       IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for irrigated','','')
1381       var_name = 'irrigated'
1382       CALL ioconf_setatt_p('UNITS', 'm^2')
1383       CALL ioconf_setatt_p('LONG_NAME','Surface of irrigated area')
1384       CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., irrigated, "gather", nbp_glo, index_g)
1385       CALL setvar_p (irrigated, val_exp, 'NO_KEYWORD', undef_sechiba)
1386    ENDIF
1387   
1388    IF ( do_floodplains ) THEN
1389       ALLOCATE (floodplains(nbpt), stat=ier)
1390       IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for floodplains','','')
1391       var_name = 'floodplains'
1392       CALL ioconf_setatt_p('UNITS', 'm^2')
1393       CALL ioconf_setatt_p('LONG_NAME','Surface which can be flooded')
1394       CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., floodplains, "gather", nbp_glo, index_g)
1395       CALL setvar_p (floodplains, val_exp, 'NO_KEYWORD', undef_sechiba)
1396    ENDIF
1397    IF ( doswamps ) THEN
1398       ALLOCATE (swamp(nbpt), stat=ier)
1399       IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for swamp','','')
1400       var_name = 'swamp'
1401       CALL ioconf_setatt_p('UNITS', 'm^2')
1402       CALL ioconf_setatt_p('LONG_NAME','Surface which can become swamp')
1403       CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., swamp, "gather", nbp_glo, index_g)
1404       CALL setvar_p (swamp, val_exp, 'NO_KEYWORD', undef_sechiba)
1405    ENDIF
1406    !
1407    ! Put into the restart file the fluxes so that they can be regenerated at restart.
1408    !
1409    ALLOCATE (lakeinflow_mean(nbpt), stat=ier)
1410    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for lakeinflow_mean','','')
1411    var_name = 'lakeinflow'
1412    CALL ioconf_setatt_p('UNITS', 'Kg/dt')
1413    CALL ioconf_setatt_p('LONG_NAME','Lake inflow')
1414    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., lakeinflow_mean, "gather", nbp_glo, index_g)
1415    CALL setvar_p (lakeinflow_mean, val_exp, 'NO_KEYWORD', zero)
1416   
1417    ALLOCATE (returnflow_mean(nbpt), stat=ier)
1418    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for returnflow_mean','','')
1419    var_name = 'returnflow'
1420    CALL ioconf_setatt_p('UNITS', 'Kg/m^2/dt')
1421    CALL ioconf_setatt_p('LONG_NAME','Deep return flux')
1422    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., returnflow_mean, "gather", nbp_glo, index_g)
1423    CALL setvar_p (returnflow_mean, val_exp, 'NO_KEYWORD', zero)
1424    returnflow(:) = returnflow_mean(:)
1425   
1426    ALLOCATE (reinfiltration_mean(nbpt), stat=ier)
1427    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for reinfiltration_mean','','')
1428    var_name = 'reinfiltration'
1429    CALL ioconf_setatt_p('UNITS', 'Kg/m^2/dt')
1430    CALL ioconf_setatt_p('LONG_NAME','Top return flux')
1431    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., reinfiltration_mean, "gather", nbp_glo, index_g)
1432    CALL setvar_p (reinfiltration_mean, val_exp, 'NO_KEYWORD', zero)
1433    reinfiltration(:) = reinfiltration_mean(:)
1434   
1435    ALLOCATE (irrigation_mean(nbpt), stat=ier)
1436    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for irrigation_mean','','')
1437    ALLOCATE (irrig_netereq(nbpt), stat=ier)
1438    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for irrig_netereq','','')
1439    irrig_netereq(:) = zero
1440   
1441    IF ( do_irrigation ) THEN
1442       var_name = 'irrigation'
1443       CALL ioconf_setatt_p('UNITS', 'Kg/dt')
1444       CALL ioconf_setatt_p('LONG_NAME','Artificial irrigation flux')
1445       CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., irrigation_mean, "gather", nbp_glo, index_g)
1446       CALL setvar_p (irrigation_mean, val_exp, 'NO_KEYWORD', zero)
1447    ELSE
1448       irrigation_mean(:) = zero
1449    ENDIF
1450    irrigation(:) = irrigation_mean(:) 
1451   
1452    ALLOCATE (riverflow_mean(nbpt), stat=ier)
1453    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for riverflow_mean','','')
1454    var_name = 'riverflow'
1455    CALL ioconf_setatt_p('UNITS', 'Kg/dt')
1456    CALL ioconf_setatt_p('LONG_NAME','River flux into the sea')
1457    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., riverflow_mean, "gather", nbp_glo, index_g)
1458    CALL setvar_p (riverflow_mean, val_exp, 'NO_KEYWORD', zero)
1459    riverflow(:) = riverflow_mean(:)
1460   
1461    ALLOCATE (coastalflow_mean(nbpt), stat=ier)
1462    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for coastalflow_mean','','')
1463    var_name = 'coastalflow'
1464    CALL ioconf_setatt_p('UNITS', 'Kg/dt')
1465    CALL ioconf_setatt_p('LONG_NAME','Diffuse flux into the sea')
1466    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., coastalflow_mean, "gather", nbp_glo, index_g)
1467    CALL setvar_p (coastalflow_mean, val_exp, 'NO_KEYWORD', zero)
1468    coastalflow(:) = coastalflow_mean(:)
1469   
1470    ! Locate it at the 2m level
1471    ipn = MINLOC(ABS(diaglev-2))
1472    floodtemp_lev = ipn(1)
1473    ALLOCATE (floodtemp(nbpt), stat=ier)
1474    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for floodtemp','','')
1475    floodtemp(:) = stempdiag(:,floodtemp_lev)
1476   
1477    ALLOCATE(hydrographs(nbpt), stat=ier)
1478    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for hydrographs','','')
1479    var_name = 'hydrographs'
1480    CALL ioconf_setatt_p('UNITS', 'kg/dt_sechiba')
1481    CALL ioconf_setatt_p('LONG_NAME','Hydrograph at outlow of grid')
1482    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., hydrographs, "gather", nbp_glo, index_g)
1483    CALL setvar_p (hydrographs, val_exp, 'NO_KEYWORD', zero)
1484 
1485    ALLOCATE(slowflow_diag(nbpt), stat=ier)
1486    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for slowflow_diag','','')
1487    var_name = 'slowflow_diag'
1488    CALL ioconf_setatt_p('UNITS', 'kg/dt_sechiba')
1489    CALL ioconf_setatt_p('LONG_NAME','Slowflow hydrograph at outlow of grid')
1490    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE.,slowflow_diag, "gather", nbp_glo, index_g)
1491    CALL setvar_p (slowflow_diag, val_exp, 'NO_KEYWORD', zero)
1492
1493    !
1494    ! The diagnostic variables, they are initialized from the above restart variables.
1495    !
1496    ALLOCATE(fast_diag(nbpt), slow_diag(nbpt), stream_diag(nbpt), flood_diag(nbpt), &
1497         & pond_diag(nbpt), lake_diag(nbpt), stat=ier)
1498    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for fast_diag,..','','')
1499   
1500    fast_diag(:) = zero
1501    slow_diag(:) = zero
1502    stream_diag(:) = zero
1503    flood_diag(:) = zero
1504    pond_diag(:) = zero
1505    lake_diag(:) = zero
1506   
1507    DO ig=1,nbpt
1508       totarea = zero
1509       DO ib=1,nbasmax
1510          totarea = totarea + routing_area(ig,ib)
1511          fast_diag(ig) = fast_diag(ig) + fast_reservoir(ig,ib)
1512          slow_diag(ig) = slow_diag(ig) + slow_reservoir(ig,ib)
1513          stream_diag(ig) = stream_diag(ig) + stream_reservoir(ig,ib)
1514          flood_diag(ig) = flood_diag(ig) + flood_reservoir(ig,ib)
1515       ENDDO
1516       !
1517       fast_diag(ig) = fast_diag(ig)/totarea
1518       slow_diag(ig) = slow_diag(ig)/totarea
1519       stream_diag(ig) = stream_diag(ig)/totarea
1520       flood_diag(ig) = flood_diag(ig)/totarea
1521       !
1522       ! This is the volume of the lake scaled to the entire grid.
1523       ! It would be better to scale it to the size of the lake
1524       ! but this information is not yet available.
1525       !
1526       lake_diag(ig) = lake_reservoir(ig)/totarea
1527       !
1528    ENDDO
1529    !
1530    ! Get from the restart the fluxes we accumulated.
1531    !
1532    ALLOCATE (floodout_mean(nbpt), stat=ier)
1533    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for floodout_mean','','')
1534    var_name = 'floodout_route'
1535    CALL ioconf_setatt_p('UNITS', 'Kg')
1536    CALL ioconf_setatt_p('LONG_NAME','Accumulated flow out of floodplains for routing')
1537    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., floodout_mean, "gather", nbp_glo, index_g)
1538    CALL setvar_p (floodout_mean, val_exp, 'NO_KEYWORD', zero)
1539   
1540    ALLOCATE (runoff_mean(nbpt), stat=ier)
1541    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for runoff_mean','','')
1542    var_name = 'runoff_route'
1543    CALL ioconf_setatt_p('UNITS', 'Kg')
1544    CALL ioconf_setatt_p('LONG_NAME','Accumulated runoff for routing')
1545    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., runoff_mean, "gather", nbp_glo, index_g)
1546    CALL setvar_p (runoff_mean, val_exp, 'NO_KEYWORD', zero)
1547   
1548    ALLOCATE(drainage_mean(nbpt), stat=ier)
1549    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for drainage_mean','','')
1550    var_name = 'drainage_route'
1551    CALL ioconf_setatt_p('UNITS', 'Kg')
1552    CALL ioconf_setatt_p('LONG_NAME','Accumulated drainage for routing')
1553    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., drainage_mean, "gather", nbp_glo, index_g)
1554    CALL setvar_p (drainage_mean, val_exp, 'NO_KEYWORD', zero)
1555   
1556    ALLOCATE(transpot_mean(nbpt), stat=ier)
1557    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for transpot_mean','','')
1558    var_name = 'transpot_route'
1559    CALL ioconf_setatt_p('UNITS', 'Kg/m^2')
1560    CALL ioconf_setatt_p('LONG_NAME','Accumulated potential transpiration for routing/irrigation')
1561    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., transpot_mean, "gather", nbp_glo, index_g)
1562    CALL setvar_p (transpot_mean, val_exp, 'NO_KEYWORD', zero)
1563
1564    ALLOCATE(precip_mean(nbpt), stat=ier)
1565    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for precip_mean','','')
1566    var_name = 'precip_route'
1567    CALL ioconf_setatt_p('UNITS', 'Kg/m^2')
1568    CALL ioconf_setatt_p('LONG_NAME','Accumulated rain precipitation for irrigation')
1569    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., precip_mean, "gather", nbp_glo, index_g)
1570    CALL setvar_p (precip_mean, val_exp, 'NO_KEYWORD', zero)
1571   
1572    ALLOCATE(humrel_mean(nbpt), stat=ier)
1573    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for humrel_mean','','')
1574    var_name = 'humrel_route'
1575    CALL ioconf_setatt_p('UNITS', '-')
1576    CALL ioconf_setatt_p('LONG_NAME','Mean humrel for irrigation')
1577    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., humrel_mean, "gather", nbp_glo, index_g)
1578    CALL setvar_p (humrel_mean, val_exp, 'NO_KEYWORD', un)
1579   
1580    ALLOCATE(k_litt_mean(nbpt), stat=ier)
1581    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for k_litt_mean','','')
1582    var_name = 'k_litt_route'
1583    CALL ioconf_setatt_p('UNITS', '-')
1584    CALL ioconf_setatt_p('LONG_NAME','Mean cond. for litter')
1585    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., k_litt_mean, "gather", nbp_glo, index_g)
1586    CALL setvar_p (k_litt_mean, val_exp, 'NO_KEYWORD', zero)
1587   
1588    ALLOCATE(totnobio_mean(nbpt), stat=ier)
1589    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for totnobio_mean','','')
1590    var_name = 'totnobio_route'
1591    CALL ioconf_setatt_p('UNITS', '-')
1592    CALL ioconf_setatt_p('LONG_NAME','Last Total fraction of no bio for irrigation')
1593    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., totnobio_mean, "gather", nbp_glo, index_g)
1594    CALL setvar_p (totnobio_mean, val_exp, 'NO_KEYWORD', zero)
1595   
1596    ALLOCATE(vegtot_mean(nbpt), stat=ier)
1597    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for vegtot_mean','','')
1598    var_name = 'vegtot_route'
1599    CALL ioconf_setatt_p('UNITS', '-')
1600    CALL ioconf_setatt_p('LONG_NAME','Last Total fraction of vegetation')
1601    CALL restget_p (rest_id, var_name, nbp_glo, 1, 1, kjit, .TRUE., vegtot_mean, "gather", nbp_glo, index_g)
1602    CALL setvar_p (vegtot_mean, val_exp, 'NO_KEYWORD', un)
1603    !
1604    !
1605    DEALLOCATE(tmp_real_g)
1606    !
1607    ! Allocate diagnostic variables
1608    !
1609    ALLOCATE(hydrodiag_loc(nbpt,nbasmax),hydrodiag_glo(nbp_glo,nbasmax),stat=ier)
1610    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for hydrodiag_glo','','')
1611    hydrodiag=>hydrodiag_loc
1612
1613    ALLOCATE(hydroupbasin_loc(nbpt),hydroupbasin_glo(nbp_glo), stat=ier)
1614    IF (ier /= 0) CALL ipslerr_p(3,'routing_init','Pb in allocate for hydroupbasin_glo','','')
1615    hydroupbasin=>hydroupbasin_loc
1616
1617  END SUBROUTINE routing_init
1618  !
1619!! ================================================================================================================================
1620!! SUBROUTINE   : routing_clear
1621!!
1622!>\BRIEF        : This subroutine deallocates the block memory previously allocated.
1623!! \n
1624!_ ================================================================================================================================
1625
1626  SUBROUTINE routing_clear()
1627
1628    IF (ALLOCATED(routing_area_loc)) DEALLOCATE(routing_area_loc)
1629    IF (ALLOCATED(route_togrid_loc)) DEALLOCATE(route_togrid_loc)
1630    IF (ALLOCATED(route_tobasin_loc)) DEALLOCATE(route_tobasin_loc)
1631    IF (ALLOCATED(route_nbintobas_loc)) DEALLOCATE(route_nbintobas_loc)
1632    IF (ALLOCATED(global_basinid_loc)) DEALLOCATE(global_basinid_loc)
1633    IF (ALLOCATED(topo_resid_loc)) DEALLOCATE(topo_resid_loc)
1634    IF (ALLOCATED(routing_area_glo)) DEALLOCATE(routing_area_glo)
1635    IF (ALLOCATED(route_togrid_glo)) DEALLOCATE(route_togrid_glo)
1636    IF (ALLOCATED(route_tobasin_glo)) DEALLOCATE(route_tobasin_glo)
1637    IF (ALLOCATED(route_nbintobas_glo)) DEALLOCATE(route_nbintobas_glo)
1638    IF (ALLOCATED(global_basinid_glo)) DEALLOCATE(global_basinid_glo)
1639    IF (ALLOCATED(topo_resid_glo)) DEALLOCATE(topo_resid_glo)
1640    IF (ALLOCATED(fast_reservoir)) DEALLOCATE(fast_reservoir)
1641    IF (ALLOCATED(slow_reservoir)) DEALLOCATE(slow_reservoir)
1642    IF (ALLOCATED(stream_reservoir)) DEALLOCATE(stream_reservoir)
1643    IF (ALLOCATED(flood_reservoir)) DEALLOCATE(flood_reservoir)
1644    IF (ALLOCATED(flood_frac_bas)) DEALLOCATE(flood_frac_bas)
1645    IF (ALLOCATED(flood_height)) DEALLOCATE(flood_height)
1646    IF (ALLOCATED(pond_frac)) DEALLOCATE(pond_frac)
1647    IF (ALLOCATED(lake_reservoir)) DEALLOCATE(lake_reservoir)
1648    IF (ALLOCATED(pond_reservoir)) DEALLOCATE(pond_reservoir)
1649    IF (ALLOCATED(returnflow_mean)) DEALLOCATE(returnflow_mean)
1650    IF (ALLOCATED(reinfiltration_mean)) DEALLOCATE(reinfiltration_mean)
1651    IF (ALLOCATED(riverflow_mean)) DEALLOCATE(riverflow_mean)
1652    IF (ALLOCATED(coastalflow_mean)) DEALLOCATE(coastalflow_mean)
1653    IF (ALLOCATED(lakeinflow_mean)) DEALLOCATE(lakeinflow_mean)
1654    IF (ALLOCATED(runoff_mean)) DEALLOCATE(runoff_mean)
1655    IF (ALLOCATED(floodout_mean)) DEALLOCATE(floodout_mean)
1656    IF (ALLOCATED(drainage_mean)) DEALLOCATE(drainage_mean)
1657    IF (ALLOCATED(transpot_mean)) DEALLOCATE(transpot_mean)
1658    IF (ALLOCATED(precip_mean)) DEALLOCATE(precip_mean)
1659    IF (ALLOCATED(humrel_mean)) DEALLOCATE(humrel_mean)
1660    IF (ALLOCATED(k_litt_mean)) DEALLOCATE(k_litt_mean)
1661    IF (ALLOCATED(totnobio_mean)) DEALLOCATE(totnobio_mean)
1662    IF (ALLOCATED(vegtot_mean)) DEALLOCATE(vegtot_mean)
1663    IF (ALLOCATED(floodtemp)) DEALLOCATE(floodtemp)
1664    IF (ALLOCATED(hydrodiag_loc)) DEALLOCATE(hydrodiag_loc)
1665    IF (ALLOCATED(hydrodiag_glo)) DEALLOCATE(hydrodiag_glo)
1666    IF (ALLOCATED(hydroupbasin_loc)) DEALLOCATE(hydroupbasin_loc)   
1667    IF (ALLOCATED(hydroupbasin_glo)) DEALLOCATE(hydroupbasin_glo)
1668    IF (ALLOCATED(hydrographs)) DEALLOCATE(hydrographs)
1669    IF (ALLOCATED(slowflow_diag)) DEALLOCATE(slowflow_diag)
1670    IF (ALLOCATED(irrigation_mean)) DEALLOCATE(irrigation_mean)
1671    IF (ALLOCATED(irrigated)) DEALLOCATE(irrigated)
1672    IF (ALLOCATED(floodplains)) DEALLOCATE(floodplains)
1673    IF (ALLOCATED(swamp)) DEALLOCATE(swamp)
1674    IF (ALLOCATED(fast_diag)) DEALLOCATE(fast_diag)
1675    IF (ALLOCATED(slow_diag)) DEALLOCATE(slow_diag)
1676    IF (ALLOCATED(stream_diag)) DEALLOCATE(stream_diag)
1677    IF (ALLOCATED(flood_diag)) DEALLOCATE(flood_diag)
1678    IF (ALLOCATED(pond_diag)) DEALLOCATE(pond_diag)
1679    IF (ALLOCATED(lake_diag)) DEALLOCATE(lake_diag)
1680
1681  END SUBROUTINE routing_clear
1682  !
1683
1684!! ================================================================================================================================
1685!! SUBROUTINE   : routing_flow
1686!!
1687!>\BRIEF         This subroutine computes the transport of water in the various reservoirs
1688!!                (including ponds and floodplains) and the water withdrawals from the reservoirs for irrigation.
1689!!
1690!! DESCRIPTION (definitions, functional, design, flags) :
1691!! This will first compute the amount of water which flows out of each of the 3 reservoirs using the assumption of an
1692!! exponential decrease of water in the reservoir (see Hagemann S and Dumenil L. (1998)). Then we compute the fluxes
1693!! for floodplains and ponds. All this will then be used in order to update each of the basins : taking water out of
1694!! the up-stream basin and adding it to the down-stream one.
1695!! As this step happens globaly we have to stop the parallel processing in order to exchange the information. Once
1696!! all reservoirs are updated we deal with irrigation. The final step is to compute diagnostic fluxes. Among them
1697!! the hydrographs of the largest rivers we have chosen to monitor.
1698!!
1699!! RECENT CHANGE(S): None
1700!!
1701!! MAIN OUTPUT VARIABLE(S): lakeinflow, returnflow, reinfiltration, irrigation, riverflow, coastalflow, hydrographs, flood_frac, flood_res
1702!!
1703!! REFERENCES   :
1704!! - Ngo-Duc, T., K. Laval, G. Ramillien, J. Polcher, and A. Cazenave (2007)
1705!!   Validation of the land water storage simulated by Organising Carbon and Hydrology in Dynamic Ecosystems (ORCHIDEE) with Gravity Recovery and Climate Experiment (GRACE) data.
1706!!   Water Resour. Res., 43, W04427, doi:10.1029/2006WR004941.
1707!! * Irrigation:
1708!! - de Rosnay, P., J. Polcher, K. Laval, and M. Sabre (2003)
1709!!   Integrated parameterization of irrigation in the land surface model ORCHIDEE. Validation over Indian Peninsula.
1710!!   Geophys. Res. Lett., 30(19), 1986, doi:10.1029/2003GL018024.
1711!! - A.C. Vivant (2003)
1712!!   Les plaines d'inondations et l'irrigation dans ORCHIDEE, impacts de leur prise en compte.
1713!!   , , 51pp.
1714!! - N. Culson (2004)
1715!!   Impact de l'irrigation sur le cycle de l'eau
1716!!   Master thesis, Paris VI University, 55pp.
1717!! - X.-T. Nguyen-Vinh (2005)
1718!!   Analyse de l'impact de l'irrigation en Amerique du Nord - plaine du Mississippi - sur la climatologie regionale
1719!!   Master thesis, Paris VI University, 33pp.
1720!! - M. Guimberteau (2006)
1721!!   Analyse et modifications proposees de la modelisation de l'irrigation dans un modele de surface.
1722!!   Master thesis, Paris VI University, 46pp.
1723!! - Guimberteau M. (2010)
1724!!   Modelisation de l'hydrologie continentale et influences de l'irrigation sur le cycle de l'eau.
1725!!   Ph.D. thesis, Paris VI University, 195pp.
1726!! - Guimberteau M., Laval K., Perrier A. and Polcher J. (2011).
1727!!   Global effect of irrigation and its impact on the onset of the Indian summer monsoon.
1728!!   In press, Climate Dynamics, doi: 10.1007/s00382-011-1252-5.
1729!! * Floodplains:
1730!! - A.C. Vivant (2002)
1731!!   L'ecoulement lateral de l'eau sur les surfaces continentales. Prise en compte des plaines d'inondations dans ORCHIDEE.
1732!!   Master thesis, Paris VI University, 46pp.
1733!! - A.C. Vivant (2003)
1734!!   Les plaines d'inondations et l'irrigation dans ORCHIDEE, impacts de leur prise en compte.
1735!!   , , 51pp.
1736!! - T. d'Orgeval (2006)
1737!!   Impact du changement climatique sur le cycle de l'eau en Afrique de l'Ouest: modelisation et incertitudes.
1738!!   Ph.D. thesis, Paris VI University, 188pp.
1739!! - T. d'Orgeval, J. Polcher, and P. de Rosnay (2008)
1740!!   Sensitivity of the West African hydrological cycle in ORCHIDEE to infiltration processes.
1741!!   Hydrol. Earth Syst. Sci., 12, 1387-1401
1742!! - M. Guimberteau, G. Drapeau, J. Ronchail, B. Sultan, J. Polcher, J.-M. Martinez, C. Prigent, J.-L. Guyot, G. Cochonneau,
1743!!   J. C. Espinoza, N. Filizola, P. Fraizy, W. Lavado, E. De Oliveira, R. Pombosa, L. Noriega, and P. Vauchel (2011)
1744!!   Discharge simulation in the sub-basins of the Amazon using ORCHIDEE forced by new datasets.
1745!!   Hydrol. Earth Syst. Sci. Discuss., 8, 11171-11232, doi:10.5194/hessd-8-11171-2011
1746!!
1747!! FLOWCHART    :None
1748!! \n
1749!_ ================================================================================================================================
1750
1751  SUBROUTINE routing_flow(nbpt, dt_routing, lalo, floodout, runoff, drainage, &
1752       &                  vegtot, totnobio, transpot_mean, precip, humrel, k_litt, floodtemp, reinf_slope, &
1753       &                  lakeinflow, returnflow, reinfiltration, irrigation, riverflow, &
1754       &                  coastalflow, hydrographs, slowflow_diag, flood_frac, flood_res, &
1755                          netflow_stream_diag, netflow_fast_diag, netflow_slow_diag)
1756    !
1757    IMPLICIT NONE
1758    !
1759!! INPUT VARIABLES
1760    INTEGER(i_std), INTENT(in)                   :: nbpt                      !! Domain size (unitless)
1761    REAL(r_std), INTENT (in)                     :: dt_routing                !! Routing time step (s)
1762    REAL(r_std), INTENT(in)                      :: lalo(nbpt,2)              !! Vector of latitude and longitudes
1763    REAL(r_std), INTENT(in)                      :: runoff(nbpt)              !! Grid-point runoff (kg/m^2/dt)
1764    REAL(r_std), INTENT(in)                      :: floodout(nbpt)            !! Grid-point flow out of floodplains (kg/m^2/dt)
1765    REAL(r_std), INTENT(in)                      :: drainage(nbpt)            !! Grid-point drainage (kg/m^2/dt)
1766    REAL(r_std), INTENT(in)                      :: vegtot(nbpt)              !! Potentially vegetated fraction (unitless;0-1)
1767    REAL(r_std), INTENT(in)                      :: totnobio(nbpt)            !! Other areas which can not have vegetation
1768    REAL(r_std), INTENT(in)                      :: transpot_mean(nbpt)       !! Mean potential transpiration of the vegetation (kg/m^2/dt)
1769    REAL(r_std), INTENT(in)                      :: precip(nbpt)              !! Rainfall (kg/m^2/dt)
1770    REAL(r_std), INTENT(in)                      :: humrel(nbpt)              !! Soil moisture stress, root extraction potential (unitless)
1771    REAL(r_std), INTENT(in)                      :: k_litt(nbpt)              !! Averaged conductivity for saturated infiltration in the 'litter' layer (kg/m^2/dt)
1772    REAL(r_std), INTENT(in)                      :: floodtemp(nbpt)           !! Temperature to decide if floodplains work (K)
1773    REAL(r_std), INTENT(in)                      :: reinf_slope(nbpt)         !! Coefficient which determines the reinfiltration ratio in the grid box due to flat areas (unitless;0-1)
1774    REAL(r_std), INTENT(out)                     :: lakeinflow(nbpt)          !! Water inflow to the lakes (kg/dt)
1775    !
1776!! OUTPUT VARIABLES
1777    REAL(r_std), INTENT(out)                     :: returnflow(nbpt)          !! The water flow from lakes and swamps which returns into the grid box.
1778                                                                              !! This water will go back into the hydrol module to allow re-evaporation (kg/m^2/dt_routing)
1779    REAL(r_std), INTENT(out)                     :: reinfiltration(nbpt)      !! Water flow from ponds and floodplains which returns to the grid box (kg/m^2/dt)
1780    REAL(r_std), INTENT(out)                     :: irrigation(nbpt)          !! Irrigation flux. This is the water taken from the reservoirs and beeing put into the upper layers of the soil (kg/m^2/dt_routing)
1781    REAL(r_std), INTENT(out)                     :: riverflow(nbpt)           !! Outflow of the major rivers. The flux will be located on the continental grid but this should be a coastal point (kg/dt_routing)
1782    REAL(r_std), INTENT(out)                     :: coastalflow(nbpt)         !! Outflow on coastal points by small basins. This is the water which flows in a disperse way into the ocean (kg/dt_routing)
1783    REAL(r_std), INTENT(out)                     :: hydrographs(nbpt)         !! Hydrographs at the outflow of the grid box for major basins (kg/dt)
1784    REAL(r_std), INTENT(out)                     :: slowflow_diag(nbpt)       !! Hydrographs of slow_flow = routed slow_flow for major basins (kg/dt)
1785    REAL(r_std), INTENT(out)                     :: flood_frac(nbpt)          !! Flooded fraction of the grid box (unitless;0-1)
1786    REAL(r_std), INTENT(out)                     :: flood_res(nbpt)           !! Diagnostic of water amount in the floodplains reservoir (kg)
1787
1788    REAL(r_std), INTENT(out)                     :: netflow_stream_diag(nbpt) !! Input - Output flow to stream reservoir
1789    REAL(r_std), INTENT(out)                     :: netflow_fast_diag(nbpt)   !! Input - Output flow to fast reservoir
1790    REAL(r_std), INTENT(out)                     :: netflow_slow_diag(nbpt)   !! Input - Output flow to slow reservoir
1791    !
1792!! LOCAL VARIABLES
1793    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: fast_flow                 !! Outflow from the fast reservoir (kg/dt)
1794    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: slow_flow                 !! Outflow from the slow reservoir (kg/dt)
1795    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: stream_flow               !! Outflow from the stream reservoir (kg/dt)
1796    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: flood_flow                !! Outflow from the floodplain reservoir (kg/dt)
1797    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: pond_inflow               !! Inflow to the pond reservoir (kg/dt)
1798    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: pond_drainage             !! Drainage from pond (kg/m^2/dt)
1799    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: flood_drainage            !! Drainage from floodplains (kg/m^2/dt)
1800    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: return_swamp              !! Inflow to the swamp (kg/dt)
1801    !
1802    ! Irrigation per basin
1803    !
1804    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: irrig_needs               !! Total irrigation requirement (water requirements by the crop for its optimal growth) (kg)
1805    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: irrig_actual              !! Possible irrigation according to the water availability in the reservoirs (kg)
1806    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: irrig_deficit             !! Amount of water missing for irrigation (kg)
1807    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: irrig_adduct              !! Amount of water carried over from other basins for irrigation (kg)
1808    !
1809    REAL(r_std), DIMENSION(nbpt, 0:nbasmax+3)    :: transport                 !! Water transport between basins (kg/dt)
1810    REAL(r_std), DIMENSION(nbp_glo, 0:nbasmax+3) :: transport_glo             !! Water transport between basins (kg/dt)
1811    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: floods                    !! Water flow in to the floodplains (kg/dt)
1812    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: potflood                  !! Potential inflow to the swamps (kg/dt)
1813    REAL(r_std), DIMENSION(nbpt)                 :: tobeflooded               !! Maximal surface which can be inundated in each grid box (m^2)
1814    REAL(r_std), DIMENSION(nbpt)                 :: totarea                   !! Total area of basin (m^2)
1815    REAL(r_std), DIMENSION(nbpt)                 :: totflood                  !! Total amount of water in the floodplains reservoir (kg)
1816    REAL(r_std), DIMENSION(nbasmax)              :: pond_excessflow           !!
1817    REAL(r_std)                                  :: flow                      !! Outflow computation for the reservoirs (kg/dt)
1818    REAL(r_std)                                  :: floodindex                !! Fraction of grid box area inundated (unitless;0-1)
1819    REAL(r_std)                                  :: pondex                    !!
1820    REAL(r_std)                                  :: flood_frac_pot            !! Total fraction of the grid box which is flooded at optimum repartition (unitless;0-1)
1821    REAL(r_std)                                  :: stream_tot                !! Total water amount in the stream reservoirs (kg)
1822    REAL(r_std)                                  :: adduction                 !! Importation of water from a stream reservoir of a neighboring grid box (kg)
1823    REAL(r_std), DIMENSION(nbp_glo)              :: lake_overflow_g           !! Removed water from lake reservoir on global grid (kg/gridcell/dt_routing)
1824    REAL(r_std), DIMENSION(nbpt)                 :: lake_overflow             !! Removed water from lake reservoir on local grid (kg/gridcell/dt_routing)
1825    REAL(r_std), DIMENSION(nbpt)                 :: lake_overflow_coast       !! lake_overflow distributed on coast gridcells, only diag(kg/gridcell/dt_routing)
1826    REAL(r_std)                                  :: total_lake_overflow       !! Sum of lake_overflow over full grid (kg)
1827    REAL(r_std), DIMENSION(8,nbasmax)            :: streams_around            !! Stream reservoirs of the neighboring grid boxes (kg)
1828    INTEGER(i_std), DIMENSION(8)                 :: igrd                      !!
1829    INTEGER(i_std), DIMENSION(2)                 :: ff                        !!
1830    INTEGER(i_std), DIMENSION(1)                 :: fi                        !!
1831    INTEGER(i_std)                               :: ig, ib, ib2, ig2          !! Indices (unitless)
1832    INTEGER(i_std)                               :: rtg, rtb, in              !! Indices (unitless)
1833    INTEGER(i_std)                               :: ier                       !! Error handling
1834    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: fast_flow_g               !! Outflow from the fast reservoir (kg/dt)
1835    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: slow_flow_g               !! Outflow from the slow reservoir (kg/dt)
1836    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: stream_flow_g             !! Outflow from the stream reservoir (kg/dt)
1837    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: irrig_deficit_glo         !! Amount of water missing for irrigation (kg)
1838    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: stream_reservoir_glo      !! Water amount in the stream reservoir (kg)
1839    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: irrig_adduct_glo          !! Amount of water carried over from other basins for irrigation (kg)
1840
1841    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: netflow_stream            !! Input - Output flow to stream reservoir
1842    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: netflow_fast              !! Input - Output flow to fast reservoir
1843    REAL(r_std), DIMENSION(nbpt, nbasmax)        :: netflow_slow              !! Input - Output flow to slow reservoir
1844
1845
1846    !! PARAMETERS
1847    LOGICAL, PARAMETER                           :: check_reservoir = .FALSE. !! Logical to choose if we write informations when a negative amount of water is occurring in a reservoir (true/false)
1848!_ ================================================================================================================================
1849    !
1850    transport(:,:) = zero
1851    transport_glo(:,:) = zero
1852    irrig_netereq(:) = zero
1853    irrig_needs(:,:) = zero
1854    irrig_actual(:,:) = zero
1855    irrig_deficit(:,:) = zero
1856    irrig_adduct(:,:) = zero
1857    totarea(:) = zero
1858    totflood(:) = zero
1859    !
1860    ! Compute all the fluxes
1861    !
1862    DO ib=1,nbasmax
1863       DO ig=1,nbpt
1864          !
1865          totarea(ig) = totarea(ig) + routing_area(ig,ib)
1866          totflood(ig) = totflood(ig) + flood_reservoir(ig,ib)
1867       ENDDO
1868    ENDDO
1869          !
1870!> The outflow fluxes from the three reservoirs are computed.
1871!> The outflow of volume of water Vi into the reservoir i is assumed to be linearly related to its volume.
1872!> The water travel simulated by the routing scheme is dependent on the water retention index topo_resid
1873!> given by a 0.5 degree resolution map for each pixel performed from a simplification of Manning's formula
1874!> (Dingman, 1994; Ducharne et al., 2003).
1875!> The resulting product of tcst (in day/m) and topo_resid (in m) represents the time constant (day)
1876!> which is an e-folding time, the time necessary for the water amount
1877!> in the stream reservoir to decrease by a factor e. Hence, it gives an order of
1878!> magnitude of the travel time through this reservoir between
1879!> the sub-basin considered and its downstream neighbor.
1880
1881    DO ib=1,nbasmax
1882       DO ig=1,nbpt
1883          IF ( route_tobasin(ig,ib) .GT. 0 ) THEN
1884             !
1885             ! Each of the fluxes is limited by the water in the reservoir and a small margin
1886             ! (min_reservoir) to avoid rounding errors.
1887             !
1888             flow = MIN(fast_reservoir(ig,ib)/((topo_resid(ig,ib)/1000.)*fast_tcst*one_day/dt_routing),&
1889                  & fast_reservoir(ig,ib)-min_sechiba)
1890             fast_flow(ig,ib) = MAX(flow, zero)
1891
1892             flow = MIN(slow_reservoir(ig,ib)/((topo_resid(ig,ib)/1000.)*slow_tcst*one_day/dt_routing),&
1893                  & slow_reservoir(ig,ib)-min_sechiba)
1894             slow_flow(ig,ib) = MAX(flow, zero)
1895
1896             flow = MIN(stream_reservoir(ig,ib)/((topo_resid(ig,ib)/1000.)*stream_tcst* & 
1897                  & MAX(un-SQRT(flood_frac_bas(ig,ib)),min_sechiba)*one_day/dt_routing),&
1898                  & stream_reservoir(ig,ib)-min_sechiba)
1899             stream_flow(ig,ib) = MAX(flow, zero)
1900             !
1901          ELSE
1902             fast_flow(ig,ib) = zero
1903             slow_flow(ig,ib) = zero
1904             stream_flow(ig,ib) = zero
1905          ENDIF
1906       ENDDO
1907    ENDDO
1908    !-
1909    !- Compute the fluxes out of the floodplains and ponds if they exist.
1910    !-
1911    IF (do_floodplains .OR. doponds) THEN
1912       DO ig=1,nbpt
1913          IF (flood_frac(ig) .GT. min_sechiba) THEN
1914             !
1915             flow = MIN(floodout(ig)*totarea(ig)*pond_frac(ig)/flood_frac(ig), pond_reservoir(ig)+totflood(ig))
1916             pondex = MAX(flow - pond_reservoir(ig), zero)
1917             pond_reservoir(ig) = pond_reservoir(ig) - (flow - pondex) 
1918             !
1919             ! If demand was over reservoir size, we will take it out from floodplains
1920             !
1921             pond_excessflow(:) = zero
1922             DO ib=1,nbasmax
1923                pond_excessflow(ib) = MIN(pondex*flood_frac_bas(ig,ib)/(flood_frac(ig)-pond_frac(ig)),&
1924                     &                    flood_reservoir(ig,ib))
1925                pondex = pondex - pond_excessflow(ib)
1926             ENDDO
1927             !
1928             IF ( pondex .GT. min_sechiba) THEN
1929                WRITE(numout,*) "Unable to redistribute the excess pond outflow over the water available in the floodplain."
1930                WRITE(numout,*) "Pondex = ", pondex
1931                WRITE(numout,*) "pond_excessflow(:) = ", pond_excessflow(:)
1932             ENDIF
1933             !
1934             DO ib=1,nbasmax
1935                !
1936                flow = floodout(ig)*routing_area(ig,ib)*flood_frac_bas(ig,ib)/flood_frac(ig) + pond_excessflow(ib)
1937                !
1938                flood_reservoir(ig,ib) = flood_reservoir(ig,ib) - flow
1939                !
1940                !
1941                IF (flood_reservoir(ig,ib) .LT. min_sechiba) THEN
1942                   flood_reservoir(ig,ib) = zero
1943                ENDIF
1944                IF (pond_reservoir(ig) .LT. min_sechiba) THEN
1945                   pond_reservoir(ig) = zero
1946                ENDIF
1947             ENDDO
1948          ENDIF
1949       ENDDO
1950    ENDIF
1951
1952    !-
1953    !- Computing the drainage and outflow from floodplains
1954!> Drainage from floodplains is depending on a averaged conductivity (k_litt)
1955!> for saturated infiltration in the 'litter' layer. Flood_drainage will be
1956!> a component of the total reinfiltration that leaves the routing scheme.
1957    !-
1958    IF (do_floodplains) THEN
1959       IF (dofloodinfilt) THEN
1960          DO ib=1,nbasmax
1961             DO ig=1,nbpt
1962                flood_drainage(ig,ib) = MAX(zero, MIN(flood_reservoir(ig,ib), &
1963                     & flood_frac(ig)*routing_area(ig,ib)*k_litt(ig)*dt_routing/one_day))
1964                flood_reservoir(ig,ib) = flood_reservoir(ig,ib) - flood_drainage(ig,ib)
1965             ENDDO
1966          ENDDO
1967       ELSE
1968          DO ib=1,nbasmax
1969             DO ig=1,nbpt
1970                flood_drainage(ig,ib) = zero 
1971             ENDDO
1972          ENDDO
1973       ENDIF
1974!> Outflow from floodplains is computed depending a delay. This delay is characterized by a time constant
1975!> function of the surface of the floodplains and the product of topo_resid and flood_tcst. flood_tcst
1976!> has been calibrated through observations in the Niger Inner Delta (D'Orgeval, 2006).
1977!
1978       DO ib=1,nbasmax
1979          DO ig=1,nbpt
1980             IF ( route_tobasin(ig,ib) .GT. 0 ) THEN
1981                IF (flood_frac_bas(ig,ib) .GT. min_sechiba) THEN
1982                   flow = MIN(flood_reservoir(ig,ib)  &
1983                        & /((topo_resid(ig,ib)/1000.)*flood_tcst* &
1984                        & flood_frac_bas(ig,ib)*one_day/dt_routing),&
1985                        & flood_reservoir(ig,ib))
1986                ELSE
1987                   flow = zero
1988                ENDIF
1989                flood_flow(ig,ib) = flow
1990             ELSE
1991                flood_flow(ig,ib) = zero
1992             ENDIF
1993          ENDDO
1994       ENDDO
1995    ELSE
1996       DO ib=1,nbasmax
1997          DO ig=1,nbpt
1998             flood_drainage(ig,ib) = zero
1999             flood_flow(ig,ib) = zero
2000             flood_reservoir(ig,ib) = zero
2001          ENDDO
2002       ENDDO
2003    ENDIF
2004
2005    !-
2006    !- Computing drainage and inflow for ponds
2007!> Drainage from ponds is computed in the same way than for floodplains.
2008!> Reinfiltrated fraction from the runoff (i.e. the outflow from the fast reservoir)
2009!> is the inflow of the pond reservoir.
2010    !-
2011    IF (doponds) THEN
2012       ! If used, the slope coef is not used in hydrol for water2infilt
2013       DO ib=1,nbasmax
2014          DO ig=1,nbpt
2015             pond_inflow(ig,ib) = fast_flow(ig,ib) * reinf_slope(ig)
2016             pond_drainage(ig,ib) = MIN(pond_reservoir(ig)*routing_area(ig,ib)/totarea(ig), &
2017                  & pond_frac(ig)*routing_area(ig,ib)*k_litt(ig)*dt_routing/one_day)
2018             fast_flow(ig,ib) = fast_flow(ig,ib) - pond_inflow(ig,ib) 
2019          ENDDO
2020       ENDDO
2021    ELSE
2022       DO ib=1,nbasmax
2023          DO ig=1,nbpt
2024             pond_inflow(ig,ib) = zero
2025             pond_drainage(ig,ib) = zero
2026             pond_reservoir(ig) = zero
2027          ENDDO
2028       ENDDO
2029    ENDIF
2030
2031!ym cette methode conserve les erreurs d'arrondie
2032!ym mais n'est pas la plus efficace
2033
2034    !-
2035    !- Compute the transport from one basin to another
2036    !-
2037
2038    IF (is_root_prc)  THEN
2039       ALLOCATE( fast_flow_g(nbp_glo, nbasmax), slow_flow_g(nbp_glo, nbasmax), &
2040            stream_flow_g(nbp_glo, nbasmax), stat=ier)
2041    ELSE
2042       ALLOCATE( fast_flow_g(1,1), slow_flow_g(1,1), &
2043            stream_flow_g(1, 1), stat=ier)
2044    ENDIF
2045    IF (ier /= 0) CALL ipslerr_p(3,'routing_flow','Pb in allocate for fast_flow_g','','')
2046       
2047    CALL gather(fast_flow,fast_flow_g)
2048    CALL gather(slow_flow,slow_flow_g)
2049    CALL gather(stream_flow,stream_flow_g)
2050
2051    IF (is_root_prc) THEN
2052       DO ib=1,nbasmax
2053          DO ig=1,nbp_glo
2054             !
2055             rtg = route_togrid_glo(ig,ib)
2056             rtb = route_tobasin_glo(ig,ib)
2057             transport_glo(rtg,rtb) = transport_glo(rtg,rtb) + fast_flow_g(ig,ib) + slow_flow_g(ig,ib) + &
2058                  & stream_flow_g(ig,ib)
2059             !
2060          ENDDO
2061       ENDDO
2062    ENDIF
2063
2064    DEALLOCATE( fast_flow_g, slow_flow_g, stream_flow_g )
2065   
2066    CALL scatter(transport_glo,transport)
2067
2068    !-
2069    !- Do the floodings - First initialize
2070    !-
2071    return_swamp(:,:)=zero
2072    floods(:,:)=zero
2073    !-
2074!> Over swamp areas, a fraction of water (return_swamp) is withdrawn from the river depending on the
2075!> parameter swamp_cst.
2076!> It will be transferred into soil moisture and thus does not return directly to the river.
2077    !
2078    !- 1. Swamps: Take out water from the river to put it to the swamps
2079    !-
2080    !
2081    IF ( doswamps ) THEN
2082       tobeflooded(:) = swamp(:)
2083       DO ib=1,nbasmax
2084          DO ig=1,nbpt
2085             potflood(ig,ib) = transport(ig,ib) 
2086             !
2087             IF ( tobeflooded(ig) > 0. .AND. potflood(ig,ib) > 0. .AND. floodtemp(ig) > tp_00 ) THEN
2088                !
2089                IF (routing_area(ig,ib) > tobeflooded(ig)) THEN
2090                   floodindex = tobeflooded(ig) / routing_area(ig,ib)
2091                ELSE
2092                   floodindex = 1.0
2093                ENDIF
2094                return_swamp(ig,ib) = swamp_cst * potflood(ig,ib) * floodindex
2095                !
2096                tobeflooded(ig) = tobeflooded(ig) - routing_area(ig,ib) 
2097                !
2098             ENDIF
2099          ENDDO
2100       ENDDO
2101    ENDIF
2102    !-
2103    !- 2. Floodplains: Update the reservoir with the flux computed above.
2104    !-
2105    IF ( do_floodplains ) THEN
2106       DO ig=1,nbpt
2107          IF (floodplains(ig) .GT. min_sechiba .AND. floodtemp(ig) .GT. tp_00) THEN
2108             DO ib=1,nbasmax
2109                floods(ig,ib) = transport(ig,ib) - return_swamp(ig,ib) 
2110             ENDDO
2111          ENDIF
2112       ENDDO
2113    ENDIF
2114    !
2115    ! Update all reservoirs
2116!> The slow and deep reservoir (slow_reservoir) collect the deep drainage whereas the
2117!> fast_reservoir collects the computed surface runoff. Both discharge into a third reservoir
2118!> (stream_reservoir) of the next sub-basin downstream.
2119!> Water from the floodplains reservoir (flood_reservoir) flows also into the stream_reservoir of the next sub-basin downstream.
2120!> Water that flows into the pond_reservoir is withdrawn from the fast_reservoir.
2121    !
2122    DO ig=1,nbpt
2123       DO ib=1,nbasmax
2124          !
2125          fast_reservoir(ig,ib) =  fast_reservoir(ig,ib) + runoff(ig)*routing_area(ig,ib) - &
2126               & fast_flow(ig,ib) - pond_inflow(ig,ib)
2127          !
2128          slow_reservoir(ig,ib) = slow_reservoir(ig,ib) + drainage(ig)*routing_area(ig,ib) - &
2129               & slow_flow(ig,ib)
2130          !
2131          stream_reservoir(ig,ib) = stream_reservoir(ig,ib) + flood_flow(ig,ib) + transport(ig,ib) - &
2132               & stream_flow(ig,ib) - return_swamp(ig,ib) - floods(ig,ib)
2133          !
2134          flood_reservoir(ig,ib) = flood_reservoir(ig,ib) + floods(ig,ib) - &
2135               & flood_flow(ig,ib) 
2136          !
2137          pond_reservoir(ig) = pond_reservoir(ig) + pond_inflow(ig,ib) - pond_drainage(ig,ib)
2138          !
2139          IF ( flood_reservoir(ig,ib) .LT. zero ) THEN
2140             IF ( check_reservoir ) THEN
2141                WRITE(numout,*) "WARNING : negative flood reservoir at :", ig, ib, ". Problem is being corrected."
2142                WRITE(numout,*) "flood_reservoir, floods, flood_flow : ", flood_reservoir(ig,ib), floods(ig,ib), &
2143                     & flood_flow(ig,ib) 
2144             ENDIF
2145             stream_reservoir(ig,ib) = stream_reservoir(ig,ib) + flood_reservoir(ig,ib)
2146             flood_reservoir(ig,ib) = zero
2147          ENDIF
2148          !
2149          IF ( stream_reservoir(ig,ib) .LT. zero ) THEN
2150             IF ( check_reservoir ) THEN
2151                WRITE(numout,*) "WARNING : negative stream reservoir at :", ig, ib, ". Problem is being corrected."
2152                WRITE(numout,*) "stream_reservoir, flood_flow, transport : ", stream_reservoir(ig,ib), flood_flow(ig,ib), &
2153                     &  transport(ig,ib)
2154                WRITE(numout,*) "stream_flow, return_swamp, floods :", stream_flow(ig,ib), return_swamp(ig,ib), floods(ig,ib)
2155             ENDIF
2156             fast_reservoir(ig,ib) =  fast_reservoir(ig,ib) + stream_reservoir(ig,ib)
2157             stream_reservoir(ig,ib) = zero
2158          ENDIF
2159          !
2160          IF ( fast_reservoir(ig,ib) .LT. zero ) THEN
2161             IF ( check_reservoir ) THEN
2162                WRITE(numout,*) "WARNING : negative fast reservoir at :", ig, ib, ". Problem is being corrected."
2163                WRITE(numout,*) "fast_reservoir, runoff, fast_flow, ponf_inflow  : ", fast_reservoir(ig,ib), &
2164                     &runoff(ig), fast_flow(ig,ib), pond_inflow(ig,ib)
2165             ENDIF
2166             slow_reservoir(ig,ib) =  slow_reservoir(ig,ib) + fast_reservoir(ig,ib)
2167             fast_reservoir(ig,ib) = zero
2168          ENDIF
2169
2170          IF ( slow_reservoir(ig,ib) .LT. - min_sechiba ) THEN
2171             WRITE(numout,*) 'WARNING : There is a negative reservoir at :', ig, ib,lalo(ig,:)
2172             WRITE(numout,*) 'WARNING : slowr, slow_flow, drainage', &
2173                  & slow_reservoir(ig,ib), slow_flow(ig,ib), drainage(ig)
2174             WRITE(numout,*) 'WARNING : pondr, pond_inflow, pond_drainage', &
2175                  & pond_reservoir(ig), pond_inflow(ig,ib), pond_drainage(ig,ib)
2176             CALL ipslerr_p(2, 'routing_flow', 'WARNING negative slow_reservoir.','','')
2177          ENDIF
2178
2179       ENDDO
2180    ENDDO
2181
2182
2183    totflood(:) = zero
2184    DO ig=1,nbpt
2185       DO ib=1,nbasmax
2186          totflood(ig) = totflood(ig) + flood_reservoir(ig,ib)
2187       ENDDO
2188    ENDDO
2189
2190    !-
2191    !- Computes the fraction of floodplains and ponds according to their volume
2192    !-
2193    IF (do_floodplains .OR. doponds) THEN
2194       flood_frac(:) = zero
2195       flood_height(:) = zero
2196       flood_frac_bas(:,:) = zero
2197       DO ig=1, nbpt
2198          IF (totflood(ig) .GT. min_sechiba) THEN
2199             ! We first compute the total fraction of the grid box which is flooded at optimum repartition
2200             flood_frac_pot = (totflood(ig) / (totarea(ig)*floodcri/(beta+un)))**(beta/(beta+un))
2201             flood_frac(ig) = MIN(floodplains(ig) / totarea(ig), flood_frac_pot)
2202             ! Then we diagnose the fraction for each basin with the size of its flood_reservoir
2203             ! (flood_frac_bas may be > 1)
2204             DO ib=1,nbasmax
2205                IF (routing_area(ig,ib) .GT. min_sechiba) THEN
2206                   flood_frac_bas(ig,ib) = flood_frac(ig) * &
2207                        & (flood_reservoir(ig,ib) / totflood(ig)) / (routing_area(ig,ib) / totarea(ig))
2208                ENDIF
2209             ENDDO
2210             ! We diagnose the maximum height of floodplain
2211             flood_height(ig) = (beta/(beta+1))*floodcri*(flood_frac(ig))**(un/beta) + totflood(ig)/(totarea(ig)*flood_frac(ig)) 
2212             ! And finally add the pond surface
2213             pond_frac(ig) = MIN(un-flood_frac(ig), ((betap+1)*pond_reservoir(ig) / (pondcri*totarea(ig)))**(betap/(betap+1)) ) 
2214             flood_frac(ig) = flood_frac(ig) + pond_frac(ig)
2215             !
2216          ENDIF
2217       ENDDO
2218    ELSE
2219       flood_frac(:) = zero
2220       flood_height(:) = zero
2221       flood_frac_bas(:,:) = zero
2222    ENDIF
2223
2224    !-
2225    !- Compute the total reinfiltration and returnflow to the grid box
2226!> A term of returnflow is computed including the water from the swamps that does not return directly to the river
2227!> but will be put into soil moisture (see hydrol module).
2228!> A term of reinfiltration is computed including the water that reinfiltrated from the ponds and floodplains areas.
2229!> It will be put into soil moisture (see hydrol module).
2230    !-
2231    IF (do_floodplains .OR. doswamps .OR. doponds) THEN
2232       returnflow(:) = zero
2233       reinfiltration(:) = zero
2234       !
2235       DO ib=1,nbasmax
2236          DO ig=1,nbpt
2237             returnflow(ig) =  returnflow(ig) + return_swamp(ig,ib)
2238             reinfiltration(ig) =  reinfiltration(ig) + pond_drainage(ig,ib) + flood_drainage(ig,ib) 
2239          ENDDO
2240       ENDDO
2241       !
2242       DO ig=1,nbpt
2243          returnflow(ig) = returnflow(ig)/totarea(ig)
2244          reinfiltration(ig) = reinfiltration(ig)/totarea(ig)
2245       ENDDO
2246    ELSE
2247       returnflow(:) = zero
2248       reinfiltration(:) = zero
2249    ENDIF
2250
2251    !
2252    ! Compute the net irrigation requirement from Univ of Kassel
2253    !
2254    ! This is a very low priority process and thus only applies if
2255    ! there is some water left in the reservoirs after all other things.
2256    !
2257!> The computation of the irrigation is performed here.
2258!> * First step
2259!> In a first time, the water requirements (irrig_netereq) by the crops for their optimal growth are calculated
2260!> over each irrigated fraction (irrigated(ig)/totarea(ig)). It is the difference
2261!> between the maximal water loss by the crops (transpot_mean) and the net water amount kept by the soil
2262!> (precipitation and reinfiltration). Transpot_mean is computed in the routines enerbil and diffuco. It
2263!> is derived from the effective transpiration parametrization under stress-free conditions, called potential transpiration.
2264!> Crop_coef was used by a previous parametrization of irrigation in the code. Here, its value is equal to one.
2265!> The crop coefficient was constant in space and time to represent a mean resistance of the vegetation to the potential evaporation.
2266!> Now, the term crop_coef*Epot is substituted by transpot_mean (see Guimberteau et al., 2011).
2267!> * Second step
2268!> We compute irrigation needs in order to supply Irrig_netereq. Water for irrigation (irrig_actual) is withdrawn
2269!> from the reservoirs. The amount of water is withdrawn in priority from the stream reservoir.
2270!> If the irrigation requirement is higher than the water availability of the reservoir, water is withdrawn
2271!> from the fast reservoir or, in the extreme case, from the slow reservoir.
2272!> * Third step
2273!> We compute a deficit in water for irrigation. If it is positive, irrigation (depending on water availibility in the reservoirs)
2274!> has not supplied the crops requirements.
2275!
2276    IF ( do_irrigation ) THEN
2277       DO ig=1,nbpt
2278          !
2279          IF ((vegtot(ig) .GT. min_sechiba) .AND. (humrel(ig) .LT. un-min_sechiba) .AND. &
2280               & (runoff(ig) .LT. min_sechiba) ) THEN
2281             
2282             irrig_netereq(ig) = (irrigated(ig) / totarea(ig) ) * MAX(zero, transpot_mean(ig) - &
2283                  & (precip(ig)+reinfiltration(ig)) )
2284             
2285          ENDIF
2286          !
2287          DO ib=1,nbasmax
2288             IF ( routing_area(ig,ib) .GT. 0 ) THEN
2289             
2290                irrig_needs(ig,ib) = irrig_netereq(ig) * routing_area(ig,ib)
2291
2292                irrig_actual(ig,ib) = MIN(irrig_needs(ig,ib),&
2293                     &   stream_reservoir(ig,ib) + fast_reservoir(ig,ib) + slow_reservoir(ig,ib) )
2294               
2295                slow_reservoir(ig,ib) = MAX(zero, slow_reservoir(ig,ib) + &
2296                     & MIN(zero, fast_reservoir(ig,ib) + MIN(zero, stream_reservoir(ig,ib)-irrig_actual(ig,ib))))
2297
2298                fast_reservoir(ig,ib) = MAX( zero, &
2299                     &  fast_reservoir(ig,ib) + MIN(zero, stream_reservoir(ig,ib)-irrig_actual(ig,ib)))
2300
2301                stream_reservoir(ig,ib) = MAX(zero, stream_reservoir(ig,ib)-irrig_actual(ig,ib) )
2302
2303                irrig_deficit(ig,ib) = irrig_needs(ig,ib)-irrig_actual(ig,ib)
2304
2305             ENDIF
2306          ENDDO
2307          !
2308          ! Check if we cannot find the missing water in another basin of the same grid (stream reservoir only).
2309          ! If we find that then we create some adduction from that subbasin to the one where we need it for
2310          ! irrigation.
2311          !
2312!> If crops water requirements have not been supplied (irrig_deficit>0), we check if we cannot find the missing water
2313!> in another basin of the same grid. If there is water in the stream reservoir of this subbasin, we create some adduction
2314!> from that subbasin to the one where we need it for irrigation.
2315!>
2316          DO ib=1,nbasmax
2317
2318             stream_tot = SUM(stream_reservoir(ig,:))
2319
2320             DO WHILE ( irrig_deficit(ig,ib) > min_sechiba .AND. stream_tot > min_sechiba)
2321               
2322                fi = MAXLOC(stream_reservoir(ig,:))
2323                ib2 = fi(1)
2324
2325                irrig_adduct(ig,ib) = MIN(irrig_deficit(ig,ib), stream_reservoir(ig,ib2))
2326                stream_reservoir(ig,ib2) = stream_reservoir(ig,ib2)-irrig_adduct(ig,ib)
2327                irrig_deficit(ig,ib) = irrig_deficit(ig,ib)-irrig_adduct(ig,ib)
2328             
2329                stream_tot = SUM(stream_reservoir(ig,:))
2330               
2331             ENDDO
2332             
2333          ENDDO
2334          !
2335       ENDDO
2336       !
2337       ! If we are at higher resolution we might need to look at neighboring grid boxes to find the streams
2338       ! which can feed irrigation
2339!
2340!> At higher resolution (grid box smaller than 100x100km), we can import water from neighboring grid boxes
2341!> to the one where we need it for irrigation.
2342       !
2343       IF (is_root_prc) THEN
2344          ALLOCATE(irrig_deficit_glo(nbp_glo, nbasmax), stream_reservoir_glo(nbp_glo, nbasmax), &
2345               &        irrig_adduct_glo(nbp_glo, nbasmax), stat=ier)
2346       ELSE
2347          ALLOCATE(irrig_deficit_glo(0, 0), stream_reservoir_glo(0, 0), &
2348               &        irrig_adduct_glo(0, 0), stat=ier)
2349       ENDIF
2350       IF (ier /= 0) CALL ipslerr_p(3,'routing_flow','Pb in allocate for irrig_deficit_glo, stream_reservoir_glo,...','','')
2351
2352       CALL gather(irrig_deficit, irrig_deficit_glo)
2353       CALL gather(stream_reservoir,  stream_reservoir_glo)
2354       CALL gather(irrig_adduct, irrig_adduct_glo)
2355
2356       IF (is_root_prc) THEN
2357          !
2358          DO ig=1,nbp_glo
2359             ! Only work if the grid box is smaller than 100x100km. Else the piplines we build
2360             ! here would be too long to be reasonable.
2361             IF ( resolution_g(ig,1) < 100000. .AND. resolution_g(ig,2) < 100000. ) THEN
2362                DO ib=1,nbasmax
2363                   !
2364                   IF ( irrig_deficit_glo(ig,ib)  > min_sechiba ) THEN
2365                      !
2366                      streams_around(:,:) = zero
2367                      !
2368                      DO in=1,NbNeighb
2369                         ig2 = neighbours_g(ig,in)
2370                         IF (ig2 .GT. 0 ) THEN
2371                            streams_around(in,:) = stream_reservoir_glo(ig2,:)
2372                            igrd(in) = ig2
2373                         ENDIF
2374                      ENDDO
2375                      !
2376                      IF ( MAXVAL(streams_around) .GT. zero ) THEN
2377                         !
2378                         ff=MAXLOC(streams_around)
2379                         ig2=igrd(ff(1))
2380                         ib2=ff(2)
2381                         !
2382                         IF ( routing_area_glo(ig2,ib2) .GT. 0 .AND. stream_reservoir_glo(ig2,ib2) > zero ) THEN
2383                            adduction = MIN(irrig_deficit_glo(ig,ib), stream_reservoir_glo(ig2,ib2))
2384                            stream_reservoir_glo(ig2,ib2) = stream_reservoir_glo(ig2,ib2) - adduction
2385                            irrig_deficit_glo(ig,ib) = irrig_deficit_glo(ig,ib) - adduction
2386                            irrig_adduct_glo(ig,ib) = irrig_adduct_glo(ig,ib) + adduction
2387                         ENDIF
2388                         !
2389                      ENDIF
2390                      !
2391                   ENDIF
2392                   !
2393                ENDDO
2394             ENDIF
2395          ENDDO
2396          !
2397       ENDIF
2398       !
2399
2400       CALL scatter(irrig_deficit_glo, irrig_deficit)
2401       CALL scatter(stream_reservoir_glo,  stream_reservoir)
2402       CALL scatter(irrig_adduct_glo, irrig_adduct)
2403
2404       DEALLOCATE(irrig_deficit_glo, stream_reservoir_glo, irrig_adduct_glo)
2405
2406    ENDIF
2407
2408    !! Calculate the net water flow to each routing reservoir (in kg/dt)
2409    !! to further diagnose the corresponding water budget residu
2410    !! in routing_main
2411
2412    netflow_fast_diag(:) = zero
2413    netflow_slow_diag(:) = zero
2414    netflow_stream_diag(:) = zero
2415
2416    DO ib=1,nbasmax
2417       DO ig=1,nbpt
2418          netflow_fast_diag(ig) = netflow_fast_diag(ig) + runoff(ig)*routing_area(ig,ib) &
2419               - fast_flow(ig,ib) - pond_inflow(ig,ib)
2420          netflow_slow_diag(ig) = netflow_slow_diag(ig) + drainage(ig)*routing_area(ig,ib) &
2421               - slow_flow(ig,ib)
2422          netflow_stream_diag(ig) = netflow_stream_diag(ig) + flood_flow(ig,ib) + transport(ig,ib) &
2423               - stream_flow(ig,ib) - return_swamp(ig,ib) - floods(ig,ib)
2424       ENDDO
2425    ENDDO
2426
2427    !! Grid cell averaging
2428    DO ig=1,nbpt
2429       netflow_fast_diag(ig) = netflow_fast_diag(ig)/totarea(ig)
2430       netflow_slow_diag(ig) = netflow_slow_diag(ig)/totarea(ig)
2431       netflow_stream_diag(ig) = netflow_stream_diag(ig)/totarea(ig)
2432    ENDDO
2433
2434    !
2435    !
2436    ! Compute the fluxes which leave the routing scheme
2437    !
2438    ! Lakeinflow is in Kg/dt
2439    ! returnflow is in Kg/m^2/dt
2440    !
2441    hydrographs(:) = zero
2442    slowflow_diag(:) = zero
2443    fast_diag(:) = zero
2444    slow_diag(:) = zero
2445    stream_diag(:) = zero
2446    flood_diag(:) =  zero
2447    pond_diag(:) =  zero
2448    irrigation(:) = zero
2449    !
2450    !
2451    DO ib=1,nbasmax
2452       !
2453       DO ig=1,nbpt
2454          IF (hydrodiag(ig,ib) > 0 ) THEN
2455             hydrographs(ig) = hydrographs(ig) + fast_flow(ig,ib) + slow_flow(ig,ib) + & 
2456                  &  stream_flow(ig,ib) 
2457             slowflow_diag(ig) = slowflow_diag(ig) + slow_flow(ig,ib)
2458          ENDIF
2459          fast_diag(ig) = fast_diag(ig) + fast_reservoir(ig,ib)
2460          slow_diag(ig) = slow_diag(ig) + slow_reservoir(ig,ib)
2461          stream_diag(ig) = stream_diag(ig) + stream_reservoir(ig,ib)
2462          flood_diag(ig) = flood_diag(ig) + flood_reservoir(ig,ib)
2463          irrigation (ig) = irrigation (ig) + irrig_actual(ig,ib) + irrig_adduct(ig,ib)
2464       ENDDO
2465    ENDDO
2466    !
2467    DO ig=1,nbpt
2468       fast_diag(ig) = fast_diag(ig)/totarea(ig)
2469       slow_diag(ig) = slow_diag(ig)/totarea(ig)
2470       stream_diag(ig) = stream_diag(ig)/totarea(ig)
2471       flood_diag(ig) = flood_diag(ig)/totarea(ig)
2472       pond_diag(ig) = pond_reservoir(ig)/totarea(ig)
2473       !
2474       irrigation(ig) = irrigation(ig)/totarea(ig)
2475       !
2476       ! The three output types for the routing : endoheric basins,, rivers and
2477       ! diffuse coastal flow.
2478       !
2479       lakeinflow(ig) = transport(ig,nbasmax+1)
2480       coastalflow(ig) = transport(ig,nbasmax+2)
2481       riverflow(ig) = transport(ig,nbasmax+3)
2482       !
2483    ENDDO
2484    !
2485    flood_res = flood_diag + pond_diag
2486   
2487
2488    !! Remove water from lake reservoir if it exceeds the maximum limit and distribute it
2489    !! uniformly over all possible the coastflow gridcells
2490   
2491    ! Calculate lake_overflow and remove it from lake_reservoir
2492    DO ig=1,nbpt
2493       lake_overflow(ig) = MAX(0., lake_reservoir(ig) - max_lake_reservoir*totarea(ig))
2494       lake_reservoir(ig) = lake_reservoir(ig) - lake_overflow(ig)
2495    END DO
2496    ! Transform lake_overflow from kg/grid-cell/dt_routing into kg/m^2/s
2497    CALL xios_orchidee_send_field("lake_overflow",lake_overflow(:)/totarea(:)/dt_routing)
2498
2499    ! Calculate the sum of the lake_overflow and distribute it uniformly over all gridboxes
2500    CALL gather(lake_overflow,lake_overflow_g)
2501    IF (is_root_prc) THEN
2502       total_lake_overflow=SUM(lake_overflow_g)
2503    END IF
2504    CALL bcast(total_lake_overflow)
2505
2506    ! Distribute the lake_overflow uniformly over all coastal gridcells
2507    ! lake_overflow_coast is only calculated to be used as diagnostics if needed
2508    DO ig=1,nbpt
2509       coastalflow(ig) = coastalflow(ig) + total_lake_overflow/nb_coast_gridcells * mask_coast(ig)
2510       lake_overflow_coast(ig) = total_lake_overflow/nb_coast_gridcells * mask_coast(ig)
2511    END DO
2512    ! Transform from kg/grid-cell/dt_routing into m^3/grid-cell/s to match output unit of coastalflow
2513    CALL xios_orchidee_send_field("lake_overflow_coast",lake_overflow_coast/mille/dt_routing)
2514   
2515
2516  END SUBROUTINE routing_flow
2517  !
2518!! ================================================================================================================================
2519!! SUBROUTINE   : routing_lake
2520!!
2521!>\BRIEF        : This subroutine stores water in lakes so that it does not cycle through the runoff.
2522!!                For the moment it only works for endoheric lakes but I can be extended in the future.
2523!!
2524!! DESCRIPTION (definitions, functional, design, flags): The return flow to the soil moisture reservoir
2525!! is based on a maximum lake evaporation rate (maxevap_lake). \n
2526!!
2527!! RECENT CHANGE(S): None
2528!!
2529!! MAIN OUTPUT VARIABLE(S):
2530!!
2531!! REFERENCES   : None
2532!!
2533!! FLOWCHART    :None
2534!! \n
2535!_ ================================================================================================================================
2536
2537  SUBROUTINE routing_lake(nbpt, dt_routing, lakeinflow, humrel, return_lakes)
2538    !
2539    IMPLICIT NONE
2540    !
2541!! INPUT VARIABLES
2542    INTEGER(i_std), INTENT(in) :: nbpt               !! Domain size (unitless)
2543    REAL(r_std), INTENT (in)   :: dt_routing         !! Routing time step (s)
2544    REAL(r_std), INTENT(out)    :: lakeinflow(nbpt)   !! Water inflow to the lakes (kg/dt)
2545    REAL(r_std), INTENT(in)    :: humrel(nbpt)       !! Soil moisture stress, root extraction potential (unitless)
2546    !
2547!! OUTPUT VARIABLES
2548    REAL(r_std), INTENT(out)   :: return_lakes(nbpt) !! Water from lakes flowing back into soil moisture (kg/m^2/dt)
2549    !
2550!! LOCAL VARIABLES
2551    INTEGER(i_std)             :: ig                 !! Indices (unitless)
2552    REAL(r_std)                :: refill             !!
2553    REAL(r_std)                :: total_area         !! Sum of all the surfaces of the basins (m^2)
2554
2555!_ ================================================================================================================================
2556    !
2557    !
2558    DO ig=1,nbpt
2559       !
2560       total_area = SUM(routing_area(ig,:))
2561       !
2562       lake_reservoir(ig) = lake_reservoir(ig) + lakeinflow(ig)
2563       
2564       IF ( doswamps ) THEN
2565          ! Calculate a return flow that will be extracted from the lake reservoir and reinserted in the soil in hydrol
2566          ! Uptake in Kg/dt
2567          refill = MAX(zero, maxevap_lake * (un - humrel(ig)) * dt_routing * total_area)
2568          return_lakes(ig) = MIN(refill, lake_reservoir(ig))
2569          lake_reservoir(ig) = lake_reservoir(ig) - return_lakes(ig)
2570          ! Return in Kg/m^2/dt
2571          return_lakes(ig) = return_lakes(ig)/total_area
2572       ELSE
2573          return_lakes(ig) = zero
2574       ENDIF
2575
2576       ! This is the volume of the lake scaled to the entire grid.
2577       ! It would be better to scale it to the size of the lake
2578       ! but this information is not yet available.
2579       lake_diag(ig) = lake_reservoir(ig)/total_area
2580
2581       lakeinflow(ig) = lakeinflow(ig)/total_area
2582
2583    ENDDO
2584    !
2585  END SUBROUTINE routing_lake
2586  !
2587
2588!! ================================================================================================================================
2589!! SUBROUTINE   : routing_diagnostic_p
2590!!
2591!>\BRIEF         This parallelized subroutine gives a diagnostic of the basins used
2592!!
2593!! DESCRIPTION (definitions, functional, design, flags) : None
2594!!
2595!! RECENT CHANGE(S): None
2596!!
2597!! MAIN OUTPUT VARIABLE(S):
2598!!
2599!! REFERENCES   : None
2600!!
2601!! FLOWCHART    : None
2602!! \n
2603!_ ================================================================================================================================
2604
2605  SUBROUTINE routing_diagnostic_p(nbpt, index, lalo, resolution, contfrac, hist_id, hist2_id)
2606    !
2607    IMPLICIT NONE
2608   
2609!! INPUT VARIABLES
2610    INTEGER(i_std), INTENT(in)      :: nbpt               !! Domain size (unitless)
2611    INTEGER(i_std), INTENT(in)      :: index(nbpt)        !! Indices of the points on the map (unitless)
2612    REAL(r_std), INTENT(in)         :: lalo(nbpt,2)       !! Vector of latitude and longitudes (beware of the order !)
2613    REAL(r_std), INTENT(in)         :: resolution(nbpt,2) !! The size of each grid box in X and Y (m)
2614    REAL(r_std), INTENT(in)         :: contfrac(nbpt)     !! Fraction of land in each grid box (unitless;0-1)
2615    INTEGER(i_std),INTENT (in)      :: hist_id            !! Access to history file (unitless)
2616    INTEGER(i_std),INTENT (in)      :: hist2_id           !! Access to history file 2 (unitless)
2617    !
2618!! LOCAL VARIABLES
2619    REAL(r_std), DIMENSION(nbpt)    :: nbrivers           !! Number of rivers in the grid (unitless)
2620    REAL(r_std), DIMENSION(nbpt)    :: basinmap           !! Map of basins (unitless)
2621    REAL(r_std), DIMENSION(nbp_glo) :: nbrivers_g         !! Number of rivers in the grid (unitless)
2622    REAL(r_std), DIMENSION(nbp_glo) :: basinmap_g         !! Map of basins (unitless)
2623
2624!_ ================================================================================================================================
2625    routing_area => routing_area_glo 
2626    topo_resid => topo_resid_glo
2627    route_togrid => route_togrid_glo
2628    route_tobasin => route_tobasin_glo
2629    route_nbintobas => route_nbintobas_glo
2630    global_basinid => global_basinid_glo
2631    hydrodiag=>hydrodiag_glo
2632    hydroupbasin=>hydroupbasin_glo
2633   
2634    IF (is_root_prc) CALL routing_diagnostic(nbp_glo, index_g, lalo_g, resolution_g, contfrac_g, nbrivers_g,basinmap_g)
2635
2636    routing_area => routing_area_loc 
2637    topo_resid => topo_resid_loc
2638    route_togrid => route_togrid_loc
2639    route_tobasin => route_tobasin_loc
2640    route_nbintobas => route_nbintobas_loc
2641    global_basinid => global_basinid_loc
2642    hydrodiag=>hydrodiag_loc
2643    hydroupbasin=>hydroupbasin_loc
2644   
2645    CALL scatter(nbrivers_g,nbrivers)
2646    CALL scatter(basinmap_g,basinmap)
2647    CALL scatter(hydrodiag_glo,hydrodiag_loc)
2648    CALL scatter(hydroupbasin_glo,hydroupbasin_loc)
2649       
2650    CALL xios_orchidee_send_field("basinmap",basinmap)
2651    CALL xios_orchidee_send_field("nbrivers",nbrivers)
2652
2653    IF ( .NOT. almaoutput ) THEN
2654       CALL histwrite_p(hist_id, 'basinmap', 1, basinmap, nbpt, index)
2655       CALL histwrite_p(hist_id, 'nbrivers', 1, nbrivers, nbpt, index)
2656    ELSE
2657    ENDIF
2658    IF ( hist2_id > 0 ) THEN
2659       IF ( .NOT. almaoutput ) THEN
2660          CALL histwrite_p(hist2_id, 'basinmap', 1, basinmap, nbpt, index)
2661          CALL histwrite_p(hist2_id, 'nbrivers', 1, nbrivers, nbpt, index)
2662       ELSE
2663       ENDIF
2664    ENDIF
2665   
2666       
2667  END SUBROUTINE routing_diagnostic_p
2668
2669!! ================================================================================================================================
2670!! SUBROUTINE   : routing_diagnostic
2671!!
2672!>\BRIEF         This non-parallelized subroutine gives a diagnostic of the basins used. This produces some information
2673!!               on the rivers which are being diagnosed.
2674!!
2675!! DESCRIPTION (definitions, functional, design, flags) : As not all rivers can be monitored in the model, we will only
2676!! archive num_largest rivers. In this routine we will diagnose the num_largest largest rivers and print to the standard
2677!! output the names of these basins and their area. The list of names of these largest rivers are taken from a list coded in the
2678!! routine routing_names. As this standard output is not sufficient, we will also write it to a netCDF file with the routine
2679!! routing_diagncfile. It is important to keep for diagnostic the fraction of the largest basins in each grid box and keep information
2680!! how they are linked one to the other.
2681!!
2682!! RECENT CHANGE(S): None
2683!!
2684!! MAIN OUTPUT VARIABLE(S): No output variables.
2685!!
2686!! REFERENCES   : None
2687!!
2688!! FLOWCHART    :None
2689!! \n
2690!_ ================================================================================================================================
2691
2692  SUBROUTINE routing_diagnostic(nbpt, l_index, lalo, resolution, contfrac, nbrivers, basinmap)
2693    !
2694    IMPLICIT NONE
2695    !
2696!! INPUT VARIABLES
2697    INTEGER(i_std), INTENT(in)                   :: nbpt                !! Domain size  (unitless)
2698    INTEGER(i_std), INTENT(in)                   :: l_index(nbpt)       !! Indices of the points on the map (unitless)
2699    REAL(r_std), INTENT(in)                      :: lalo(nbpt,2)        !! Vector of latitude and longitudes (beware of the order !)
2700    REAL(r_std), INTENT(in)                      :: resolution(nbpt,2)  !! The size of each grid box in X and Y (m)
2701    REAL(r_std), INTENT(in)                      :: contfrac(nbpt)      !! Fraction of land in each grid box (unitless;0-1)
2702    !
2703!! OUTPUT VARIABLES
2704    REAL(r_std), DIMENSION(nbpt), INTENT(out)    :: nbrivers            !! Number of rivers in the grid (unitless)
2705    REAL(r_std), DIMENSION(nbpt), INTENT(out)    :: basinmap            !! Map of basins (unitless)
2706    !
2707!! LOCAL VARIABLES
2708    INTEGER(i_std), DIMENSION(nbpt,nbasmax)      :: outids              !! IDs of river to which this basin contributes (unitless)
2709    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)  :: pts                 !! List the points belonging to the basin (unitless)
2710    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)  :: ptbas               !! List the basin number for this point (unitless)
2711    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)  :: outpt               !! Outflow point for each basin (unitless)
2712    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)    :: nb_pts              !! Number of points in the basin (unitless)
2713    REAL(r_std), ALLOCATABLE, DIMENSION(:)       :: totarea             !! Total area of basin (m^2)
2714    REAL(r_std), ALLOCATABLE, DIMENSION(:)       :: tmparea             !!
2715    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)    :: topids              !! The IDs of the first num_largest basins (unitless)
2716    CHARACTER(LEN=25), ALLOCATABLE, DIMENSION(:) :: basin_names         !! Names of the rivers (unitless)
2717    CHARACTER(LEN=25)                            :: name_str            !!
2718    !
2719    LOGICAL                                      :: river_file          !! Choose to write a description of the rivers (true/false)
2720    CHARACTER(LEN=80)                            :: river_file_name     !! Filename in which we write the description of the rivers (unitless)
2721    !
2722    CHARACTER(LEN=25), ALLOCATABLE, DIMENSION(:)  :: sorted_names       !!
2723    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: streams_nb         !! Number of streams in basin (unitless)
2724    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: streams_avehops    !! Average number of hops in streams (unitless)
2725    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: streams_minhops    !! Minimum number of hops in streams (unitless)
2726    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: streams_maxhops    !! Minimum number of hops in streams (unitless)
2727    REAL(r_std), ALLOCATABLE, DIMENSION(:)        :: streams_resid      !! Average residence time
2728    !
2729    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: lbasin_area        !!
2730    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: lbasin_uparea      !!
2731    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: lrivercode         !!
2732    !
2733    INTEGER(i_std)                                :: ig, ib, og, ob, ign, ibn, ff(1), ic, icc, nb_small, idbas, slen, ii !! Indices (unitless)
2734    INTEGER(i_std)                                :: ier                !! Error handling
2735    CHARACTER(LEN=3)                              :: nn                 !!
2736    INTEGER(i_std)                                :: name_found         !!
2737    !
2738    REAL(r_std)                                   :: averesid           !!
2739    REAL(r_std), DIMENSION(nbasmax)               :: tmpbas             !!
2740    REAL(r_std), DIMENSION(nbpt,nbasmax)          :: areaupbasin        !!
2741    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: sortedrivs         !!
2742    !
2743    ! Variables for the river coding
2744    !
2745    INTEGER(i_std)                               :: longest_river       !!
2746    INTEGER(i_std)                               :: nbmax               !!
2747    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)  :: allstreams          !!
2748    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)     :: upstreamchange      !!
2749    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)    :: tstreams, tslen, tpts, tptbas, tcode !!
2750    REAL(r_std), ALLOCATABLE, DIMENSION(:)       :: tuparea             !!
2751    REAL(r_std), ALLOCATABLE, DIMENSION(:)       :: tupstreamchange     !!
2752    !
2753    LOGICAL                                      :: err_nbpt_grid_basin !! (true/false)
2754    LOGICAL                                      :: err_basin_number    !! (true/false)
2755
2756!_ ================================================================================================================================
2757    !
2758    !
2759    ALLOCATE(pts(num_largest, nbpt), stat=ier)
2760    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for pts','','')
2761
2762    ALLOCATE(ptbas(num_largest, nbpt), stat=ier)
2763    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for ptbas','','')
2764
2765    ALLOCATE(outpt(num_largest, 2), stat=ier)
2766    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for outpt','','')
2767
2768    ALLOCATE(nb_pts(num_largest), stat=ier)
2769    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for nb_pts','','')
2770
2771    ALLOCATE(totarea(num_largest), tmparea(num_largest), stat=ier)
2772    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for totarea','','')
2773
2774    ALLOCATE(topids(num_largest), stat=ier)
2775    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for topids','','')
2776
2777    ALLOCATE(sortedrivs(num_largest), stat=ier)
2778    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for sortedrivs','','')
2779
2780    ALLOCATE(sorted_names(num_largest), stat=ier)
2781    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for sorted_names','','')
2782
2783    ALLOCATE(streams_nb(num_largest), streams_avehops(num_largest), streams_minhops(num_largest), stat=ier)
2784    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for streams_nb','','')
2785
2786    ALLOCATE(streams_maxhops(num_largest), stat=ier)
2787    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for streams_maxhops','','')
2788
2789    ALLOCATE(streams_resid(num_largest), stat=ier)
2790    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for streams_resid','','')
2791   
2792    ALLOCATE(lbasin_area(num_largest,nbpt), lbasin_uparea(num_largest,nbpt), lrivercode(num_largest,nbpt), stat=ier)
2793    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for lbasin_area','','')
2794   
2795    IF ( .NOT. is_root_prc) THEN
2796       WRITE(numout,*) "routing_diagnostic is not suitable for running in parallel"
2797       WRITE(numout,*) "We are here on a non root processor. is_root_prc = ", is_root_prc
2798       WRITE(numout,*) "STOP from routing_diagnostic"
2799       CALL ipslerr_p(3,'routing_diagnostic','This routine is not suitable for running in parallel','','')
2800    ENDIF
2801   
2802   
2803    !Config Key   = RIVER_DESC
2804    !Config Desc  = Writes out a description of the rivers
2805    !Config If    = RIVER_ROUTING
2806    !Config Def   = n
2807    !Config Help  = This flag allows to write out a file containing the list of
2808    !Config         rivers which are beeing simulated. It provides location of outflow
2809    !Config         drainage area, name and ID.
2810    !Config Units = [FLAG]
2811    !
2812    river_file=.FALSE.
2813    CALL getin('RIVER_DESC', river_file)
2814    !
2815    !Config Key   = RIVER_DESC_FILE
2816    !Config Desc  = Filename in which we write the description of the rivers. If suffix is ".nc" a netCDF file is created
2817    !Config If    = RIVER_DESC
2818    !Config Def   = river_desc.nc
2819    !Config Help  = File name where we will write the information. If the suffix is ".nc" a netCDF file is generated. Else
2820    !Config         a simple text file will contain some information. The netCDF file is valuable for post-processing the
2821    !               data as it will contain the fraction of the large basins in each grid box.
2822    !Config Units = [FILE]
2823    !
2824    river_file_name="river_desc.nc"
2825    CALL getin('RIVER_DESC_FILE', river_file_name)
2826    !
2827    !
2828    ! First we get the list of all river outflow points
2829    ! We work under the assumption that we only have num_largest basins finishing with
2830    ! nbasmax+3. This is checked in routing_truncate.
2831    !
2832    nb_small = 1
2833    outpt(:,:) = -1
2834    ic = 0
2835    DO ig=1,nbpt
2836       DO ib=1,nbasmax
2837          ign = route_togrid(ig, ib)
2838          ibn = route_tobasin(ig, ib)
2839          IF ( ibn .EQ. nbasmax+3) THEN
2840             ic = ic + 1
2841             outpt(ic,1) = ig
2842             outpt(ic,2) = ib
2843             !
2844             ! Get the largest id of the basins we call a river. This is
2845             ! to extract the names of all rivers.
2846             !
2847             IF ( global_basinid(ig,ib) > nb_small ) THEN
2848                nb_small = global_basinid(ig,ib)
2849             ENDIF
2850          ENDIF
2851       ENDDO
2852    ENDDO
2853   
2854    nb_small = MIN(nb_small, 349)
2855   
2856    ALLOCATE(basin_names(nb_small), stat=ier)
2857    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for basins_names','','')
2858
2859    CALL routing_names(nb_small, basin_names)
2860    !
2861    ! Go through all points and basins to see if they outflow as a river and store the
2862    ! information needed in the various arrays.
2863    !
2864    nb_pts(:) = 0
2865    totarea(:) = zero
2866    hydrodiag(:,:) = 0
2867    areaupbasin(:,:) = zero
2868    outids(:,:) = -1
2869    ob = -1
2870    og = -1
2871    lbasin_area(:,:) = zero
2872    lbasin_uparea(:,:) = zero
2873    longest_river = 0
2874    !
2875    err_nbpt_grid_basin = .FALSE.
2876    loopgridbasin : DO ig=1,nbpt
2877       !
2878       DO ib=1,nbasmax
2879          IF ( routing_area(ig,ib) .GT. zero ) THEN
2880             ic = 0
2881             ign = ig
2882             ibn = ib
2883             ! Locate outflow point
2884             DO WHILE (ibn .GT. 0 .AND. ibn .LE. nbasmax .AND. ic .LT. nbasmax*nbpt)
2885                ic = ic + 1
2886                og = ign
2887                ob = ibn
2888                ign = route_togrid(og, ob)
2889                ibn = route_tobasin(og, ob)
2890                areaupbasin(og, ob) = areaupbasin(og, ob) + routing_area(ig,ib)
2891             ENDDO
2892             !
2893             longest_river = MAX(longest_river, ic)
2894             !
2895             ! Now that we have an outflow check if it is one of the num_largest rivers.
2896             ! In this case we keeps the location so we diagnose it.
2897             !
2898             IF ( ibn .EQ. nbasmax + 3) THEN
2899                DO icc = 1,num_largest
2900                   IF ( outpt(icc,1) .EQ. og .AND. outpt(icc,2) .EQ. ob ) THEN
2901                      !
2902                      ! We only keep this point for our map if it is large enough.
2903                      !
2904                      nb_pts(icc) = nb_pts(icc) + 1
2905                      !
2906                      !
2907                      IF ( nb_pts(icc) > nbpt ) THEN
2908                         err_nbpt_grid_basin = .TRUE.
2909                         EXIT loopgridbasin
2910                      ENDIF
2911                      !
2912                      pts(icc, nb_pts(icc)) = ig
2913                      ptbas(icc, nb_pts(icc)) = ib
2914                      totarea(icc) = totarea(icc) + routing_area(ig,ib)
2915                      !
2916                      lbasin_area(icc,nb_pts(icc)) = routing_area(ig,ib)
2917                      !
2918                      ! ID of the river is taken from the last point before the outflow.
2919                      topids(icc) = global_basinid(og,ob)
2920                      outids(ig,ib) = global_basinid(og,ob)
2921                      !
2922                      ! On this gridbox and basin we will diagnose the hydrograph
2923                      !
2924                      hydrodiag(ig, ib) = 1
2925                      !
2926                   ENDIF
2927                ENDDO
2928             ENDIF
2929          ENDIF
2930          !
2931       ENDDO
2932       !
2933    ENDDO loopgridbasin
2934    !
2935    IF ( err_nbpt_grid_basin ) THEN
2936       WRITE(numout, *) "routing_diagnostic : The number of grid points in basin ", icc
2937       WRITE(numout, *) "routing_diagnostic : is larger than anticiped. "
2938       CALL ipslerr_p(3, 'routing_diagnostic', 'We are heading for a out of bounds in arrays pts, ptsbas and lbasin_area.',&
2939                     & 'Increase the last dimension of these arrays.','')
2940    ENDIF
2941    !
2942    ! Now we decide which points we will keep from the largest basins
2943    !
2944    ! Temporary fix
2945    route_nbintobas(:,:) = 0
2946    !
2947    basinmap(:) = zero
2948    DO ig=1,nbpt
2949       !
2950       ! Look for the dominant basin in this grid. This information only affects some
2951       ! diagnostics : hydrographs and saved area upstream.
2952       !
2953       icc = 0
2954       idbas = -1
2955       !
2956       DO ib=1,nbasmax
2957          IF ( outids(ig,ib) > 0 ) THEN
2958             IF ( COUNT(outids(ig,:) == outids(ig,ib)) > icc ) THEN
2959                icc = COUNT(outids(ig,:) == outids(ig,ib))
2960                idbas = outids(ig,ib)
2961             ENDIF
2962          ENDIF
2963       ENDDO
2964       !
2965       ! If we have found a point from the large basins and decided which one
2966       ! takes over this grid then we note it on the map.
2967       ! Clean-up a little the hydrodiag array
2968       !
2969       IF ( idbas > 0 ) THEN
2970          basinmap(ig) = REAL(idbas, r_std)
2971       ENDIF
2972       !
2973       ! Now place the hydrograph diagnostic on the point closest to the
2974       ! ocean.
2975       !
2976       tmpbas(:) = zero
2977       DO ib=1,nbasmax
2978          IF ( outids(ig,ib) .EQ. idbas) THEN
2979             tmpbas(ib) = areaupbasin(ig,ib)
2980          ENDIF
2981       ENDDO
2982       hydrodiag(ig,:) = 0
2983       ff=MAXLOC(tmpbas)
2984       hydrodiag(ig,ff(1)) = 1
2985       hydroupbasin(ig) = areaupbasin(ig,ff(1))
2986       !
2987    ENDDO
2988    !
2989    !
2990    !
2991    tmparea(:) = totarea(:)
2992    DO icc = 1, num_largest
2993       ff = MAXLOC(tmparea)
2994       sortedrivs(icc) = ff(1)
2995       tmparea(ff(1)) = 0.0
2996    ENDDO
2997    !
2998    ! Diagnose the complexity of the basins obtained and determine their code in the Pfafstetter system
2999    !
3000    nbmax=MAXVAL(nb_pts)
3001    ALLOCATE(allstreams(nbmax, longest_river), upstreamchange(nbmax, longest_river), stat=ier)
3002    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for allstreams','','')
3003
3004    ALLOCATE(tstreams(longest_river), tupstreamchange(longest_river), stat=ier)
3005    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for tstreams','','')
3006
3007    ALLOCATE(tslen(nbmax), tpts(nbmax), tptbas(nbmax), tuparea(nbmax), stat=ier)
3008    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for tslen','','')
3009
3010    ALLOCATE(tcode(nbmax), stat=ier)
3011    IF (ier /= 0) CALL ipslerr_p(3,'routing_diagnostic','Pb in allocate for tcode','','')
3012
3013    DO icc = 1, num_largest
3014       !
3015       ! Work through the largest basins
3016       !
3017       idbas = sortedrivs(icc)
3018       !
3019       streams_nb(idbas) = 0
3020       streams_avehops(idbas) = 0
3021       streams_minhops(idbas) = undef_int
3022       streams_maxhops(idbas) = 0
3023       streams_resid(idbas) = zero
3024       tslen(:) = 0
3025       !
3026       allstreams(:,:) = 0
3027       upstreamchange(:,:) = zero
3028       !
3029       DO ii=1,nb_pts(idbas)
3030          !
3031          ig = pts(idbas, ii)
3032          ib = ptbas(idbas, ii)
3033          !
3034          lbasin_uparea(idbas,ii) = areaupbasin(ig,ib)
3035          !
3036          slen = 0
3037          ign = ig
3038          ibn = ib
3039          og = ig
3040          ob = ib
3041          !
3042          averesid = zero
3043          tupstreamchange(:) = zero
3044          ! go to outflow point to count the number of hops
3045          DO WHILE (ibn .GT. 0 .AND. ibn .LE. nbasmax)
3046             ! Store data
3047             slen = slen + 1
3048             tstreams(slen) = ign
3049             tupstreamchange(slen) = areaupbasin(ign,ibn)-areaupbasin(og,ob)
3050             ! Move to next point
3051             og = ign
3052             ob = ibn
3053             ign = route_togrid(og, ob)
3054             ibn = route_tobasin(og, ob)
3055             averesid = averesid + topo_resid(og, ob)**2
3056          ENDDO
3057          !
3058          allstreams(ii,1:slen) = tstreams(slen:1:-1)
3059          upstreamchange(ii,1:slen) = tupstreamchange(slen:1:-1)
3060          tslen(ii) = slen
3061          !
3062          ! Save diagnostics
3063          !
3064          streams_nb(idbas) = streams_nb(idbas) + 1
3065          streams_avehops(idbas) = streams_avehops(idbas) + slen
3066          streams_resid(idbas) = streams_resid(idbas) + SQRT(averesid)
3067          IF ( slen < streams_minhops(idbas) ) THEN
3068             streams_minhops(idbas) = slen
3069          ENDIF
3070          IF ( slen > streams_maxhops(idbas) ) THEN
3071             streams_maxhops(idbas) = slen
3072          ENDIF
3073          !
3074       ENDDO
3075       ! build the average
3076       IF ( streams_nb(idbas) > 0 ) THEN
3077          streams_avehops(idbas) = streams_avehops(idbas)/streams_nb(idbas)
3078          streams_resid(idbas) = streams_resid(idbas)/REAL(streams_nb(idbas), r_std)
3079       ELSE
3080          ! River without streams ... very rare but happens
3081          streams_avehops(idbas) = zero
3082          streams_resid(idbas) = zero
3083          streams_maxhops(idbas) = zero
3084          streams_minhops(idbas) = zero
3085       ENDIF
3086       !
3087       !
3088       ii=nb_pts(idbas)
3089       tpts(:) = 0
3090       tpts(1:ii) = pts(idbas,1:ii)
3091       tptbas(:) = 0
3092       tptbas(1:ii) = ptbas(idbas,1:ii)
3093       tuparea(:) = 0
3094       tuparea(1:ii) = lbasin_uparea(idbas,1:ii)
3095       !
3096       CALL routing_diagcode(ii, tpts, tptbas, tuparea, tslen, MAXVAL(tslen), allstreams, upstreamchange, tcode) 
3097       !
3098       lrivercode(idbas,:) = 0
3099       lrivercode(idbas,1:ii) = tcode(1:ii)
3100       !
3101    ENDDO
3102    !
3103    ! Create the sorted list of names
3104    !
3105    err_basin_number = .FALSE.
3106    DO icc = 1, num_largest
3107       !
3108       ib=sortedrivs(icc)
3109       !
3110       IF ( topids(ib) .GT. nb_small ) THEN
3111          IF (topids(ib) <= 99 ) THEN
3112             WRITE(sorted_names(icc), '("Nb_",I2.2)') topids(ib)
3113          ELSE IF (topids(ib) <= 999 ) THEN
3114             WRITE(sorted_names(icc), '("Nb_",I3.3)') topids(ib)
3115          ELSE IF (topids(ib) <= 9999 ) THEN
3116             WRITE(sorted_names(icc), '("Nb_",I4.4)') topids(ib)
3117          ELSE IF (topids(ib) <= 99999 ) THEN
3118             WRITE(sorted_names(icc), '("Nb_",I5.5)') topids(ib)
3119          ELSE IF (topids(ib) <= 999999 ) THEN
3120             WRITE(sorted_names(icc), '("Nb_",I6.6)') topids(ib)
3121          ELSE
3122             err_basin_number = .TRUE.
3123             EXIT
3124          ENDIF
3125
3126       ELSE
3127          IF (topids(ib) <= -1 ) THEN
3128             WRITE(sorted_names(icc), '("Ne_",I2.2)') -1*topids(ib)
3129          ELSE
3130             IF (printlev >=6) WRITE(numout,*) ">>> nb_small, ib, topids :", nb_small, ib, topids(ib)
3131             sorted_names(icc) = basin_names(topids(ib))
3132          ENDIF
3133       ENDIF
3134       !
3135    ENDDO
3136    !
3137    IF ( err_basin_number ) THEN
3138       CALL ipslerr_p(3, 'routing_diagnostic', 'We found a basin number larger than 999999.',&
3139            & 'This is impossible. Please verify your configuration.','')
3140    ENDIF
3141    !
3142    ! Check for doubles and rename if needed
3143    !
3144    DO icc = 1, num_largest
3145       name_found=0
3146       DO ic=1, num_largest
3147          IF ( TRIM(sorted_names(icc)) == TRIM(sorted_names(ic)) ) THEN
3148             name_found = name_found + 1
3149          ENDIF
3150       ENDDO
3151       
3152       IF ( name_found > 1 ) THEN
3153          DO ic=num_largest,1,-1
3154             IF ( TRIM(sorted_names(icc)) == TRIM(sorted_names(ic)) .AND. name_found > 1 ) THEN
3155                IF ( name_found < 10 ) THEN
3156                   WRITE(nn,'(I1)')  name_found
3157                ELSE IF ( name_found < 100 ) THEN
3158                   WRITE(nn,'(I2)')  name_found
3159                ELSE IF ( name_found < 1000 ) THEN
3160                   WRITE(nn,'(I3)')  name_found
3161                ELSE
3162                   ! Make sur to increase nn size when adding more cases
3163                   CALL ipslerr_p(3, 'routing_diagnostic', &
3164                        'Non of the previous values can fit in the new char', &
3165                        'Add a new condition to deal with it', '')
3166                ENDIF
3167                sorted_names(ic) = TRIM(sorted_names(ic))//TRIM(nn)
3168                name_found = name_found - 1
3169             ENDIF
3170          ENDDO
3171       ENDIF
3172       
3173    ENDDO
3174    !
3175    ! Print to stdout on ROOT_PROC the diagnostics for the largest basins we have found.
3176    !
3177    IF (printlev>=1) THEN
3178       DO icc = 1, num_largest
3179          IF ( nb_pts(sortedrivs(icc)) .GT. 2 ) THEN
3180             name_str = sorted_names(icc)
3181             WRITE(numout,'("Basin ID ", I5," ", A15, " Area [km^2] : ", F13.4, " Nb points : ", I4)')&
3182                  & topids(sortedrivs(icc)), name_str(1:15), totarea(sortedrivs(icc))/1.e6,  nb_pts(sortedrivs(icc))
3183          ENDIF
3184       ENDDO
3185    END IF
3186    !
3187    ! Save some of the basin information into files.
3188    !
3189    IF ( river_file ) THEN
3190
3191       IF ( INDEX(river_file_name,".nc") > 1 ) THEN
3192
3193          CALL routing_diagncfile(river_file_name, nbpt, lalo, nb_pts, topids, sorted_names, sortedrivs, &
3194               &                  pts, lbasin_area, lbasin_uparea, lrivercode, outpt, streams_nb, streams_avehops, &
3195               &                  streams_minhops, streams_maxhops, streams_resid)
3196
3197       ELSE
3198
3199          OPEN(diagunit, FILE=river_file_name)
3200          WRITE(diagunit,'(A)') "Basin ID, Area [km^2], Nb points, Lon and Lat of outflow"
3201          WRITE(diagunit,'(A)') "Nb streams, total number of hops, min, ave and max number of hops per stream"
3202          !
3203          DO icc = 1, num_largest
3204             !
3205             IF ( nb_pts(sortedrivs(icc)) .GT. 2 ) THEN
3206                !
3207                name_str = sorted_names(icc)
3208                !
3209                WRITE(diagunit,'(I5,A25,F14.5,I5,2F9.2)') topids(sortedrivs(icc)), name_str(1:15), totarea(sortedrivs(icc))/1.e6, &
3210                     &    nb_pts(sortedrivs(icc)), lalo(outpt(sortedrivs(icc),1),2), lalo(outpt(sortedrivs(icc),1),1)
3211                WRITE(diagunit,'(5I9,F16.4)') streams_nb(sortedrivs(icc)), &
3212                     & streams_avehops(sortedrivs(icc))*streams_nb(sortedrivs(icc)), &
3213                     & streams_minhops(sortedrivs(icc)), &
3214                     & streams_avehops(sortedrivs(icc)), &
3215                     & streams_maxhops(sortedrivs(icc)), streams_resid(sortedrivs(icc))
3216                !
3217             ENDIF
3218             !
3219          ENDDO
3220          !
3221          CLOSE(diagunit)
3222          !
3223       ENDIF
3224       !
3225    ENDIF
3226    !
3227    !
3228    nbrivers(:) = zero
3229    DO ig=1,nbpt
3230       nbrivers(ig) = COUNT(route_tobasin(ig,1:nbasmax) == nbasmax+3)
3231    ENDDO
3232    DO ig=1,nbpt
3233       IF ( nbrivers(ig) > 1 ) THEN
3234          WRITE(numout,*) 'Grid box ', ig, ' has ', NINT(nbrivers(ig)), ' outflow points.'
3235          WRITE(numout,*) 'The rivers which flow into the ocean at this point are :'
3236          DO icc=1,nbasmax
3237             IF ( route_tobasin(ig,icc) == nbasmax+3) THEN
3238                IF ( global_basinid(ig,icc) <= nb_small ) THEN
3239                   WRITE(numout,*) 'ID = ',global_basinid(ig,icc), ' Name = ', basin_names(global_basinid(ig,icc))
3240                ELSE
3241                   WRITE(numout,*) 'ID = ',global_basinid(ig,icc), ' Problem ===== ID is larger than possible'
3242                ENDIF
3243             ENDIF
3244          ENDDO
3245       ENDIF
3246    ENDDO
3247    !
3248    ic = COUNT(topo_resid .GT. 0.)
3249    IF (printlev>=1) THEN
3250       WRITE(numout,*) 'Maximum topographic index :', MAXVAL(topo_resid)
3251       WRITE(numout,*) 'Mean topographic index :', SUM(topo_resid, MASK=topo_resid .GT. zero)/ic
3252       WRITE(numout,*) 'Minimum topographic index :', MINVAL(topo_resid, MASK=topo_resid .GT. zero)
3253    END IF
3254   
3255    DEALLOCATE(pts)
3256    DEALLOCATE(outpt)
3257    DEALLOCATE(nb_pts)
3258    DEALLOCATE(totarea, tmparea)
3259    DEALLOCATE(streams_nb, streams_avehops, streams_minhops, streams_maxhops)
3260    !
3261    DEALLOCATE(lbasin_area, lbasin_uparea, lrivercode)
3262    !
3263    DEALLOCATE(allstreams)
3264    DEALLOCATE(tstreams)
3265    DEALLOCATE(tslen, tpts, tptbas, tuparea)
3266    DEALLOCATE(tcode)
3267    !
3268    ic = COUNT(topo_resid .GT. 0.)
3269    IF (printlev>=1) THEN
3270       WRITE(numout,*) 'Maximum topographic index :', MAXVAL(topo_resid)
3271       WRITE(numout,*) 'Mean topographic index :', SUM(topo_resid, MASK=topo_resid .GT. 0.)/ic
3272       WRITE(numout,*) 'Minimum topographic index :', MINVAL(topo_resid, MASK=topo_resid .GT. 0.)
3273    END IF
3274   
3275  END SUBROUTINE routing_diagnostic
3276  !
3277!! ================================================================================================================================
3278!! SUBROUTINE   : routing_diagcode
3279!!
3280!>\BRIEF       This subroutine determines the code in the Pfafstetter system for all points
3281!!              within the given catchment. 
3282!!
3283!! DESCRIPTION (definitions, functional, design, flags) : None
3284!!
3285!! RECENT CHANGE(S): None
3286!!
3287!! MAIN OUTPUT VARIABLE(S): streamcode
3288!!
3289!! REFERENCES   : None
3290!!
3291!! FLOWCHART    :None
3292!! \n
3293!_ ================================================================================================================================
3294
3295  SUBROUTINE routing_diagcode(ip, tpts, tpbas, tuparea, tslen, ls, allstreams, upstreamchange, streamcode) 
3296    !
3297    IMPLICIT NONE
3298    !
3299!! INPUT VARIABLES
3300    INTEGER(i_std), INTENT(in)                   :: ip             !!
3301    INTEGER(i_std), INTENT(in)                   :: ls             !!
3302    INTEGER(i_std), DIMENSION(ip), INTENT(in)    :: tpts           !!
3303    INTEGER(i_std), DIMENSION(ip), INTENT(in)    :: tpbas          !!
3304    REAL(r_std), DIMENSION(ip), INTENT(in)       :: tuparea        !!
3305    INTEGER(i_std), DIMENSION(ip), INTENT(in)    :: tslen          !!
3306    INTEGER(i_std), DIMENSION(ip,ls), INTENT(in) :: allstreams     !!
3307    REAL(r_std), DIMENSION(ip,ls), INTENT(in)    :: upstreamchange !!
3308    !
3309!! OUTPUT VARIABLES
3310    INTEGER(i_std), DIMENSION(ip), INTENT(out)   :: streamcode     !!
3311    !
3312!! LOCAL VARIABLES
3313    INTEGER(i_std)                               :: ilev, cntsubbas, ib, ic, i, it, ilevmax, imaxlen, nbzero !!
3314    INTEGER(i_std)                               :: tstreamcode(ip)!!
3315    INTEGER(i_std)                               :: indsubbas(ip)  !!
3316    INTEGER(i_std)                               :: iw(ip)         !!
3317    INTEGER(i_std)                               :: tdiff(ip)      !!
3318    INTEGER(i_std)                               :: tmpjunc(4)     !!
3319    INTEGER(i_std)                               :: junction(4)    !!
3320    INTEGER(i_std)                               :: ff(1)          !!
3321    INTEGER(i_std)                               :: ll             !!
3322    REAL(r_std)                                  :: chguparea(ip)  !!
3323    REAL(r_std)                                  :: largest        !!
3324
3325!_ ================================================================================================================================
3326    !
3327    streamcode(:) = 0
3328    !
3329    ! If we accept 4 grid boxes per coded basin then per level we need at least
3330    ! 4*9=36 boxes.
3331    !
3332    ilevmax = 0
3333    it = ip
3334    DO WHILE (it >= 36)
3335       ilevmax = ilevmax+1
3336       it = it/9
3337    ENDDO
3338    !
3339    DO ilev=1,ilevmax
3340       !
3341       ! Count number of sub-basins we already have
3342       !
3343       cntsubbas=0
3344       tstreamcode(:) = streamcode(:)
3345       DO WHILE ( COUNT(tstreamcode(:) >= 0) > 0 )
3346         cntsubbas=cntsubbas+1
3347         indsubbas(cntsubbas) = MAXVAL(tstreamcode(:))
3348         WHERE ( tstreamcode(:) == indsubbas(cntsubbas) ) tstreamcode = -1
3349       ENDDO
3350       !
3351       ! Go through all these basins in order to find the next Pfafstetter numbers
3352       !
3353       DO ib=1,cntsubbas
3354          !
3355          ! Get all the streams which have the current Pfadstetter number
3356          !
3357          it=0
3358          DO ic=1,ip
3359             IF ( streamcode(ic) == indsubbas(ib) ) THEN
3360                it =it+1
3361                iw(it)=ic 
3362             ENDIF
3363          ENDDO
3364          !
3365          ! Which is the longest stream in this basin ?
3366          !
3367          ff=MAXLOC(tslen(iw(1:it)))
3368          imaxlen=iw(ff(1))
3369          chguparea(:) = zero
3370          chguparea(1:tslen(imaxlen)) = upstreamchange(imaxlen, 1:tslen(imaxlen))
3371          !
3372          IF ( COUNT(chguparea(1:tslen(imaxlen)) > 0) < 4 ) THEN
3373             !
3374             ! If this subbasin is too small we just set all points to zero
3375             !
3376             DO i=1,it
3377                streamcode(iw(i)) = streamcode(iw(i))*10
3378             ENDDO
3379          ELSE
3380             !
3381             ! Else do the Pfafstetter numbering
3382             !
3383             !
3384             ! Where do we have the 4 largest change in upstream area on this stream.
3385             ! This must be the confluence of 2 rivers and thus a junction point.
3386             !
3387             largest=pi*R_Earth*R_Earth
3388             DO i=1,4
3389                ff = MAXLOC(chguparea(1:tslen(imaxlen)), MASK = chguparea(1:tslen(imaxlen)) < largest)
3390                tmpjunc(i) = ff(1)
3391                largest=chguparea(tmpjunc(i))
3392             ENDDO
3393             ! sort junctions to go from the outflow up-stream
3394             ff(1)=0
3395             DO i=1,4
3396                junction(i) = MINVAL(tmpjunc, MASK=tmpjunc > ff(1))
3397                ff(1) = junction(i)
3398             ENDDO
3399             !
3400             ! Find all streams which are identical up to that junction and increase their code accordingly
3401             !
3402             DO i=1,it
3403                ll=MIN(tslen(imaxlen),tslen(iw(i)))
3404                tdiff(1:ll) = allstreams(imaxlen,1:ll)-allstreams(iw(i),1:ll)
3405                nbzero = COUNT(tdiff(1:ll) == 0)
3406                IF (nbzero < junction(1) ) THEN
3407                   ! Before first of the 4 largest basins
3408                   streamcode(iw(i)) = streamcode(iw(i))*10+1
3409                ELSE IF (nbzero == junction(1) ) THEN
3410                   ! Stream part of the first largest basin
3411                   streamcode(iw(i)) = streamcode(iw(i))*10+2
3412                ELSE IF (nbzero < junction(2) ) THEN
3413                   ! Between first and second stream
3414                   streamcode(iw(i)) = streamcode(iw(i))*10+3
3415                ELSE IF (nbzero == junction(2) ) THEN
3416                   ! Stream part of the second basin
3417                   streamcode(iw(i)) = streamcode(iw(i))*10+4
3418                ELSE IF (nbzero < junction(3) ) THEN
3419                   ! In between stream 2 and 3
3420                   streamcode(iw(i)) = streamcode(iw(i))*10+5
3421                ELSE IF (nbzero == junction(3) ) THEN
3422                   ! Part of 3rd basin
3423                   streamcode(iw(i)) = streamcode(iw(i))*10+6
3424                ELSE IF (nbzero < junction(4) ) THEN
3425                   ! In between 3 and 4th basins
3426                   streamcode(iw(i)) = streamcode(iw(i))*10+7
3427                ELSE IF (nbzero == junction(4) ) THEN
3428                   ! Final of the 4 largest basins
3429                   streamcode(iw(i)) = streamcode(iw(i))*10+8
3430                ELSE
3431                   ! The rest of the points and also the basin of the longest stream
3432                   streamcode(iw(i)) = streamcode(iw(i))*10+9
3433                ENDIF
3434             ENDDO
3435          ENDIF
3436       ENDDO
3437       !
3438    ENDDO
3439    !
3440    !
3441  END SUBROUTINE routing_diagcode
3442  !
3443!! ================================================================================================================================
3444!! SUBROUTINE   : routing_diagncfile
3445!!
3446!>\BRIEF         This subroutine creates a netCDF file containing all the informations
3447!!                on the largest rivers which can be used for a refined analysis.
3448!!
3449!! DESCRIPTION (definitions, functional, design, flags) : None
3450!!
3451!! RECENT CHANGE(S): None
3452!!
3453!! MAIN OUTPUT VARIABLE(S): None
3454!!
3455!! REFERENCES   : None
3456!!
3457!! FLOWCHART    : None
3458!! \n
3459!_ ================================================================================================================================
3460
3461  SUBROUTINE routing_diagncfile(river_file_name, nbpt, lalo, nb_pts, topids, sorted_names, sortedrivs, &
3462       &       lbasin_index, lbasin_area, lbasin_uparea, lrivercode, outpt, streams_nb, streams_avehops, &
3463       &       streams_minhops, streams_maxhops, streams_resid)
3464    !
3465    USE netcdf
3466    !
3467    IMPLICIT NONE
3468    !
3469    !
3470!! INPUT VARIABLES
3471    REAL(r_std), INTENT(in)                     :: lalo(nbpt,2)             !! Vector of latitude and longitudes (beware of the order !)
3472
3473!! LOCAL VARIABLES
3474    CHARACTER(LEN=80)                           :: river_file_name          !! Filename in which we write the description of the rivers (1)
3475    INTEGER(i_std)                              :: nbpt                     !! Domain size  (unitless)
3476    INTEGER(i_std), DIMENSION(num_largest)      :: nb_pts                   !! Number of points in the basin (unitless)
3477    INTEGER(i_std), DIMENSION(num_largest)      :: topids                   !! The IDs of the first num_largest basins (unitless)
3478    CHARACTER(LEN=25), DIMENSION(num_largest)   :: sorted_names             !! Names of the basins to be put into the file (unitless)
3479    INTEGER(i_std), DIMENSION(num_largest)      :: sortedrivs               !!
3480    INTEGER(i_std), DIMENSION(num_largest,nbpt) :: lbasin_index             !!
3481    REAL(r_std), DIMENSION(num_largest,nbpt)    :: lbasin_area              !!
3482    REAL(r_std), DIMENSION(num_largest,nbpt)    :: lbasin_uparea            !!
3483    INTEGER(i_std), DIMENSION(num_largest,nbpt) :: lrivercode               !!
3484    !
3485    INTEGER(i_std), DIMENSION(num_largest,2)    :: outpt                    !! Outflow point for each basin (unitless)
3486    INTEGER(i_std), DIMENSION(num_largest)      :: streams_nb               !! Number of streams in basin (unitless)
3487    INTEGER(i_std), DIMENSION(num_largest)      :: streams_avehops          !! Average number of hops in streams (unitless)
3488    INTEGER(i_std), DIMENSION(num_largest)      :: streams_minhops          !! Minimum number of hops in streams (unitless)
3489    INTEGER(i_std), DIMENSION(num_largest)      :: streams_maxhops          !! Minimum number of hops in streams (unitless)
3490    REAL(r_std), DIMENSION(num_largest)         :: streams_resid            !! Average residence time
3491    !
3492    INTEGER(i_std)                              :: icc, fid, iret, ierr_tot, ib, ij, ik, i, j, lcc !! Indices (unitless)
3493    INTEGER(i_std)                              :: nlonid, nlatid, varid, varid2, varid3
3494    INTEGER(i_std)                              :: dims(2)                  !!
3495    REAL(r_std)                                 :: lon_min, lon_max, lat_min, lat_max
3496    CHARACTER(LEN=80)                           :: lon_name, lat_name, var_name, long_name, nc_name, att_str
3497
3498    REAL(r_std)                                 :: basinfrac(iim_g,jjm_g)   !!
3499    REAL(r_std)                                 :: basinuparea(iim_g,jjm_g) !!
3500    INTEGER(i_std)                              :: basincode(iim_g,jjm_g)   !!
3501    !
3502    LOGICAL                                     :: check=.FALSE.            !! (true/false)
3503    !
3504!! PARAMETERS
3505    INTEGER(i_std),PARAMETER                    :: kind_r_diag=NF90_REAL8   !!
3506    INTEGER(i_std),PARAMETER                    :: kind_i_diag=NF90_INT     !!
3507
3508!_ ================================================================================================================================
3509    !
3510    !
3511    ! 1.0 Create the NETCDF file and store the coordinates.
3512    !
3513    iret = NF90_CREATE(TRIM(river_file_name), NF90_CLOBBER, fid)
3514    IF (iret /= NF90_NOERR) THEN
3515       CALL ipslerr_p (3,'routing_diagncfile', 'Could not create file :', &
3516            & TRIM(river_file_name), '(Problem with disk place or filename ?)')
3517    ENDIF
3518    !
3519    ! 1.1 Define dimensions
3520    !
3521    IF ( grid_type == regular_lonlat ) THEN
3522       !
3523       ! 1.1.1 regular grid
3524       !
3525       iret = NF90_DEF_DIM(fid, 'lon', iim_g, dims(1))
3526       IF (iret /= NF90_NOERR) THEN
3527          CALL ipslerr_p (3,'routing_diagncfile', 'Dimension "x" can not be defined for the file : ', &
3528               &         TRIM(river_file_name),'(Solution ?)')
3529       ENDIF
3530       iret = NF90_DEF_DIM(fid, 'lat', jjm_g, dims(2))
3531       IF (iret /= NF90_NOERR) THEN
3532          CALL ipslerr_p (3,'routing_diagncfile', 'Dimension "y" can not be defined for the file : ', &
3533               &         TRIM(river_file_name),'(Solution ?)')
3534       ENDIF
3535    ELSE
3536       !
3537       ! 1.1.2 irregular grid
3538       !
3539       iret = NF90_DEF_DIM(fid, 'x', iim_g, dims(1))
3540       IF (iret /= NF90_NOERR) THEN
3541          CALL ipslerr_p (3,'routing_diagncfile', 'Dimension "x" can not be defined for the file : ', &
3542               &         TRIM(river_file_name),'(Solution ?)')
3543       ENDIF
3544       
3545       iret = NF90_DEF_DIM(fid, 'y', jjm_g, dims(2))
3546       IF (iret /= NF90_NOERR) THEN
3547          CALL ipslerr_p (3,'routing_diagncfile', 'Dimension "y" can not be defined for the file : ', &
3548               &         TRIM(river_file_name),'(Solution ?)')
3549       ENDIF
3550    ENDIF
3551    !
3552    !
3553    ! 1.2 Define variables and attributes
3554    !
3555    IF ( grid_type == regular_lonlat ) THEN
3556       !
3557       ! 1.2.1 regular grid
3558       !
3559       lon_name = 'lon'
3560       !
3561       iret = NF90_DEF_VAR(fid, lon_name, kind_r_diag, dims(1), nlonid)
3562       IF (iret /= NF90_NOERR) THEN
3563          CALL ipslerr_p (3,'routing_diagncfile', 'Variable '//lon_name//' can not be defined for the file : ', &
3564               &         TRIM(river_file_name),'(Solution ?)')
3565       ENDIF
3566       !
3567       lat_name = 'lat'
3568       iret = NF90_DEF_VAR(fid, lat_name, kind_r_diag, dims(2), nlatid)
3569       IF (iret /= NF90_NOERR) THEN
3570          CALL ipslerr_p (3,'routing_diagncfile', 'Variable '//lat_name//' can not be defined for the file : ', &
3571               &         TRIM(river_file_name),'(Solution ?)')
3572       ENDIF
3573       !
3574    ELSE
3575       !
3576       ! 1.2.2 irregular grid
3577       !
3578       lon_name = 'nav_lon'
3579       !
3580       iret = NF90_DEF_VAR(fid, lon_name, kind_r_diag, dims, nlonid)
3581       IF (iret /= NF90_NOERR) THEN
3582          CALL ipslerr_p (3,'routing_diagncfile', 'Variable '//lon_name//' can not be defined for the file : ', &
3583               &         TRIM(river_file_name),'(Solution ?)')
3584       ENDIF
3585       !
3586       lat_name = 'nav_lat'
3587       iret = NF90_DEF_VAR(fid, lat_name, kind_r_diag, dims, nlatid)
3588       IF (iret /= NF90_NOERR) THEN
3589          CALL ipslerr_p (3,'routing_diagncfile', 'Variable '//lat_name//' can not be defined for the file : ', &
3590               &         TRIM(river_file_name),'(Solution ?)')
3591       ENDIF
3592       !
3593    ENDIF
3594    !
3595    ! 1.3 Add attributes to the coordinate variables
3596    !
3597    iret = NF90_PUT_ATT(fid, nlonid, 'units', "degrees_east") 
3598    IF (iret /= NF90_NOERR) THEN
3599       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lon_name//' for the file :', &
3600            &          TRIM(river_file_name),'(Solution ?)')
3601    ENDIF
3602    !
3603    lon_min = -180.
3604    lon_max = 180.
3605    !
3606    iret = NF90_PUT_ATT(fid, nlonid, 'valid_min', lon_min)
3607    IF (iret /= NF90_NOERR) THEN
3608       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lon_name//' for the file :', &
3609            &          TRIM(river_file_name),'(Solution ?)')
3610    ENDIF
3611    iret = NF90_PUT_ATT(fid, nlonid, 'valid_max', lon_max)
3612    IF (iret /= NF90_NOERR) THEN
3613       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lon_name//' for the file :', &
3614            &          TRIM(river_file_name),'(Solution ?)')
3615    ENDIF
3616    !
3617    iret = NF90_PUT_ATT(fid, nlonid, 'long_name', "Longitude")
3618    IF (iret /= NF90_NOERR) THEN
3619       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lon_name//' for the file :', &
3620            &          TRIM(river_file_name),'(Solution ?)')
3621    ENDIF
3622    iret = NF90_PUT_ATT(fid, nlatid, 'units', "degrees_north")
3623    IF (iret /= NF90_NOERR) THEN
3624       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lat_name//' for the file :', &
3625            &          TRIM(river_file_name),'(Solution ?)')
3626    ENDIF
3627    !
3628    lat_max = 90.
3629    lat_min = -90.
3630    !
3631    iret = NF90_PUT_ATT(fid, nlatid, 'valid_min', lat_min)
3632    IF (iret /= NF90_NOERR) THEN
3633       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lat_name//' for the file :', &
3634            &          TRIM(river_file_name),'(Solution ?)')
3635    ENDIF
3636    iret = NF90_PUT_ATT(fid, nlatid, 'valid_max', lat_max)
3637    IF (iret /= NF90_NOERR) THEN
3638       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lat_name//' for the file :', &
3639            &          TRIM(river_file_name),'(Solution ?)')
3640    ENDIF
3641    iret = NF90_PUT_ATT(fid, nlatid, 'long_name', "Latitude")
3642    IF (iret /= NF90_NOERR) THEN
3643       CALL ipslerr_p (3,'routing_diagncfile', 'Could not add attribut to variable '//lat_name//' for the file :', &
3644            &          TRIM(river_file_name),'(Solution ?)')
3645    ENDIF
3646    !
3647    iret = NF90_ENDDEF(fid)
3648    IF (iret /= NF90_NOERR) THEN
3649       CALL ipslerr_p (3,'routing_diagncfile', 'Could not end definitions in the file : ', &
3650 &          TRIM(river_file_name),'(Solution ?)')
3651    ENDIF
3652    !
3653    !  1.4 Write coordinates
3654    !
3655    IF ( grid_type == regular_lonlat ) THEN
3656       !
3657       ! 1.4.1 regular grid
3658       !
3659       iret = NF90_PUT_VAR(fid, nlonid, lon_g(1:iim_g,1))
3660       IF (iret /= NF90_NOERR) THEN
3661          CALL ipslerr_p (3,'routing_diagncfile', 'Could not put variable nav_lon  in the file : ', &
3662               &          TRIM(river_file_name),'(Solution ?)')
3663       ENDIF
3664       !
3665       iret = NF90_PUT_VAR(fid, nlatid, lat_g(1,1:jjm_g))
3666       IF (iret /= NF90_NOERR) THEN
3667          CALL ipslerr_p (3,'routing_diagncfile', 'Could not put variable nav_lat  in the file : ', &
3668               &          TRIM(river_file_name),'(Solution ?)')
3669       ENDIF
3670    ELSE
3671       !
3672       ! 1.4.2 irregular grid
3673       !
3674       iret = NF90_PUT_VAR(fid, nlonid, lon_g)
3675       IF (iret /= NF90_NOERR) THEN
3676          CALL ipslerr_p (3,'routing_diagncfile', 'Could not put variable nav_lon  in the file : ', &
3677               &          TRIM(river_file_name),'(Solution ?)')
3678       ENDIF
3679       !
3680       iret = NF90_PUT_VAR(fid, nlatid, lat_g)
3681       IF (iret /= NF90_NOERR) THEN
3682          CALL ipslerr_p (3,'routing_diagncfile', 'Could not put variable nav_lat  in the file : ', &
3683               &          TRIM(river_file_name),'(Solution ?)')
3684       ENDIF
3685    ENDIF
3686    !
3687    ! 2.0 Go through all basins and wirte the information into the netCDF file.
3688    !
3689    DO icc = 1, num_largest
3690       !
3691       ! 2.1 Compute the fields to be saved in the file
3692       !
3693       ib=sortedrivs(icc)
3694       !
3695       !
3696       IF ( nb_pts(ib) > 2 ) THEN
3697          !
3698          basinfrac(:,:) = zero
3699          basinuparea(:,:) = zero
3700          basincode(:,:) = zero
3701          !
3702          DO ij=1, nb_pts(ib)
3703
3704             ik=lbasin_index(ib,ij)
3705
3706             j = ((index_g(ik)-1)/iim_g) + 1
3707             i = (index_g(ik)-(j-1)*iim_g)
3708
3709             basinfrac(i,j) = basinfrac(i,j) + lbasin_area(ib,ij)/(resolution_g(ik,1)*resolution_g(ik,2))
3710             basinuparea(i,j) = MAX(basinuparea(i,j), lbasin_uparea(ib,ij))
3711             basincode(i,j) = lrivercode(ib,ij)
3712
3713          ENDDO
3714          !
3715          DO i=1,iim_g
3716             DO j=1,jjm_g
3717                IF ( basinfrac(i,j) <= EPSILON(zero) ) THEN
3718                   basinfrac(i,j) = undef_sechiba
3719                   basinuparea(i,j)  = undef_sechiba
3720                   basincode(i,j)  = undef_int
3721                ELSE
3722                   basinfrac(i,j) = MIN(basinfrac(i,j), un)
3723                ENDIF
3724             ENDDO
3725          ENDDO
3726          !
3727          !
3728          ! 2.2 Define the variables in the netCDF file
3729          !
3730          iret = NF90_REDEF(fid)
3731          IF (iret /= NF90_NOERR) THEN
3732             CALL ipslerr_p (3,'routing_diagncfile', &
3733                  &          'Could not restart definitions in the file : ', &
3734                  &          TRIM(river_file_name),'(Solution ?)')
3735          ENDIF
3736          !
3737          ! Create a name more suitable for a variable in a netCDF file
3738          !
3739          nc_name =  TRIM(sorted_names(icc))
3740          ! Take out all character which could cause problems
3741          lcc=LEN_TRIM(nc_name)
3742          DO ij=1,lcc
3743             IF ( nc_name(ij:ij) == " " ) nc_name(ij:ij) = "_"
3744             IF ( nc_name(ij:ij) == "(" ) nc_name(ij:ij) = "_"
3745             IF ( nc_name(ij:ij) == ")" ) nc_name(ij:ij) = "_"
3746          ENDDO
3747          ! reduce redundant "__"
3748          DO ij=1,lcc
3749             IF ( nc_name(ij:ij+1) == "__" ) nc_name(ij+1:)=nc_name(ij+2:lcc)
3750          ENDDO
3751          lcc=LEN_TRIM(nc_name)
3752          IF ( nc_name(lcc:lcc) == "_" ) nc_name(lcc:lcc) = " "
3753          !
3754          !
3755          ! 2.3 Fraction variable
3756          !
3757          IF (check) WRITE(numout,*) "Define Fraction variable and add attributes"
3758          !
3759          var_name =  TRIM(nc_name)//"_frac"
3760          !
3761          iret = NF90_DEF_VAR(fid, TRIM(var_name), kind_r_diag, dims, varid)
3762          IF (iret /= NF90_NOERR) THEN
3763             CALL ipslerr_p (3,'routing_diagncfile', 'Variable '//TRIM(var_name)//' can not be defined for the file : ', &
3764                  &         TRIM(river_file_name),'(Solution ?)')
3765          ENDIF
3766          !
3767          ierr_tot = 0
3768          ! Units
3769          iret = NF90_PUT_ATT(fid, varid, 'units', "-")
3770          IF (iret /= NF90_NOERR) THEN
3771             WRITE(numout,*) 'Units',  iret
3772             WRITE(numout,*) TRIM(NF90_STRERROR(iret))
3773             ierr_tot = ierr_tot + 1
3774          ENDIF
3775          ! Long name
3776          long_name = "Fraction of basin "//TRIM(sorted_names(icc))//" per grid box"
3777          iret = NF90_PUT_ATT(fid, varid, 'long_name', long_name)
3778          IF (iret /= NF90_NOERR) THEN
3779             WRITE(numout,*) 'Long_Name', long_name, iret
3780             WRITE(numout,*) TRIM(NF90_STRERROR(iret))
3781             ierr_tot = ierr_tot + 1
3782          ENDIF
3783          ! Missing value
3784          iret = NF90_PUT_ATT(fid, varid, 'missing_value', undef_sechiba)
3785          IF (iret /= NF90_NOERR) THEN
3786             WRITE(numout,*) 'Missing value', undef_sechiba, iret
3787             WRITE(numout,*) TRIM(NF90_STRERROR(iret))
3788             ierr_tot = ierr_tot + 1
3789          ENDIF
3790          !
3791          ib=sortedrivs(icc)
3792          IF ( check ) WRITE(numout,*) "Doing basin ", icc," corrsdponding to index = ", ib, "num_largest : ", num_largest
3793          !
3794          ! Nb of grid points in basin
3795          att_str='Nb_of_grid_points_in_basin'
3796          iret = NF90_PUT_ATT(fid, varid, att_str, nb_pts(ib))
3797          IF (iret /= NF90_NOERR) THEN
3798             WRITE(numout,*) 'Nb of grid points in basin', nb_pts(ib), iret
3799             WRITE(numout,*) TRIM(NF90_STRERROR(iret))
3800             ierr_tot = ierr_tot + 1
3801          ENDIF
3802          !
3803          ! Longitude of outflow point
3804          att_str='Longitude_of_outflow_point'
3805          iret = NF90_PUT_ATT(fid, varid, att_str, lalo(outpt(ib,1),2))
3806          IF (iret /= NF90_NOERR) THEN
3807             WRITE(numout,*) 'Longitude of outflow point', lalo(outpt(ib,1),2), iret
3808             WRITE(numout,*) TRIM(NF90_STRERROR(iret))
3809             ierr_tot = ierr_tot + 1
3810          ENDIF
3811          !
3812          ! Latitide of outflow point
3813          att_str='Latitude_of_outflow_point'
3814          iret = NF90_PUT_ATT(fid, varid, att_str, lalo(outpt(ib,1),1))
3815          IF (iret /= NF90_NOERR) THEN
3816             WRITE(numout,*) 'Latitude of outflow point',  lalo(outpt(ib,1),1), iret
3817             WRITE(numout,*) TRIM(NF90_STRERROR(iret))
3818             ierr_tot = ierr_tot + 1
3819          ENDIF
3820          !
3821          ! Number of streams
3822          att_str= 'Number_of_streams'
3823          iret = NF90_PUT_ATT(fid, varid, att_str, streams_nb(ib))
3824          IF (iret /= NF90_NOERR) THEN
3825             WRITE(numout,*) 'Number of streams', streams_nb(ib), iret
3826             WRITE(numout,*) TRIM(NF90_STRERROR(iret))
3827             ierr_tot = ierr_tot + 1
3828          ENDIF
3829          !
3830          ! Total number of hops to go to the oceans
3831          att_str='Total_number_of_hops_to_ocean'
3832          iret = NF90_PUT_ATT(fid, varid, att_str, streams_avehops(ib)*streams_nb(ib))
3833          IF (iret /= NF90_NOERR) THEN
3834             WRITE(numout,*) 'Total number of hops to go to the oceans ', streams_avehops(ib)*streams_nb(ib), iret
3835             ierr_tot = ierr_tot + 1
3836          ENDIF
3837          !
3838          ! Minimum number of hops to go to the ocean for any stream
3839          att_str='Minimum_number_of_hops_to_ocean_for_any_stream'
3840          iret = NF90_PUT_ATT(fid, varid, att_str, streams_minhops(ib))
3841          IF (iret /= NF90_NOERR) THEN
3842             WRITE(numout,*) 'Minimum number of hops to go tp the ocean for any stream', streams_minhops(ib), iret
3843             ierr_tot = ierr_tot + 1
3844          ENDIF
3845          !
3846          ! Average number of hops to go to the ocean for any stream
3847          att_str='Average_number_of_hops_to_ocean_for_any_stream'
3848          iret = NF90_PUT_ATT(fid, varid, att_str, streams_avehops(ib))
3849          IF (iret /= NF90_NOERR) THEN
3850             WRITE(numout,*) 'Average number of hops to go tp the ocean for any stream', streams_avehops(ib), iret
3851             ierr_tot = ierr_tot + 1
3852          ENDIF
3853          !
3854          ! Maximum number of hops to go to the ocean for any stream
3855          att_str='Maximum_number_of_hops_to_ocean_for_any_stream'
3856          iret = NF90_PUT_ATT(fid, varid, att_str, streams_maxhops(ib))
3857          IF (iret /= NF90_NOERR) THEN
3858             WRITE(numout,*) 'Maximum number of hops to go tp the ocean for any stream', streams_maxhops(ib), iret
3859             ierr_tot = ierr_tot + 1
3860          ENDIF
3861          !
3862          ! Average residence time in the basin
3863          att_str='Average_residence_time_in_basin'
3864          iret = NF90_PUT_ATT(fid, varid, att_str, streams_resid(ib))
3865          IF (iret /= NF90_NOERR) THEN
3866             WRITE(numout,*) 'Average residence time in the basin', streams_resid(ib), iret
3867             ierr_tot = ierr_tot + 1
3868          ENDIF
3869          !
3870          IF (ierr_tot > 0 ) THEN
3871             CALL ipslerr_p (3,'routing_diagncfile', 'Could not add some attributes to variable '//var_name//' for the file :', &
3872                  &          TRIM(river_file_name),'(Solution ?)')
3873          ENDIF
3874          !
3875          ! 2.4 Upstream area variable variable
3876          !
3877          IF (check) WRITE(numout,*) "Define Upstream variable and add attributes"
3878          !
3879          ! Create a name more suitable for a variable in a netCDF file
3880          !
3881          var_name =  TRIM(nc_name)//"_upstream"
3882          DO ij=1,LEN_TRIM(var_name)
3883             IF ( var_name(ij:ij) == " " ) var_name(ij:ij) = "_"
3884          ENDDO
3885          !
3886          iret = NF90_DEF_VAR(fid, TRIM(var_name), kind_r_diag, dims, varid2)
3887          IF (iret /= NF90_NOERR) THEN
3888             CALL ipslerr_p (3,'routing_diagncfile', 'Variable '//TRIM(var_name)//' can not be defined for the file : ', &
3889                  &         TRIM(river_file_name),'(Solution ?)')
3890          ENDIF
3891          !
3892          ierr_tot = 0
3893          ! Units
3894          iret = NF90_PUT_ATT(fid, varid2, 'units', "m^2")
3895          IF (iret /= NF90_NOERR) ierr_tot = ierr_tot + 1
3896          ! Long name
3897          long_name = "Upstream area of basin "//TRIM(sorted_names(icc))//" in the grid box"
3898          iret = NF90_PUT_ATT(fid, varid2, 'long_name', long_name)
3899          IF (iret /= NF90_NOERR) ierr_tot = ierr_tot + 1
3900          ! Missing value
3901          iret = NF90_PUT_ATT(fid, varid2, 'missing_value', undef_sechiba)
3902          IF (iret /= NF90_NOERR) ierr_tot = ierr_tot + 1
3903          !
3904          IF (ierr_tot > 0 ) THEN
3905             CALL ipslerr_p (3,'routing_diagncfile', 'Could not add some attributes to variable '//var_name//' for the file :', &
3906                  &          TRIM(river_file_name),'(Solution ?)')
3907          ENDIF
3908          !
3909          ! 2.5 Pfafstetter codes for basins
3910          !
3911          IF (check) WRITE(numout,*) "Define Pfafstetter codes variable and add attributes"
3912          !
3913          var_name =  TRIM(nc_name)//"_coding"
3914          DO ij=1,LEN_TRIM(var_name)
3915             IF ( var_name(ij:ij) == " " ) var_name(ij:ij) = "_"
3916          ENDDO
3917          !
3918          iret = NF90_DEF_VAR(fid, TRIM(var_name), kind_i_diag, dims, varid3)
3919          IF (iret /= NF90_NOERR) THEN
3920             CALL ipslerr_p (3,'routing_diagncfile', 'Variable '//TRIM(var_name)//' can not be defined for the file : ', &
3921                  &         TRIM(river_file_name),'(Solution ?)')
3922          ENDIF
3923          !
3924          ierr_tot = 0
3925          ! Units
3926          iret = NF90_PUT_ATT(fid, varid3, 'units', "-")
3927          IF (iret /= NF90_NOERR) ierr_tot = ierr_tot + 1
3928          ! Long name
3929          long_name = "Pfafstetter codes of grid boxes in basin "//TRIM(sorted_names(icc))
3930          iret = NF90_PUT_ATT(fid, varid3, 'long_name', long_name)
3931          IF (iret /= NF90_NOERR) ierr_tot = ierr_tot + 1
3932          ! Missing value
3933          iret = NF90_PUT_ATT(fid, varid3, 'missing_value', undef_int)
3934          IF (iret /= NF90_NOERR) ierr_tot = ierr_tot + 1
3935          !
3936          IF (ierr_tot > 0 ) THEN
3937             CALL ipslerr_p (3,'routing_diagncfile', 'Could not add some attributes to variable '//var_name//' for the file :', &
3938                  &          TRIM(river_file_name),'(Solution ?)')
3939          ENDIF
3940          !
3941          ! 2.6 ENDDEF of netCDF file
3942          !
3943          IF (check) WRITE(numout,*) "END define"
3944          !
3945          iret = NF90_ENDDEF(fid)
3946          IF (iret /= NF90_NOERR) THEN
3947             CALL ipslerr_p (3,'routing_diagncfile', &
3948                  &          'Could not end definitions in the file : ', &
3949                  &          TRIM(river_file_name),'(Solution ?)')
3950          ENDIF
3951          !
3952          ! 2.7 Write the data to the file
3953          !
3954          IF (check) WRITE(numout,*) "Put basinfrac"
3955          iret = NF90_PUT_VAR(fid, varid, basinfrac)
3956          IF (iret /= NF90_NOERR) THEN
3957             CALL ipslerr_p (3,'routing_diagncfile', 'Could not put variable basinfrac in the file : ', &
3958                  &          TRIM(river_file_name),'(Solution ?)')
3959          ENDIF
3960
3961          IF (check) WRITE(numout,*) "Put basinuparea"
3962          iret = NF90_PUT_VAR(fid, varid2, basinuparea)
3963          IF (iret /= NF90_NOERR) THEN
3964             CALL ipslerr_p (3,'routing_diagncfile', 'Could not put variable basinuparea in the file : ', &
3965                  &          TRIM(river_file_name),'(Solution ?)')
3966          ENDIF
3967
3968          IF (check) WRITE(numout,*) "Put basincode"
3969          iret = NF90_PUT_VAR(fid, varid3, basincode)
3970          IF (iret /= NF90_NOERR) THEN
3971             CALL ipslerr_p (3,'routing_diagfile', 'Could not put variable basincode in the file : ', &
3972                  &          TRIM(river_file_name),'(Solution ?)')
3973          ENDIF
3974          !
3975       ENDIF
3976       !
3977    ENDDO
3978    !
3979    IF (check) WRITE(numout,*) "Close file"
3980    !
3981    ! Close netCDF file and do some memory management.
3982    !
3983    iret = NF90_CLOSE(fid)
3984    IF (iret /= NF90_NOERR) THEN
3985       CALL ipslerr_p (3,'routing_diagncfile', &
3986            &          'Could not end definitions in the file : ', &
3987            &          TRIM(river_file_name),'(Solution ?)')
3988    ENDIF
3989    !
3990    !
3991  END SUBROUTINE routing_diagncfile
3992  !
3993!! ================================================================================================================================
3994!! SUBROUTINE   : routing_basins_p
3995!!
3996!>\BRIEF        This parallelized subroutine computes the routing map if needed.
3997!!
3998!! DESCRIPTION (definitions, functional, design, flags) : None
3999!!
4000!! RECENT CHANGE(S): None
4001!!
4002!! MAIN OUTPUT VARIABLE(S):
4003!!
4004!! REFERENCES   : None
4005!!
4006!! FLOWCHART    : None
4007!! \n
4008!_ ================================================================================================================================
4009
4010  SUBROUTINE routing_basins_p(nbpt, lalo, neighbours, resolution, contfrac)
4011    !
4012    IMPLICIT NONE
4013    !
4014!! INPUT VARIABLES
4015    INTEGER(i_std), INTENT(in) :: nbpt               !! Domain size (unitless)
4016    REAL(r_std), INTENT(in)    :: lalo(nbpt,2)       !! Vector of latitude and longitudes (beware of the order !)
4017    INTEGER(i_std), INTENT(in) :: neighbours(nbpt,NbNeighb) !! Vector of neighbours for each grid point (1=North and then clockwise) (unitless)
4018    REAL(r_std), INTENT(in)    :: resolution(nbpt,2) !! The size of each grid box in X and Y (m)
4019    REAL(r_std), INTENT(in)    :: contfrac(nbpt)     !! Fraction of land in each grid box (unitless;0-1)
4020
4021!_ ================================================================================================================================
4022
4023!    INTEGER(i_std)    :: neighbours_tmp(nbpt,8)
4024!    INTEGER(i_std) :: i,j
4025   
4026!    DO i=1,nbp_loc
4027!      DO j=1,NbNeighb
4028!       IF (neighbours(i,j)==-1) THEN
4029!         neighbours_tmp(i,j)=neighbours(i,j)
4030!       ELSE
4031!         neighbours_tmp(i,j)=neighbours(i,j)+nbp_para_begin(mpi_rank)-1
4032!       ENDIF 
4033!      ENDDO
4034!    ENDDO
4035
4036    routing_area => routing_area_glo 
4037    topo_resid => topo_resid_glo
4038    route_togrid => route_togrid_glo
4039    route_tobasin => route_tobasin_glo
4040    route_nbintobas => route_nbintobas_glo
4041    global_basinid => global_basinid_glo
4042 
4043    IF (is_root_prc) CALL routing_basins(nbp_glo,lalo_g, neighbours_g, resolution_g, contfrac_g)
4044
4045    routing_area => routing_area_loc 
4046    topo_resid => topo_resid_loc
4047    route_togrid => route_togrid_loc
4048    route_tobasin => route_tobasin_loc
4049    route_nbintobas => route_nbintobas_loc
4050    global_basinid => global_basinid_loc
4051
4052    CALL scatter(routing_area_glo,routing_area_loc)
4053    CALL scatter(topo_resid_glo,topo_resid_loc)
4054    CALL scatter(route_togrid_glo,route_togrid_loc)
4055    CALL scatter(route_tobasin_glo,route_tobasin_loc)
4056    CALL scatter(route_nbintobas_glo,route_nbintobas_loc)
4057    CALL scatter(global_basinid_glo,global_basinid_loc)
4058   
4059  END SUBROUTINE routing_basins_p
4060  !
4061 
4062!! ================================================================================================================================
4063!! SUBROUTINE   : routing_basins
4064!!
4065!>\BRIEF        This non-parallelized subroutine reads in the map of basins and flow direction to construct
4066!!              the catchments of each grid box.
4067!!
4068!! DESCRIPTION (definitions, functional, design, flags) :
4069!! The work is done in a number of steps which are performed locally on the
4070!! GCM grid:
4071!!  1) First we find the grid-points of the high resolution routing grid which are
4072!!     within the coarser grid of the GCM.
4073!!  2) When we have these grid points we decompose them into basins in the routine
4074!!     routing_findbasins. A number of simplifications are done if needed.
4075!!  3) In the routine routing_globalize we put the basin information of this grid
4076!!     into the global fields.
4077!! Then we work on the global grid to perform the following tasks :
4078!!  1) We link up the basins of the various grid points and check the global consistency.
4079!!  2) The area of each outflow point is computed.
4080!!  3) The final step is to reduce the number of basins in order to fit into the truncation.\n
4081!!
4082!! RECENT CHANGE(S): None
4083!!
4084!! MAIN OUTPUT VARIABLE(S): None, as the routine puts information into the global variables of the module.
4085!!
4086!! REFERENCES   : None
4087!!
4088!! FLOWCHART    : None
4089!! \n
4090!_ ================================================================================================================================
4091
4092SUBROUTINE routing_basins(nbpt, lalo, neighbours, resolution, contfrac)
4093    !
4094    IMPLICIT NONE
4095    !
4096!! INPUT VARIABLES
4097    INTEGER(i_std), INTENT(in)                    :: nbpt                  !! Domain size (unitless)
4098    REAL(r_std), INTENT(in)                       :: lalo(nbpt,2)          !! Vector of latitude and longitudes (beware of the order !)
4099    INTEGER(i_std), INTENT(in)                    :: neighbours(nbpt,NbNeighb)!! Vector of neighbours for each grid point
4100                                                                           !! (1=North and then cloxkwise)
4101    REAL(r_std), INTENT(in)                       :: resolution(nbpt,2)    !! The size of each grid box in X and Y (m)
4102    REAL(r_std), INTENT(in)                       :: contfrac(nbpt)        !! Fraction of land in each grid box (unitless;0-1)
4103    !
4104!! LOCAL VARIABLES
4105    CHARACTER(LEN=80)                             :: filename              !! Name of the netcdf file (unitless)
4106    INTEGER(i_std)                                :: iml, jml, lml, tml, fid, ib, ip, jp, fopt !! Indices (unitless)
4107    REAL(r_std)                                   :: lev(1), date, dt, coslat
4108    INTEGER(i_std)                                :: itau(1)               !!
4109    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: trip                  !! The trip field (unitless)
4110    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: basins                !! The basin field (unitless)
4111    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: topoindex             !! Topographic index of the residence time (m)
4112    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: hierarchy             !!
4113    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: lat_rel               !!
4114    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: lon_rel               !!
4115    !
4116    INTEGER(i_std)                                :: nbi, nbj              !! Number of point in x and y within the grid (unitless)
4117    REAL(r_std)                                   :: min_topoind           !! The current minimum of topographic index (m)
4118    REAL(r_std)                                   :: max_basins            !!
4119    REAL(r_std)                                   :: invented_basins       !!
4120    !
4121    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: area_bx               !! Area of each small box in the grid box (m^2)
4122    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: hierarchy_bx          !! Level in the basin of the point
4123    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: lon_bx                !!
4124    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: lat_bx                !!
4125    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: topoind_bx            !! Topographic index of the residence time for each of the smaller boxes (m)
4126    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: trip_bx               !! The trip field for each of the smaller boxes (unitless)
4127    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: basin_bx              !!
4128    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: coast_pts             !! The coastal flow points (unitless)
4129    !
4130    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: basin_count           !!
4131    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: basin_id              !!
4132    REAL(r_std),  ALLOCATABLE, DIMENSION(:,:)     :: basin_area            !!
4133    REAL(r_std),  ALLOCATABLE, DIMENSION(:,:)     :: basin_hierarchy       !!
4134    REAL(r_std),  ALLOCATABLE, DIMENSION(:,:)     :: basin_topoind         !! Topographic index of the residence time for a basin (m)
4135    REAL(r_std),  ALLOCATABLE, DIMENSION(:,:)     :: fetch_basin           !!
4136    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: basin_flowdir         !! Water flow directions in the basin (unitless)
4137    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: outflow_grid          !! Type of outflow on the grid box (unitless)
4138    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: outflow_basin         !!
4139    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: inflow_number         !!
4140    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:,:) :: inflow_basin          !!
4141    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:,:) :: inflow_grid           !!
4142    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: nbcoastal             !!
4143    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: coastal_basin         !!
4144    !
4145    ! Interpolation help variables
4146    !
4147    INTEGER(i_std)                                :: nix, njx              !!
4148    CHARACTER(LEN=30)                             :: callsign              !!
4149    REAL(r_std), ALLOCATABLE, DIMENSION(:,:,:)    :: resol_lu              !! Resolution
4150    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)   :: mask                  !! Mask to exclude some points (unitless)
4151    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)      :: sub_area              !! Area on the fine grid (m^2)
4152    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:,:) :: sub_index             !! Indices of the points we need on the fine grid (unitless)
4153    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: sub_pts               !! Number of high resolution points on this grid (unitless)
4154    INTEGER                                       :: ALLOC_ERR             !!
4155    LOGICAL                                       :: ok_interpol = .FALSE. !! Flag for interpolation (true/false)
4156    !
4157    INTEGER(i_std)                                :: nb_basin              !! Number of sub-basins (unitless)
4158    INTEGER(i_std)                                :: nwbas                 !!
4159    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: basin_inbxid          !!
4160    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: basin_sz              !!
4161    INTEGER(i_std), ALLOCATABLE, DIMENSION(:)     :: basin_bxout           !!
4162    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:,:) :: basin_pts             !!
4163    CHARACTER(LEN=7)                              :: fmt                   !!
4164    LOGICAL                                       :: debug = .FALSE.       !! (true/false)
4165    !
4166    INTEGER(i_std), DIMENSION(2)                  :: diagbox = (/ 1, 2 /)  !!
4167
4168!_ ================================================================================================================================
4169    !
4170    !
4171    IF ( .NOT. is_root_prc) THEN
4172       WRITE(numout,*) "is_root_prc = ", is_root_prc
4173       CALL ipslerr_p (3,'routing_basins', &
4174            &          'routing_basins is not suitable for running in parallel', &
4175            &          'We are here on a non root processor. ','(STOP from routing_basins)')
4176    ENDIF
4177    !
4178    ! Test on diagbox and nbpt
4179    !
4180    IF (debug) THEN
4181       IF (ANY(diagbox .GT. nbpt)) THEN
4182          WRITE(numout,*) "Debug diganostics : nbpt, diagbox", nbpt, diagbox
4183          call ipslerr_p(3,'routing_basin', &
4184               &      'Problem with diagbox in debug mode.', & 
4185               &      'diagbox values can''t be greater than land points number.', &
4186               &      '(decrease diagbox wrong value)')
4187       ENDIF
4188    ENDIF
4189    !
4190    !
4191    !  Needs to be a configurable variable
4192    !
4193    !
4194    !Config Key   = ROUTING_FILE
4195    !Config Desc  = Name of file which contains the routing information
4196    !Config If    = RIVER_ROUTING
4197    !Config Def   = routing.nc
4198    !Config Help  = The file provided here should alow the routing module to
4199    !Config         read the high resolution grid of basins and the flow direction
4200    !Config         from one mesh to the other.
4201    !Config Units = [FILE]
4202    !
4203    filename = 'routing.nc'
4204    CALL getin('ROUTING_FILE',filename)
4205    !
4206    CALL flininfo(filename,iml, jml, lml, tml, fid)
4207    CALL flinclo(fid)
4208    !
4209    ! soils_param.nc file is 1° soit texture file.
4210    !
4211    ALLOCATE(lat_rel(iml,jml), STAT=ALLOC_ERR)
4212    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for lat_rel','','')
4213
4214    ALLOCATE(lon_rel(iml,jml), STAT=ALLOC_ERR)
4215    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for lon_rel','','')
4216
4217    ALLOCATE (trip(iml,jml), STAT=ALLOC_ERR)
4218    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for trip','','')
4219
4220    ALLOCATE (basins(iml,jml), STAT=ALLOC_ERR)
4221    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basins','','')
4222
4223    ALLOCATE (topoindex(iml,jml), STAT=ALLOC_ERR)
4224    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for topoindex','','')
4225
4226    ALLOCATE (hierarchy(iml,jml), STAT=ALLOC_ERR)
4227    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for hierarchy','','')
4228
4229    !
4230    CALL flinopen(filename, .FALSE., iml, jml, lml, lon_rel, lat_rel, lev, tml, itau, date, dt, fid)
4231    !!
4232    !! From the basin description data we will read the following variables :
4233    !!
4234    !! Trip : Provides the flow direction following the convention :
4235    !! trip = 1 : flow = N
4236    !! trip = 2 : flow = NE
4237    !! trip = 3 : flow = E
4238    !! trip = 4 : flow = SE
4239    !! trip = 5 : flow = S
4240    !! trip = 6 : flow = SW
4241    !! trip = 7 : flow = W
4242    !! trip = 8 : flow = NW
4243    !! trip = 97 : return flow into the ground
4244    !! trip = 98 : coastal flow (diffuse flow into the oceans)
4245    !! trip = 99 : river flow into the oceans
4246    !!
4247    !! Basins : Provides a uniqe ID for each basin. These IDs are also used to get
4248    !! the name of the basin from the table in routine routing_names.
4249    !!
4250    !! Topoind :  is the topographic index for the retention time of the water in the
4251    !! grid box. It has been computed with the following formula : 1000 x sqrt(d^3/Dz)
4252    !! where d is the distance of the river from the current grid box to the next one
4253    !! as indicated by the variable trip.
4254    !! Dz the hight difference between between the two grid boxes.
4255    !! All these variables are in meters.
4256    !! Furthermore  we have to limit the height difference to 5m in order to avoid any unpleasant
4257    !! surprises. If dz < 5m then dz=5.
4258    !!
4259    !
4260    CALL flinget(fid, 'trip', iml, jml, lml, tml, 1, 1, trip)
4261    !
4262    CALL flinget(fid, 'basins', iml, jml, lml, tml, 1, 1, basins)
4263    !
4264    CALL flinget(fid, 'topoind', iml, jml, lml, tml, 1, 1, topoindex)
4265    !
4266    CALL flinclo(fid)
4267    !
4268    min_topoind = MINVAL(topoindex, MASK=topoindex .LT. undef_sechiba-un)
4269    !
4270    DO ip=1,iml
4271       DO jp=1,jml
4272          IF ( trip(ip,jp) < 1.e10 .AND. topoindex(ip,jp) > 1.e10) THEN
4273             WRITE(numout,*) 'trip exists but not topoind :'
4274             WRITE(numout,*) 'ip, jp :', ip, jp
4275             WRITE(numout,*) 'trip, topoind : ', trip(ip,jp), topoindex(ip,jp)
4276             CALL ipslerr_p(3,'routing_basins','trip exists but not topoind','','')
4277          ENDIF
4278       ENDDO
4279    ENDDO
4280
4281    ALLOCATE(resol_lu(iml,jml,2), STAT=ALLOC_ERR)
4282    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for resol_lu','','')
4283
4284    ALLOCATE(mask(iml,jml), STAT=ALLOC_ERR)
4285    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for mask','','')
4286    !
4287    ! Consider all points a priori
4288    !
4289    mask(:,:) = 0
4290    !
4291    DO ip=1,iml
4292       DO jp=1,jml
4293          !
4294          ! Determine the land mask of the basin map read from the file ROUTING_FILE
4295          !
4296          IF ( trip(ip,jp) < 1.e10 ) THEN
4297             mask(ip,jp) = 1
4298          ENDIF
4299          !
4300          ! Resolution in longitude
4301          !
4302          coslat = MAX( COS( lat_rel(ip,jp) * pi/180. ), mincos )     
4303          IF ( ip .EQ. 1 ) THEN
4304             resol_lu(ip,jp,1) = ABS( lon_rel(ip+1,jp) - lon_rel(ip,jp) ) * pi/180. * R_Earth * coslat
4305          ELSEIF ( ip .EQ. iml ) THEN
4306             resol_lu(ip,jp,1) = ABS( lon_rel(ip,jp) - lon_rel(ip-1,jp) ) * pi/180. * R_Earth * coslat
4307          ELSE
4308             resol_lu(ip,jp,1) = ABS( lon_rel(ip+1,jp) - lon_rel(ip-1,jp) )/2. * pi/180. * R_Earth * coslat
4309          ENDIF
4310          !
4311          ! Resolution in latitude
4312          !
4313          IF ( jp .EQ. 1 ) THEN
4314             resol_lu(ip,jp,2) = ABS( lat_rel(ip,jp) - lat_rel(ip,jp+1) ) * pi/180. * R_Earth
4315          ELSEIF ( jp .EQ. jml ) THEN
4316             resol_lu(ip,jp,2) = ABS( lat_rel(ip,jp-1) - lat_rel(ip,jp) ) * pi/180. * R_Earth
4317          ELSE
4318             resol_lu(ip,jp,2) =  ABS( lat_rel(ip,jp-1) - lat_rel(ip,jp+1) )/2. * pi/180. * R_Earth
4319          ENDIF
4320          !
4321       ENDDO
4322    ENDDO
4323    !
4324    ! The maximum number of points of the source map (basin description here) which can fit into
4325    ! any grid point of the ORCHIDEE grid is stimated here.
4326    ! Some margin is taken.
4327    !
4328    callsign = "routing_basins"
4329    ok_interpol = .FALSE.
4330   
4331    nix=INT(MAXVAL(resolution_g(:,1))/MAXVAL(resol_lu(:,:,1)))+2
4332    njx=INT(MAXVAL(resolution_g(:,2))/MAXVAL(resol_lu(:,:,2)))+2
4333    nbvmax = nix*njx*2
4334    !
4335    ! We are on the root processor here as this routine is not in parallel. So no need to broadcast.
4336    !
4337    IF (printlev >=1) THEN
4338       WRITE(numout,*) "Projection arrays for ",callsign," : "
4339       WRITE(numout,*) "Routing : nbvmax = ", nbvmax
4340    END IF
4341
4342    ALLOCATE (sub_area(nbpt,nbvmax), STAT=ALLOC_ERR)
4343    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for sub_area','','')
4344    sub_area(:,:)=zero
4345
4346    ALLOCATE (sub_index(nbpt,nbvmax,2), STAT=ALLOC_ERR)
4347    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for sub_index','','')
4348    sub_index(:,:,:)=0
4349
4350    ALLOCATE (sub_pts(nbpt), STAT=ALLOC_ERR)
4351    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for sub_pts','','')
4352    sub_pts(:)=0
4353    !
4354    ! routine aggregate will for each point of the ORCHIDEE grid determine which points
4355    ! of the source grid (basin definitions here) fit in there and which fraction of
4356    ! of the ORCHIDEE grid it represents.
4357    !
4358    CALL aggregate(nbpt, lalo, neighbours, resolution, contfrac, &
4359         &                iml, jml, lon_rel, lat_rel, mask, callsign, &
4360         &                nbvmax, sub_index, sub_area, ok_interpol)
4361    !
4362    WHERE (sub_area < 0) sub_area=zero
4363    !
4364    ! Some verifications
4365    !
4366    DO ib=1,nbpt
4367       sub_pts(ib) = COUNT(sub_area(ib,:) > zero)
4368       DO fopt=1,sub_pts(ib)
4369          IF (sub_area(ib, fopt) == 0 ) THEN
4370             WRITE(numout,*) "Zero Area - Sub_area > 0 : ", ib, fopt
4371             WRITE(numout,*) "Zero Area - lon : ",lalo(ib,2)
4372             WRITE(numout,*) "Zero Area - lon_rel : ", lon_rel(sub_index(ib, fopt, 1),sub_index(ib, fopt, 2))
4373             WRITE(numout,*) "Zero Area - lat : ",lalo(ib,1)
4374             WRITE(numout,*) "Zero Area - lat_rel : ", lat_rel(sub_index(ib, fopt, 1),sub_index(ib, fopt, 2))
4375          ENDIF
4376       ENDDO
4377    ENDDO
4378    !
4379    ! Do some memory management.
4380    !
4381    nwbas = MAX(MAXVAL(sub_pts), NbNeighb+1)
4382    !
4383    ALLOCATE (area_bx(nbvmax,nbvmax), stat=ALLOC_ERR)
4384    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for area_bx','','')
4385    ALLOCATE (hierarchy_bx(nbvmax,nbvmax), stat=ALLOC_ERR)
4386    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for hierarchy_bx','','')
4387    ALLOCATE (lon_bx(nbvmax,nbvmax), stat=ALLOC_ERR)
4388    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for lon_bx','','')
4389    ALLOCATE (lat_bx(nbvmax,nbvmax), stat=ALLOC_ERR)
4390    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for lat_bx','','')
4391    ALLOCATE (topoind_bx(nbvmax,nbvmax), stat=ALLOC_ERR)
4392    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for topoind_bx','','')
4393    ALLOCATE (trip_bx(nbvmax,nbvmax), stat=ALLOC_ERR)
4394    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for trip_bx','','')
4395    ALLOCATE (basin_bx(nbvmax,nbvmax), stat=ALLOC_ERR)
4396    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_bx','','')
4397    ALLOCATE (coast_pts(nbvmax), stat=ALLOC_ERR)
4398    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for coast_pts','','')
4399    ALLOCATE (basin_inbxid(nbvmax), stat=ALLOC_ERR)
4400    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_inbxid','','')
4401    ALLOCATE (basin_sz(nbvmax), stat=ALLOC_ERR)
4402    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_sz','','')
4403    ALLOCATE (basin_pts(nbvmax,nbvmax,2), stat=ALLOC_ERR)
4404    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_pts','','')
4405    ALLOCATE (basin_bxout(nbvmax), stat=ALLOC_ERR)
4406    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_bxout','','')
4407    ALLOCATE (basin_count(nbpt), stat=ALLOC_ERR)
4408    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_count','','')
4409    ALLOCATE (basin_area(nbpt,nwbas), basin_hierarchy(nbpt,nwbas), basin_topoind(nbpt,nwbas), stat=ALLOC_ERR)
4410    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_area','','')
4411    ALLOCATE (fetch_basin(nbpt,nwbas), stat=ALLOC_ERR)
4412    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for fetch_basin','','')
4413    ALLOCATE (basin_id(nbpt,nwbas),  basin_flowdir(nbpt,nwbas), stat=ALLOC_ERR)
4414    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for basin_id','','')
4415    ALLOCATE (outflow_grid(nbpt,nwbas),outflow_basin(nbpt,nwbas), stat=ALLOC_ERR)
4416    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for outflow_grid','','')
4417    ALLOCATE (inflow_number(nbpt,nwbas), stat=ALLOC_ERR)
4418    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for inflow_number','','')
4419    ALLOCATE (inflow_basin(nbpt,nwbas,nbvmax), inflow_grid(nbpt,nwbas,nbvmax), stat=ALLOC_ERR)
4420    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for inflow_basin','','')
4421    ALLOCATE (nbcoastal(nbpt), coastal_basin(nbpt,nwbas), stat=ALLOC_ERR)
4422    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_basins','Pb in allocate for nbcoastal','','')
4423   
4424    !    Order all sub points in each grid_box and find the sub basins
4425    !
4426    !    before we start we set the maps to empty
4427    !
4428    basin_id(:,:) = undef_int
4429    basin_count(:) = 0
4430    hierarchy(:,:) = undef_sechiba
4431    max_basins = MAXVAL(basins, MASK=basins .LT. 1.e10)
4432    invented_basins = max_basins
4433    nbcoastal(:) = 0
4434    !
4435    !! Finds,in each grid box, the distance to the outflow point ... this defines the order in which
4436    !! the water will go through the sub-basins and grid boxes.
4437    !
4438    CALL routing_hierarchy(iml, jml, trip, topoindex, hierarchy)
4439    !
4440    !
4441    DO ib =1, nbpt
4442       !
4443       !
4444       !  extract the information for this grid box
4445       !
4446       !! Extracts from the global high resolution fields the data for the current grid box.
4447       !
4448       CALL routing_getgrid(nbpt, iml, jml, ib, sub_pts, sub_index, sub_area, max_basins, min_topoind, &
4449            & lon_rel, lat_rel, lalo, resolution, contfrac, trip, basins, topoindex, hierarchy, &
4450            & nbi, nbj, area_bx, trip_bx, basin_bx, topoind_bx, hierarchy_bx, lon_bx, lat_bx)
4451       !
4452       !! Finds the basins: returns the list of all points which are within the same basin of the grid box.
4453       !
4454       CALL routing_findbasins(nbi, nbj, trip_bx, basin_bx, hierarchy_bx, topoind_bx,&
4455            & nb_basin, basin_inbxid, basin_sz, basin_bxout, basin_pts, coast_pts)
4456       !
4457       !  Deal with the case where nb_basin=0 for this grid box. In this case all goes into coastal flow.
4458       !
4459       IF ( debug .AND. (COUNT(diagbox .EQ. ib) .GT. 0) ) THEN
4460          WRITE(numout,*) '===================== IB = :', ib
4461          WRITE(numout,*) "sub_pts(ib) :", sub_pts(ib), "sub_area(ib,:) :",sub_area(ib,1:2)
4462          WRITE(numout,*) 'LON LAT of GCM :', lalo(ib,2), lalo(ib,1)
4463          WRITE(numout,*) 'Neighbor options :',  neighbours(ib,1:NbNeighb)
4464          WRITE(numout,*) 'Resolution :', resolution(ib,1:2)
4465          WRITE(fmt,"('(',I3,'I6)')") nbi
4466          WRITE(numout,*) '-------------> trip ', trip_bx(1,1)
4467          DO jp=1,nbj
4468             WRITE(numout,fmt) trip_bx(1:nbi,jp)
4469          ENDDO
4470          WRITE(numout,*) '-------------> basin ',basin_bx(1,1)
4471          DO jp=1,nbj
4472             WRITE(numout,fmt) basin_bx(1:nbi,jp)
4473          ENDDO
4474          WRITE(numout,*) '-------------> hierarchy ',hierarchy_bx(1,1)
4475          DO jp=1,nbj
4476             WRITE(numout,fmt) INT(hierarchy_bx(1:nbi,jp)/1000.)
4477          ENDDO
4478          WRITE(numout,*) '-------------> topoindex ',topoind_bx(1,1)
4479          DO jp=1,nbj
4480             WRITE(numout,fmt) INT(topoind_bx(1:nbi,jp)/1000.)
4481          ENDDO
4482          !
4483          WRITE(numout,*) '------------> The basins we retain'
4484          DO jp=1,nb_basin
4485             WRITE(numout,*) 'index, size, bxout, coast :', basin_inbxid(jp), basin_sz(jp),&
4486                  & basin_bxout(jp), coast_pts(jp)
4487          ENDDO
4488          !
4489       ENDIF
4490       !
4491       !! Puts the basins found for the current grid box in the context of the global map.
4492       !
4493       CALL routing_globalize(nbpt, ib, neighbours, area_bx, trip_bx, hierarchy_bx, topoind_bx, min_topoind,&
4494            & nb_basin, basin_inbxid, basin_sz, basin_pts, basin_bxout, coast_pts, nwbas, basin_count,&
4495            & basin_area, basin_hierarchy, basin_topoind, basin_id, basin_flowdir, outflow_grid,&
4496            & nbcoastal, coastal_basin) 
4497       !
4498       !
4499       IF ( debug .AND. (COUNT(diagbox .EQ. ib) .GT. 0) ) THEN
4500          WRITE(numout,*) 'GLOBAL information after routing_globalize for grid ', ib
4501          DO jp=1,basin_count(ib)
4502             WRITE(numout,*) 'Basin ID : ', basin_id(ib, jp)
4503             WRITE(numout,*) 'Basin flowdir :', basin_flowdir(ib, jp)
4504             WRITE(numout,*) 'Basin hierarchy :', basin_hierarchy(ib, jp)
4505             WRITE(numout,*) 'Basin topoindex :', basin_topoind(ib, jp)
4506             WRITE(numout,*) 'Basin outflow grid :', outflow_grid(ib,jp)
4507          ENDDO
4508       ENDIF
4509       !
4510    ENDDO
4511    !
4512    !! Makes the connections between the bains and ensures global coherence.
4513    !
4514    CALL routing_linkup(nbpt, contfrac, neighbours, nwbas, basin_count, basin_area, basin_id, basin_flowdir, &
4515         & basin_hierarchy, outflow_grid, outflow_basin, inflow_number, inflow_grid, inflow_basin, &
4516         & nbcoastal, coastal_basin, invented_basins)
4517    !
4518    !
4519    IF (printlev>=1) WRITE(numout,*) 'The maximum number of basins in any grid :', MAXVAL(basin_count)
4520    !
4521    IF ( debug ) THEN
4522       DO ib=1,SIZE(diagbox)
4523          IF ( diagbox(ib) .GT. 0 ) THEN
4524             WRITE(numout,*) 'After routing_linkup information for grid ', diagbox(ib)
4525             DO jp=1,basin_count(diagbox(ib))
4526                WRITE(numout,*) 'Basin ID : ', basin_id(diagbox(ib), jp)
4527                WRITE(numout,*) 'Basin outflow_grid :', outflow_grid(diagbox(ib), jp)
4528                WRITE(numout,*) 'Basin outflow_basin:', outflow_basin(diagbox(ib), jp)
4529                WRITE(numout,*) 'Basin hierarchy :', basin_hierarchy(diagbox(ib), jp)
4530             ENDDO
4531          ENDIF
4532       ENDDO
4533    ENDIF
4534    !
4535    !! Computes the fetch of each basin, upstream area in known.
4536    !
4537    CALL routing_fetch(nbpt, resolution, contfrac, nwbas, basin_count, basin_area, basin_id, outflow_grid, &
4538         & outflow_basin, fetch_basin)
4539    !
4540    !
4541    IF (printlev >=3) WRITE(numout,*) "Start reducing the number of basins per grid to meet the required truncation."
4542    !
4543    !! Reduces the number of basins per grid to the value chosen by the user.
4544    !
4545    CALL routing_truncate(nbpt, resolution, contfrac, nwbas, basin_count, basin_area, basin_topoind,&
4546         & fetch_basin, basin_id, basin_flowdir, outflow_grid, outflow_basin, inflow_number,&
4547         & inflow_grid, inflow_basin)
4548    !
4549    DEALLOCATE (lat_rel)
4550    DEALLOCATE (lon_rel)
4551    !
4552    DEALLOCATE (trip)
4553    DEALLOCATE (basins)
4554    DEALLOCATE (topoindex)
4555    DEALLOCATE (hierarchy)
4556    !
4557    DEALLOCATE (sub_area)
4558    DEALLOCATE (sub_index)
4559    DEALLOCATE (sub_pts)
4560    !
4561    DEALLOCATE (mask)
4562    DEALLOCATE (resol_lu)
4563    !
4564    DEALLOCATE (basin_count)
4565    DEALLOCATE (basin_area, basin_hierarchy, basin_topoind, fetch_basin)
4566    DEALLOCATE (basin_id,  basin_flowdir)
4567    DEALLOCATE (outflow_grid,outflow_basin)
4568    DEALLOCATE (inflow_number)
4569    DEALLOCATE (inflow_basin, inflow_grid)
4570    DEALLOCATE (nbcoastal, coastal_basin)
4571
4572  END SUBROUTINE routing_basins
4573
4574
4575!! ================================================================================================================================
4576!! SUBROUTINE   : routing_getgrid
4577!!
4578!>\BRIEF         This subroutine extracts from the global high resolution fields
4579!!               the data for the current grid box we are dealing with.
4580!!
4581!! DESCRIPTION (definitions, functional, design, flags) :
4582!! Convention for trip on the input :
4583!! The trip field follows the following convention for the flow of the water :
4584!! trip = 1 : flow = N
4585!! trip = 2 : flow = NE
4586!! trip = 3 : flow = E
4587!! trip = 4 : flow = SE
4588!! trip = 5 : flow = S
4589!! trip = 6 : flow = SW
4590!! trip = 7 : flow = W
4591!! trip = 8 : flow = NW
4592!! trip = 97 : return flow into the ground
4593!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here
4594!! trip = 99 : river flow into the oceans
4595!!
4596!! On output, the grid boxes of the basin map which flow out of the GCM grid are identified
4597!! by numbers larger than 100 :
4598!! trip = 101 : flow = N out of the coarse grid
4599!! trip = 102 : flow = NE out of the coarse grid
4600!! trip = 103 : flow = E out of the coarse grid
4601!! trip = 104 : flow = SE out of the coarse grid
4602!! trip = 105 : flow = S out of the coarse grid
4603!! trip = 106 : flow = SW out of the coarse grid
4604!! trip = 107 : flow = W out of the coarse grid
4605!! trip = 108 : flow = NW out of the coarse grid
4606!! Inside the grid the convention remains the same as above (ie between 1 and 99).:\n
4607!!
4608!! RECENT CHANGE(S): None
4609!!
4610!! MAIN OUTPUT VARIABLE(S):
4611!!
4612!! REFERENCES   : None
4613!!
4614!! FLOWCHART    : None
4615!! \n
4616!_ ================================================================================================================================
4617
4618  SUBROUTINE routing_getgrid(nbpt, iml, jml, ib, sub_pts, sub_index, sub_area, max_basins, min_topoind, &
4619       & lon_rel, lat_rel, lalo, resolution, contfrac, trip, basins, topoindex, hierarchy, &
4620       & nbi, nbj, area_bx, trip_bx, basin_bx, topoind_bx, hierarchy_bx, lon_bx, lat_bx)
4621    !
4622    IMPLICIT NONE
4623    !
4624!!  INPUT VARIABLES
4625    INTEGER(i_std), INTENT(in)  :: nbpt                        !! Domain size (unitless)
4626    INTEGER(i_std), INTENT(in)  :: iml                         !! X resolution of the high resolution grid
4627    INTEGER(i_std), INTENT(in)  :: jml                         !! Y resolution of the high resolution grid
4628    INTEGER(i_std), INTENT(in)  :: ib                          !! Current basin (unitless)
4629    INTEGER(i_std), INTENT(in)  :: sub_pts(nbpt)               !! Number of high resolution points on this grid (unitless)
4630    INTEGER(i_std), INTENT(in)  :: sub_index(nbpt,nbvmax,2)    !! Indices of the points we need on the fine grid (unitless)
4631    REAL(r_std), INTENT(inout)  :: max_basins                  !! The current maximum of basins
4632    REAL(r_std), INTENT(in)     :: min_topoind                 !! The current minimum of topographic index (m)
4633    REAL(r_std), INTENT(in)     :: sub_area(nbpt,nbvmax)       !! Area on the fine grid (m^2)
4634    REAL(r_std), INTENT(in)     :: lon_rel(iml,jml)            !!
4635    REAL(r_std), INTENT(in)     :: lat_rel(iml,jml)            !! coordinates of the fine grid
4636    REAL(r_std), INTENT(in)     :: lalo(nbpt,2)                !! Vector of latitude and longitudes (beware of the order !)
4637    REAL(r_std), INTENT(in)     :: resolution(nbpt,2)          !! The size of each grid box in X and Y (m)
4638    REAL(r_std), INTENT(in)     :: contfrac(nbpt)              !! Fraction of land in each grid box (unitless;0-1)
4639    REAL(r_std), INTENT(inout)  :: trip(iml,jml)               !! The trip field (unitless)
4640    REAL(r_std), INTENT(inout)  :: basins(iml,jml)             !! data on the fine grid
4641    REAL(r_std), INTENT(inout)  :: topoindex(iml,jml)          !! Topographic index of the residence time (m)
4642    REAL(r_std), INTENT(inout)  :: hierarchy(iml, jml)         !! data on the fine grid
4643    !
4644!!  OUTPUT VARIABLES
4645    INTEGER(i_std), INTENT(out) :: nbi, nbj                    !! Number of point in x and y within the grid (unitless)
4646    REAL(r_std), INTENT(out)    :: area_bx(nbvmax,nbvmax)      !! Area of each small box in the grid box (m^2)
4647    REAL(r_std), INTENT(out)    :: hierarchy_bx(nbvmax,nbvmax) !! Level in the basin of the point
4648    REAL(r_std), INTENT(out)    :: lon_bx(nbvmax,nbvmax)       !!
4649    REAL(r_std), INTENT(out)    :: lat_bx(nbvmax,nbvmax)       !!
4650    REAL(r_std), INTENT(out)    :: topoind_bx(nbvmax,nbvmax)   !! Topographic index of the residence time for each of the smaller boxes (m)
4651    INTEGER(i_std), INTENT(out) :: trip_bx(nbvmax,nbvmax)      !! The trip field for each of the smaller boxes (unitless)
4652    INTEGER(i_std), INTENT(out) :: basin_bx(nbvmax,nbvmax)     !!
4653    !
4654!! LOCAL VARIABLES
4655    INTEGER(i_std)              :: ip, jp, ll(1), iloc, jloc   !! Indices (unitless)
4656    REAL(r_std)                 :: lonstr(nbvmax*nbvmax)       !!
4657    REAL(r_std)                 :: latstr(nbvmax*nbvmax)       !!
4658
4659!_ ================================================================================================================================
4660
4661    !
4662    ! Set everything to undef to locate easily empty points
4663    !
4664    trip_bx(:,:) = undef_int
4665    basin_bx(:,:) = undef_int
4666    topoind_bx(:,:) = undef_sechiba
4667    area_bx(:,:) = undef_sechiba
4668    hierarchy_bx(:,:) = undef_sechiba
4669    !
4670    IF ( sub_pts(ib) > 0 ) THEN
4671       !
4672       DO ip=1,sub_pts(ib)
4673          lonstr(ip) = lon_rel(sub_index(ib, ip, 1), sub_index(ib, ip, 2))
4674          latstr(ip) = lat_rel(sub_index(ib, ip, 1), sub_index(ib, ip, 2))
4675       ENDDO
4676       !
4677       !  Get the size of the area and order the coordinates to go from North to South and West to East
4678       !
4679       CALL routing_sortcoord(sub_pts(ib), lonstr, 'WE', nbi)
4680       CALL routing_sortcoord(sub_pts(ib), latstr, 'NS', nbj)
4681       !
4682       ! Transfer the data in such a way that (1,1) is the North Western corner and
4683       ! (nbi, nbj) the South Eastern.
4684       !
4685       DO ip=1,sub_pts(ib)
4686          ll = MINLOC(ABS(lonstr(1:nbi) - lon_rel(sub_index(ib, ip, 1), sub_index(ib, ip, 2))))
4687          iloc = ll(1)
4688          ll = MINLOC(ABS(latstr(1:nbj) - lat_rel(sub_index(ib, ip, 1), sub_index(ib, ip, 2))))
4689          jloc = ll(1)
4690          trip_bx(iloc, jloc) = NINT(trip(sub_index(ib, ip, 1), sub_index(ib, ip, 2)))
4691          basin_bx(iloc, jloc) = NINT(basins(sub_index(ib, ip, 1), sub_index(ib, ip, 2)))
4692          area_bx(iloc, jloc) = sub_area(ib, ip)
4693          topoind_bx(iloc, jloc) = topoindex(sub_index(ib, ip, 1), sub_index(ib, ip, 2))
4694          hierarchy_bx(iloc, jloc) = hierarchy(sub_index(ib, ip, 1), sub_index(ib, ip, 2))
4695          lon_bx(iloc, jloc) = lon_rel(sub_index(ib, ip, 1), sub_index(ib, ip, 2))
4696          lat_bx(iloc, jloc) = lat_rel(sub_index(ib, ip, 1), sub_index(ib, ip, 2))
4697       ENDDO
4698    ELSE
4699       !
4700       ! This is the case where the model invented a continental point
4701       !
4702       nbi = 1
4703       nbj = 1
4704       iloc = 1
4705       jloc = 1
4706       trip_bx(iloc, jloc) = 98
4707       basin_bx(iloc, jloc) = NINT(max_basins + 1)
4708       max_basins = max_basins + 1
4709       area_bx(iloc, jloc) = resolution(ib,1)*resolution(ib,2)*contfrac(ib)
4710       topoind_bx(iloc, jloc) = min_topoind
4711       hierarchy_bx(iloc, jloc) =  min_topoind
4712       lon_bx(iloc, jloc) = lalo(ib,2)
4713       lat_bx(iloc, jloc) = lalo(ib,1)
4714       !
4715    ENDIF
4716    !
4717    ! Tag in trip all the outflow conditions. The table is thus :
4718    ! trip = 100+n : Outflow into another grid box
4719    ! trip = 99    : River outflow into the ocean
4720    ! trip = 98    : This will be coastal flow (not organized as a basin)
4721    ! trip = 97    : return flow into the soil (local)
4722    !
4723    DO jp=1,nbj
4724       IF ( trip_bx(1,jp) .EQ. 8 .OR. trip_bx(1,jp) .EQ. 7 .OR. trip_bx(1,jp) .EQ. 6) THEN
4725          trip_bx(1,jp) = trip_bx(1,jp) + 100
4726       ENDIF
4727       IF ( trip_bx(nbi,jp) .EQ. 2 .OR. trip_bx(nbi,jp) .EQ. 3 .OR. trip_bx(nbi,jp) .EQ. 4) THEN
4728          trip_bx(nbi,jp) = trip_bx(nbi,jp) + 100
4729       ENDIF
4730    ENDDO
4731    DO ip=1,nbi
4732       IF ( trip_bx(ip,1) .EQ. 8 .OR. trip_bx(ip,1) .EQ. 1 .OR. trip_bx(ip,1) .EQ. 2) THEN
4733          trip_bx(ip,1) = trip_bx(ip,1) + 100
4734       ENDIF
4735       IF ( trip_bx(ip,nbj) .EQ. 6 .OR. trip_bx(ip,nbj) .EQ. 5 .OR. trip_bx(ip,nbj) .EQ. 4) THEN
4736          trip_bx(ip,nbj) = trip_bx(ip,nbj) + 100
4737       ENDIF
4738    ENDDO
4739    !
4740    !
4741    !  We simplify the outflow. We only need the direction normal to the
4742    !     box boundary and the 4 corners.
4743    !
4744    ! Northern border
4745    IF ( trip_bx(1,1) .EQ. 102 ) trip_bx(1,1) = 101
4746    IF ( trip_bx(nbi,1) .EQ. 108 ) trip_bx(nbi,1) = 101
4747    DO ip=2,nbi-1
4748       IF ( trip_bx(ip,1) .EQ. 108 .OR. trip_bx(ip,1) .EQ. 102 ) trip_bx(ip,1) = 101
4749    ENDDO
4750    ! Southern border
4751    IF ( trip_bx(1,nbj) .EQ. 104 ) trip_bx(1,nbj) = 105
4752    IF ( trip_bx(nbi,nbj) .EQ. 106 ) trip_bx(nbi,nbj) = 105
4753    DO ip=2,nbi-1
4754       IF ( trip_bx(ip,nbj) .EQ. 104 .OR. trip_bx(ip,nbj) .EQ. 106 ) trip_bx(ip,nbj) = 105
4755    ENDDO
4756    ! Eastern border
4757    IF ( trip_bx(nbi,1) .EQ. 104) trip_bx(nbi,1) = 103
4758    IF ( trip_bx(nbi,nbj) .EQ. 102) trip_bx(nbi,nbj) = 103
4759    DO jp=2,nbj-1
4760       IF ( trip_bx(nbi,jp) .EQ. 104 .OR. trip_bx(nbi,jp) .EQ. 102 ) trip_bx(nbi,jp) = 103
4761    ENDDO
4762    ! Western border
4763    IF ( trip_bx(1,1) .EQ. 106) trip_bx(1,1) = 107
4764    IF ( trip_bx(1,nbj) .EQ. 108) trip_bx(1,nbj) = 107
4765    DO jp=2,nbj-1
4766       IF ( trip_bx(1,jp) .EQ. 106 .OR. trip_bx(1,jp) .EQ. 108 ) trip_bx(1,jp) = 107
4767    ENDDO       
4768    !
4769    !
4770  END SUBROUTINE routing_getgrid
4771!
4772!! ================================================================================================================================
4773!! SUBROUTINE   : routing_sortcoord
4774!!
4775!>\BRIEF         This subroutines orders the coordinates to go from North to South and West to East.
4776!!
4777!! DESCRIPTION (definitions, functional, design, flags) : None
4778!!
4779!! RECENT CHANGE(S): None
4780!!
4781!! MAIN OUTPUT VARIABLE(S):
4782!!
4783!! REFERENCES   : None
4784!!
4785!! FLOWCHART    : None
4786!! \n
4787!_ ================================================================================================================================
4788
4789  SUBROUTINE routing_sortcoord(nb_in, coords, direction, nb_out)
4790    !
4791    IMPLICIT NONE
4792    !
4793!! INPUT VARIABLES
4794    INTEGER(i_std), INTENT(in)   :: nb_in             !!
4795    REAL(r_std), INTENT(inout)   :: coords(nb_in)     !!
4796    !
4797!! OUTPUT VARIABLES
4798    INTEGER(i_std), INTENT(out)  :: nb_out            !!
4799    !
4800!! LOCAL VARIABLES
4801    CHARACTER(LEN=2)             :: direction         !!
4802    INTEGER(i_std)               :: ipos              !!
4803    REAL(r_std)                  :: coords_tmp(nb_in) !!
4804    INTEGER(i_std), DIMENSION(1) :: ll                !!
4805    INTEGER(i_std)               :: ind(nb_in)        !!
4806
4807!_ ================================================================================================================================
4808    !
4809    ipos = 1
4810    nb_out = nb_in
4811    !
4812    ! Compress the coordinates array
4813    !
4814    DO WHILE ( ipos < nb_in )
4815       IF ( coords(ipos+1) /= undef_sechiba) THEN
4816         IF ( COUNT(coords(ipos:nb_out) == coords(ipos)) > 1 ) THEN
4817            coords(ipos:nb_out-1) = coords(ipos+1:nb_out) 
4818            coords(nb_out:nb_in) = undef_sechiba
4819            nb_out = nb_out - 1
4820         ELSE
4821            ipos = ipos + 1
4822         ENDIF
4823      ELSE
4824         EXIT
4825      ENDIF
4826    ENDDO
4827    !
4828    ! Sort it now
4829    !
4830    ! First we get ready and adjust for the periodicity in longitude
4831    !
4832    coords_tmp(:) = undef_sechiba
4833    IF ( INDEX(direction, 'WE') == 1 .OR.  INDEX(direction, 'EW') == 1) THEN
4834       IF ( MAXVAL(ABS(coords(1:nb_out))) .GT. 160 ) THEN
4835          coords_tmp(1:nb_out) = MOD(coords(1:nb_out) + 360.0, 360.0)
4836       ELSE
4837          coords_tmp(1:nb_out) = coords(1:nb_out)
4838       ENDIF
4839    ELSE IF ( INDEX(direction, 'NS') == 1 .OR.  INDEX(direction, 'SN') == 1) THEN
4840       coords_tmp(1:nb_out) = coords(1:nb_out)
4841    ELSE
4842       WRITE(numout,*) 'The chosen direction (', direction,') is not recognized'
4843       CALL ipslerr_p(3,'routing_sortcoord','The chosen direction is not recognized','First section','')
4844    ENDIF
4845    !
4846    ! Get it sorted out now
4847    !
4848    ipos = 1
4849    !
4850    IF ( INDEX(direction, 'WE') == 1 .OR. INDEX(direction, 'SN') == 1) THEN
4851       DO WHILE (COUNT(ABS(coords_tmp(:)-undef_sechiba) > EPSILON(undef_sechiba)*10.) >= 1)
4852          ll = MINLOC(coords_tmp(:), coords_tmp /= undef_sechiba)
4853          ind(ipos) = ll(1) 
4854          coords_tmp(ll(1)) = undef_sechiba
4855          ipos = ipos + 1
4856       ENDDO
4857    ELSE IF ( INDEX(direction, 'EW') == 1 .OR. INDEX(direction, 'NS') == 1) THEN
4858       DO WHILE (COUNT(ABS(coords_tmp(:)-undef_sechiba) > EPSILON(undef_sechiba)*10.) >= 1)
4859          ll = MAXLOC(coords_tmp(:), coords_tmp /= undef_sechiba)
4860          ind(ipos) = ll(1) 
4861          coords_tmp(ll(1)) = undef_sechiba
4862          ipos = ipos + 1
4863       ENDDO
4864    ELSE
4865       WRITE(numout,*) 'The chosen direction (', direction,') is not recognized (second)'
4866       CALL ipslerr_p(3,'routing_sortcoord','The chosen direction is not recognized','Second section','')
4867    ENDIF
4868    !
4869    coords(1:nb_out) = coords(ind(1:nb_out))
4870    IF (nb_out < nb_in) THEN
4871       coords(nb_out+1:nb_in) = zero
4872    ENDIF
4873    !
4874  END SUBROUTINE routing_sortcoord
4875  !
4876
4877!! ================================================================================================================================
4878!! SUBROUTINE   : routing_findbasins
4879!!
4880!>\BRIEF         This subroutine finds the basins and does some clean up.
4881!!               The aim is to return the list off all points which are within the
4882!!               same basin of the grid box.
4883!!
4884!! DESCRIPTION (definitions, functional, design, flags) :
4885!!  We will also collect all points which directly flow into the ocean in one basin
4886!!  Make sure that we do not have a basin with two outflows and other exceptions.
4887!!  At this stage no effort is made to come down to the truncation of the model.
4888!!
4889!! Convention for trip    \n
4890!! -------------------    \n
4891!! Inside of the box :    \n
4892!! trip = 1 : flow = N    \n
4893!! trip = 2 : flow = NE    \n
4894!! trip = 3 : flow = E    \n
4895!! trip = 4 : flow = SE    \n
4896!! trip = 5 : flow = S    \n
4897!! trip = 6 : flow = SW    \n
4898!! trip = 7 : flow = W    \n
4899!! trip = 8 : flow = NW    \n
4900!! trip = 97 : return flow into the ground    \n
4901!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here    \n
4902!! trip = 99 : river flow into the oceans    \n
4903!!
4904!! Out flow from the grid :    \n
4905!! trip = 101 : flow = N out of the coarse grid    \n
4906!! trip = 102 : flow = NE out of the coarse grid    \n
4907!! trip = 103 : flow = E out of the coarse grid    \n
4908!! trip = 104 : flow = SE out of the coarse grid    \n
4909!! trip = 105 : flow = S out of the coarse grid    \n
4910!! trip = 106 : flow = SW out of the coarse grid    \n
4911!! trip = 107 : flow = W out of the coarse grid    \n
4912!! trip = 108 : flow = NW out of the coarse grid!    \n
4913!! RECENT CHANGE(S): None
4914!!
4915!! MAIN OUTPUT VARIABLE(S):
4916!!
4917!! REFERENCES   : None
4918!!
4919!! FLOWCHART    : None
4920!! \n
4921!_ ================================================================================================================================
4922
4923  SUBROUTINE routing_findbasins(nbi, nbj, trip, basin, hierarchy, topoind, nb_basin, basin_inbxid, basin_sz,&
4924       & basin_bxout, basin_pts, coast_pts)
4925    !
4926    IMPLICIT NONE
4927    !
4928!! INPUT VARIABLES
4929    INTEGER(i_std), INTENT(in)    :: nbi                          !! Number of point in x within the grid (unitless)
4930    INTEGER(i_std), INTENT(in)    :: nbj                          !! Number of point in y within the grid (unitless)
4931    REAL(r_std), INTENT(in)       :: hierarchy(:,:)               !!
4932    REAL(r_std), INTENT(in)       :: topoind(:,:)                 !! Topographic index of the residence time (m)
4933    !
4934    !  Modified
4935    INTEGER(i_std), INTENT(inout) :: trip(:,:)                    !! The trip field (unitless)
4936    INTEGER(i_std), INTENT(inout) :: basin(:,:)                   !!
4937    !
4938!! OUTPUT VARIABLES
4939    INTEGER(i_std), INTENT(out)   :: nb_basin                     !! Number of sub-basins (unitless)
4940    INTEGER(i_std), INTENT(out)   :: basin_inbxid(nbvmax)         !!
4941    INTEGER(i_std), INTENT(out)   :: basin_sz(nbvmax)             !!
4942    INTEGER(i_std), INTENT(out)   :: basin_bxout(nbvmax)          !!
4943    INTEGER(i_std), INTENT(out)   :: basin_pts(nbvmax, nbvmax, 2) !!
4944    INTEGER(i_std), INTENT(out)   :: coast_pts(nbvmax)            !! The coastal flow points (unitless)
4945    !
4946!! LOCAL VARIABLES
4947    INTEGER(i_std)                :: ibas, ilf, nbb, nb_in        !!
4948    INTEGER(i_std)                :: bname(nbvmax)                !!
4949    INTEGER(i_std)                :: sz(nbvmax)                   !!
4950    INTEGER(i_std)                :: pts(nbvmax,nbvmax,2)         !!
4951    INTEGER(i_std)                :: nbout(nbvmax)                !!
4952    INTEGER(i_std)                :: new_nb                       !!
4953    INTEGER(i_std)                :: new_bname(nbvmax)            !!
4954    INTEGER(i_std)                :: new_sz(nbvmax)               !!
4955    INTEGER(i_std)                :: new_pts(nbvmax,nbvmax,2)     !!
4956    INTEGER(i_std)                :: itrans                       !!
4957    INTEGER(i_std)                :: trans(nbvmax)                !!
4958    INTEGER(i_std)                :: outdir(nbvmax)               !!
4959    INTEGER(i_std)                :: tmpsz(nbvmax)                !!
4960    INTEGER(i_std)                :: ip, jp, jpp(1), ipb          !!
4961    INTEGER(i_std)                :: sortind(nbvmax)              !!
4962    CHARACTER(LEN=7)              :: fmt                          !!
4963
4964!_ ================================================================================================================================
4965    !
4966    nbb = 0
4967    ibas = -1
4968    bname(:) = undef_int
4969    sz(:) = 0
4970    nbout(:) = 0
4971    new_pts(:,:,:) = 0
4972    !
4973    ! 1.0 Find all basins within this grid box
4974    !     Sort the variables per basin so that we can more easily
4975    !     access data from the same basin (The variables are :
4976    !     bname, sz, pts, nbout)
4977    !
4978    DO ip=1,nbi
4979       DO jp=1,nbj
4980          IF ( basin(ip,jp) .LT. undef_int) THEN
4981             IF ( COUNT(basin(ip,jp) .EQ. bname(:)) .EQ. 0 ) THEN
4982                nbb = nbb + 1
4983                IF ( nbb .GT. nbvmax ) CALL ipslerr_p(3,'routing_findbasins','nbvmax too small','first section','')
4984                bname(nbb) = basin(ip,jp)
4985                sz(nbb) = 0
4986             ENDIF
4987             !
4988             DO ilf=1,nbb
4989                IF ( basin(ip,jp) .EQ. bname(ilf) ) THEN
4990                   ibas = ilf
4991                ENDIF
4992             ENDDO
4993             !
4994             sz(ibas) = sz(ibas) + 1
4995             IF ( sz(ibas) .GT. nbvmax ) CALL ipslerr_p(3,'routing_findbasins','nbvmax too small','second section','')
4996             pts(ibas, sz(ibas), 1) = ip
4997             pts(ibas, sz(ibas), 2) = jp
4998             ! We deal only with outflow and leave flow back into the grid box for later.
4999             IF ( trip(ip,jp) .GE. 97 ) THEN
5000                nbout(ibas) = nbout(ibas) + 1
5001             ENDIF
5002             !
5003          ENDIF
5004          !
5005       ENDDO
5006    ENDDO
5007    !
5008    ! 2.0 All basins which have size 1 and flow to the ocean are put together.
5009    !
5010    itrans = 0
5011    coast_pts(:) = undef_int
5012    ! Get all the points we can collect
5013    DO ip=1,nbb
5014       IF ( sz(ip) .EQ. 1 .AND. trip(pts(ip,1,1),pts(ip,1,2)) .EQ. 99) THEN
5015          itrans = itrans + 1
5016          trans(itrans) = ip
5017          trip(pts(ip,1,1),pts(ip,1,2)) = 98
5018       ENDIF
5019    ENDDO
5020    ! put everything in the first basin
5021    IF ( itrans .GT. 1) THEN
5022       ipb = trans(1)
5023       coast_pts(sz(ipb)) = bname(ipb)
5024       bname(ipb) = -1
5025       DO ip=2,itrans
5026          sz(ipb) = sz(ipb) + 1
5027          coast_pts(sz(ipb)) = bname(trans(ip))
5028          sz(trans(ip)) = 0
5029          pts(ipb, sz(ipb), 1) = pts(trans(ip), 1, 1) 
5030          pts(ipb, sz(ipb), 2) = pts(trans(ip), 1, 2) 
5031       ENDDO
5032    ENDIF
5033    !
5034    ! 3.0 Make sure that we have only one outflow point in each basin
5035    !
5036    ! nbb is the number of basins on this grid box.
5037    new_nb = 0
5038    DO ip=1,nbb
5039       ! We only do this for grid-points which have more than one outflow
5040       IF ( sz(ip) .GT. 1 .AND. nbout(ip) .GT. 1) THEN
5041          !
5042          ! Pick up all points needed and store them in trans
5043          !
5044          itrans = 0
5045          DO jp=1,sz(ip)
5046             IF ( trip(pts(ip,jp,1),pts(ip,jp,2)) .GE. 97) THEN
5047                itrans = itrans + 1
5048                trans(itrans) = trip(pts(ip,jp,1),pts(ip,jp,2))
5049             ENDIF
5050          ENDDO
5051          !
5052          ! First issue : We have more than one point of the basin which flows into
5053          ! the ocean. In this case we put everything into coastal flow. It will go into
5054          ! a separate basin in the routing_globalize routine.
5055          !
5056          IF ( (COUNT(trans(1:itrans) .EQ. 99) + COUNT(trans(1:itrans) .EQ. 98)) .GT. 1) THEN
5057             DO jp=1,sz(ip)
5058                IF ( trip(pts(ip,jp,1),pts(ip,jp,2)) .EQ. 99 ) THEN
5059                   trip(pts(ip,jp,1),pts(ip,jp,2)) = 98
5060                   trans(itrans) = trip(pts(ip,jp,1),pts(ip,jp,2))
5061                ENDIF
5062             ENDDO
5063          ENDIF
5064          !
5065          ! Second issue : We have redundant outflows at the boundaries. That is two small grid
5066          ! boxes flowing into the same GCM grid box.
5067          !
5068          IF ( COUNT(trans(1:itrans) .GT. 100) .GE. 1) THEN
5069             CALL routing_simplify(nbi, nbj, trip, basin, hierarchy, bname(ip))
5070             itrans = 0
5071             DO jp=1,sz(ip)
5072                IF ( trip(pts(ip,jp,1),pts(ip,jp,2)) .GE. 9) THEN
5073                   itrans = itrans + 1
5074                   trans(itrans) = trip(pts(ip,jp,1),pts(ip,jp,2))
5075                ENDIF
5076             ENDDO
5077          ENDIF
5078          !
5079          ! Third issue : we have more than one outflow from the boxes. This could be
5080          !             - flow into 2 or more neighboring GCM grids
5081          !             - flow into a neighboring GCM grids and into the ocean or be a return flow (=97. =98, =99)
5082          !             - flow into a neighboring GCM grids or ocean and back into the same GCM grid box
5083          ! The only solution is to cut the basin up in as many parts.
5084          !
5085          IF ( COUNT(trans(1:itrans) .GE. 97) .GT. 1) THEN
5086             !
5087             nb_in =  new_nb
5088             CALL routing_cutbasin(nbi, nbj, nbb, trip, basin, bname(ip), new_nb, new_bname, new_sz, new_pts)
5089             !
5090             ! If we have split the basin then we need to cancel the old one
5091             !
5092             IF ( nb_in .NE. new_nb) THEN
5093                sz(ip) = 0
5094             ENDIF
5095             !
5096          ENDIF
5097          !
5098       ENDIF
5099    ENDDO
5100    !
5101    !  Add the new basins to the end of the list
5102    !
5103    If ( nbb+new_nb .LE. nbvmax) THEN
5104       DO ip=1,new_nb
5105          bname(nbb+ip) = new_bname(ip)
5106          sz(nbb+ip) = new_sz(ip)
5107          pts(nbb+ip,:,:) = new_pts(ip,:,:)
5108       ENDDO
5109       nbb = nbb+new_nb
5110    ELSE
5111       WRITE(numout,*) 'Increase nbvmax. It is too small to contain all the basins (routing_findbasins)'
5112       CALL ipslerr_p(3,'routing_findbasins','Increase nbvmax.','It is too small to contain all the basins','')
5113    ENDIF
5114    !
5115    ! Keep the output direction
5116    !
5117    DO ip=1,nbb
5118       IF ( sz(ip) .GT. 0 ) THEN
5119          trans(:) = 0
5120          DO jp=1,sz(ip)
5121             trans(jp) = trip(pts(ip,jp,1),pts(ip,jp,2))
5122          ENDDO
5123          outdir(ip) = MAXVAL(trans(1:sz(ip)))
5124          IF ( outdir(ip) .GE. 97 ) THEN
5125             outdir(ip) = outdir(ip) - 100
5126          ELSE
5127             WRITE(numout,*) 'Why are we here and can not find a trip larger than 96'
5128             WRITE(numout,*) 'Does this mean that the basin does not have any outflow ', ip, bname(ip)
5129             WRITE(fmt,"('(',I3,'I9)')") nbi
5130             WRITE(numout,*) '-----------------------> trip'
5131             DO jp=1,nbj
5132                WRITE(numout,fmt) trip(1:nbi,jp)
5133             ENDDO
5134             WRITE(numout,*) '-----------------------> basin'
5135             DO jp=1,nbj
5136                WRITE(numout,fmt) basin(1:nbi,jp)
5137             ENDDO
5138             CALL ipslerr_p(3,'routing_findbasins','Probleme finding trip','','')
5139          ENDIF
5140       ENDIF
5141    ENDDO
5142    !
5143    !
5144    ! Sort the output by size of the various basins.
5145    !
5146    nb_basin = COUNT(sz(1:nbb) .GT. 0)
5147    tmpsz(:) = -1
5148    tmpsz(1:nbb) = sz(1:nbb)
5149    DO ip=1,nbb
5150       jpp = MAXLOC(tmpsz(:))
5151       IF ( sz(jpp(1)) .GT. 0) THEN
5152          sortind(ip) = jpp(1)
5153          tmpsz(jpp(1)) = -1
5154       ENDIF
5155    ENDDO
5156    basin_inbxid(1:nb_basin) = bname(sortind(1:nb_basin))
5157    basin_sz(1:nb_basin) = sz(sortind(1:nb_basin))
5158    basin_pts(1:nb_basin,:,:) = pts(sortind(1:nb_basin),:,:)
5159    basin_bxout(1:nb_basin) = outdir(sortind(1:nb_basin))
5160    !
5161    ! We can only check if we have at least as many outflows as basins
5162    !
5163    ip = COUNT(trip(1:nbi,1:nbj) .GE. 97 .AND. trip(1:nbi,1:nbj) .LT. undef_int)
5164!!    ip = ip + COUNT(trip(1:nbi,1:nbj) .EQ. 97)
5165!!    IF ( COUNT(trip(1:nbi,1:nbj) .EQ. 98) .GT. 0) ip = ip + 1
5166    IF ( ip .LT. nb_basin ) THEN
5167       WRITE(numout,*) 'We have less outflow points than basins :', ip
5168       WRITE(fmt,"('(',I3,'I9)')") nbi
5169       WRITE(numout,*) '-----------------------> trip'
5170       DO jp=1,nbj
5171          WRITE(numout,fmt) trip(1:nbi,jp)
5172       ENDDO
5173       WRITE(numout,*) '-----------------------> basin'
5174       DO jp=1,nbj
5175          WRITE(numout,fmt) basin(1:nbi,jp)
5176       ENDDO
5177       WRITE(numout,*) 'nb_basin :', nb_basin
5178       WRITE(numout,*) 'Basin sized :', basin_sz(1:nb_basin)
5179       CALL ipslerr_p(3,'routing_findbasins','Probleme less outflow points than basins','','')
5180    ENDIF
5181   
5182  END SUBROUTINE routing_findbasins
5183  !
5184!! ================================================================================================================================
5185!! SUBROUTINE   : routing_simplify
5186!!
5187!>\BRIEF         This subroutine symplifies the routing out of each basin by taking
5188!!               out redundancies at the borders of the GCM box.
5189!!               The aim is to have only one outflow point per basin and grid box.
5190!!               But here we will not change the direction of the outflow. 
5191!!
5192!! DESCRIPTION (definitions, functional, design, flags) : None
5193!!
5194!! RECENT CHANGE(S): None
5195!!
5196!! MAIN OUTPUT VARIABLE(S):
5197!!
5198!! REFERENCES   : None
5199!!
5200!! FLOWCHART    : None
5201!! \n
5202!_ ================================================================================================================================
5203
5204SUBROUTINE routing_simplify(nbi, nbj, trip, basin, hierarchy, basin_inbxid)
5205    !
5206    IMPLICIT NONE
5207    !
5208!! LOCAL VARIABLES
5209    INTEGER(i_std)                             :: nbi                        !! Number of point in x within the grid (unitless)
5210    INTEGER(i_std)                             :: nbj                        !! Number of point in y within the grid (unitless)
5211    INTEGER(i_std)                             :: trip(:,:)                  !! The trip field (unitless)
5212    INTEGER(i_std)                             :: basin(:,:)                 !!
5213    REAL(r_std)                                :: hierarchy(:,:)             !!
5214    INTEGER(i_std)                             :: basin_inbxid               !!
5215    !
5216    INTEGER(i_std)                             :: ip, jp, nbout, basin_sz, iborder !!
5217    INTEGER(i_std), DIMENSION(nbvmax,nbvmax)   :: trip_tmp                   !! Temporary trip field which only contains the values for the basin on which we currently work (1)
5218    INTEGER(i_std), DIMENSION(nbvmax,nbvmax,2) :: trip_flow                  !!
5219    INTEGER(i_std), DIMENSION(nbvmax,2)        :: outflow                    !!
5220    INTEGER(i_std), DIMENSION(nbvmax)          :: outsz                      !!
5221    CHARACTER(LEN=7)                           :: fmt                        !!
5222    !
5223    INTEGER(i_std), DIMENSION(8,2)             :: inc                        !!
5224    INTEGER(i_std)                             :: itodo, ill(1), icc, ismall, ibas, iip, jjp, ib, id !! Indices (unitless)
5225    INTEGER(i_std), DIMENSION(nbvmax)          :: todopt                     !!
5226!!$, todosz
5227    REAL(r_std), DIMENSION(nbvmax)             :: todohi                     !!
5228    LOGICAL                                    :: not_found, debug = .FALSE. !! (true/false)
5229
5230!_ ================================================================================================================================
5231    !
5232    !
5233    !  The routing code (i=1, j=2)
5234    !
5235    inc(1,1) = 0
5236    inc(1,2) = -1
5237    inc(2,1) = 1
5238    inc(2,2) = -1
5239    inc(3,1) = 1
5240    inc(3,2) = 0
5241    inc(4,1) = 1
5242    inc(4,2) = 1
5243    inc(5,1) = 0
5244    inc(5,2) = 1
5245    inc(6,1) = -1
5246    inc(6,2) = 1
5247    inc(7,1) = -1
5248    inc(7,2) = 0
5249    inc(8,1) = -1
5250    inc(8,2) = -1
5251    !
5252    !
5253    !  Symplify the outflow conditions first. We are only interested in the
5254    !  outflows which go to different GCM grid boxes.
5255    !
5256    IF ( debug ) THEN
5257       WRITE(numout,*) '+++++++++++++++++++ BEFORE ANYTHING ++++++++++++++++++++'
5258       WRITE(fmt,"('(',I3,'I6)')") nbi
5259       DO jp=1,nbj
5260          WRITE(numout,fmt) trip_tmp(1:nbi,jp)
5261       ENDDO
5262    ENDIF
5263    !
5264    !  transfer the trips into an array which only contains the basin we are interested in
5265    !
5266    trip_tmp(:,:) = -1
5267    basin_sz = 0
5268    DO ip=1,nbi
5269       DO jp=1,nbj
5270          IF ( basin(ip,jp) .EQ. basin_inbxid) THEN
5271             trip_tmp(ip,jp) = trip(ip,jp)
5272             basin_sz = basin_sz + 1
5273          ENDIF
5274       ENDDO
5275    ENDDO
5276    !
5277    ! Determine for each point where it flows to
5278    !
5279    CALL routing_findrout(nbi, nbj, trip_tmp, basin_sz, basin_inbxid, nbout, outflow, trip_flow, outsz)
5280    !
5281    !
5282    !
5283    !
5284    ! Over the width of a GCM grid box we can have many outflows but we are interested
5285    ! in only one for each basin. Thus we wish to collect them all to form only one outflow
5286    ! to the neighboring grid box.
5287    !
5288    DO iborder = 101,107,2
5289       !
5290       ! If we have more than one of these outflows then we need to merge the sub-basins
5291       !
5292       icc = COUNT(trip_tmp .EQ. iborder)-1
5293       DO WHILE ( icc .GT. 0)
5294          ! Pick out all the points we will have to do
5295          itodo = 0
5296          DO ip=1,nbout
5297             IF (trip_tmp(outflow(ip,1),outflow(ip,2)) .EQ. iborder) THEN
5298                itodo = itodo + 1
5299                todopt(itodo) = ip
5300!!$                todosz(itodo) = outsz(ip)
5301                ! We take the hierarchy of the outflow point as we will try to
5302                ! minimize if for the outflow of the entire basin.
5303                todohi(itodo) = hierarchy(outflow(ip,1),outflow(ip,2))
5304             ENDIF
5305          ENDDO
5306          !
5307          ! We change the direction of the smallest basin.
5308          !
5309          ill=MAXLOC(todohi(1:itodo))
5310          ismall = todopt(ill(1))
5311          !
5312          DO ip=1,nbi
5313             DO jp=1,nbj
5314                IF ( trip_flow(ip,jp,1) .EQ. outflow(ismall,1) .AND.&
5315                     & trip_flow(ip,jp,2) .EQ. outflow(ismall,2) ) THEN
5316                   ! Now that we have found a point of the smallest sub-basin we
5317                   ! look around for another sub-basin
5318                   ib = 1
5319                   not_found = .TRUE.
5320                   DO WHILE ( not_found .AND. ib .LE. itodo ) 
5321                      IF ( ib .NE. ill(1) ) THEN
5322                         ibas = todopt(ib)
5323                         DO id=1,8
5324                            iip = ip + inc(id,1)
5325                            jjp = jp + inc(id,2)
5326                            ! Can we look at this points or is there any need to ?
5327                            IF ( iip .GE. 1 .AND. iip .LE. nbi .AND. &
5328                                 & jjp .GE. 1 .AND. jjp .LE. nbj .AND. not_found) THEN
5329                               ! Is this point the one we look for ?
5330                               IF ( trip_flow(iip,jjp,1) .EQ. outflow(ibas,1) .AND. &
5331                                    & trip_flow(iip,jjp,2) .EQ. outflow(ibas,2)) THEN
5332                                  trip_flow(ip,jp,1) = outflow(ibas,1)
5333                                  trip_flow(ip,jp,2) = outflow(ibas,2)
5334                                  trip_tmp(ip,jp) = id
5335                                  ! This last line ensures that we do not come back to this point
5336                                  ! and that in the end the outer while will stop
5337                                  not_found = .FALSE.
5338                               ENDIF
5339                            ENDIF
5340                         ENDDO
5341                      ENDIF
5342                      ib = ib + 1
5343                   ENDDO
5344                ENDIF
5345             ENDDO
5346          ENDDO
5347          !
5348          icc = icc - 1
5349       ENDDO
5350       !
5351       !
5352    ENDDO
5353    !
5354    IF ( debug ) THEN
5355       WRITE(numout,*) '+++++++++++++++++++ AFTER +++++++++++++++++++++++++++++'
5356       WRITE(fmt,"('(',I3,'I6)')") nbi
5357       DO jp=1,nbj
5358          WRITE(numout,fmt) trip_tmp(1:nbi,jp)
5359       ENDDO
5360    ENDIF
5361    !
5362    !  Put trip_tmp back into trip
5363    !
5364    DO ip=1,nbi
5365       DO jp=1,nbj
5366          IF ( trip_tmp(ip,jp) .GT. 0) THEN
5367             trip(ip,jp) = trip_tmp(ip,jp)
5368          ENDIF
5369       ENDDO
5370    ENDDO
5371    !
5372  END SUBROUTINE routing_simplify
5373!
5374!! ================================================================================================================================
5375!! SUBROUTINE   : routing_cutbasin
5376!!
5377!>\BRIEF        This subroutine cuts the original basin which has more than one outflow
5378!!              into as many subbasins as outflow directions. 
5379!!
5380!! DESCRIPTION (definitions, functional, design, flags) : None
5381!!
5382!! RECENT CHANGE(S): None
5383!!
5384!! MAIN OUTPUT VARIABLE(S):
5385!!
5386!! REFERENCES   : None
5387!!
5388!! FLOWCHART    : None
5389!! \n
5390!_ ================================================================================================================================
5391
5392SUBROUTINE routing_cutbasin (nbi, nbj, nbbasins, trip, basin, basin_inbxid, nb, bname, sz, pts)
5393    !
5394    IMPLICIT NONE
5395    !
5396!! INPUT VARIABLES
5397    INTEGER(i_std), INTENT(in)                 :: nbi, nbj             !! Number of point in x and y within the grid (unitless)
5398    INTEGER(i_std), INTENT(in)                 :: nbbasins             !!
5399    INTEGER(i_std), INTENT(in)                 :: basin_inbxid         !!
5400    !
5401    !  Modified
5402    INTEGER(i_std), INTENT(inout)              :: trip(:,:)            !! The trip field (unitless)
5403    INTEGER(i_std), INTENT(inout)              :: basin(:,:)           !!
5404    !
5405!! OUTPUT VARIABLES
5406    INTEGER(i_std), INTENT(out)                :: nb                   !!
5407    INTEGER(i_std), INTENT(out)                :: bname(nbvmax)        !!
5408    INTEGER(i_std), INTENT(out)                :: sz(nbvmax)           !!
5409    INTEGER(i_std), INTENT(out)                :: pts(nbvmax,nbvmax,2) !!
5410    !
5411!! LOCAL VARIABLES
5412    INTEGER(i_std)                             :: ip, jp, iip, jjp, ib, ibb, id, nbout !! Indices (unitless)
5413    INTEGER(i_std)                             :: basin_sz             !!
5414    INTEGER(i_std)                             :: nb_in                !!
5415    INTEGER(i_std), DIMENSION(nbvmax,nbvmax)   :: trip_tmp             !! Temporary trip field which only contains the values for the basin on which we currently work (unitless)
5416    INTEGER(i_std), DIMENSION(nbvmax,nbvmax,2) :: trip_flow            !!
5417    INTEGER(i_std), DIMENSION(nbvmax,2)        :: outflow              !!
5418    INTEGER(i_std), DIMENSION(nbvmax)          :: outsz                !!
5419    CHARACTER(LEN=7)                           :: fmt                  !!
5420    LOGICAL                                    :: not_found            !! (true/false)
5421    LOGICAL                                    :: debug=.FALSE.        !! (true/false)
5422    !
5423    INTEGER(i_std), DIMENSION(8,2)             :: inc                  !!
5424
5425!_ ================================================================================================================================
5426    !
5427    !
5428    !  The routing code (i=1, j=2)
5429    !
5430    inc(1,1) = 0
5431    inc(1,2) = -1
5432    inc(2,1) = 1
5433    inc(2,2) = -1
5434    inc(3,1) = 1
5435    inc(3,2) = 0
5436    inc(4,1) = 1
5437    inc(4,2) = 1
5438    inc(5,1) = 0
5439    inc(5,2) = 1
5440    inc(6,1) = -1
5441    inc(6,2) = 1
5442    inc(7,1) = -1
5443    inc(7,2) = 0
5444    inc(8,1) = -1
5445    inc(8,2) = -1
5446    !
5447    ! Set up a temporary trip field which only contains the values
5448    ! for the basin on which we currently work.
5449    !
5450    trip_tmp(:,:) = -1
5451    basin_sz = 0
5452    DO ip=1,nbi
5453       DO jp=1,nbj
5454          IF ( basin(ip,jp) .EQ. basin_inbxid) THEN
5455             trip_tmp(ip,jp) = trip(ip,jp)
5456             basin_sz = basin_sz + 1
5457          ENDIF
5458       ENDDO
5459    ENDDO
5460    !
5461    CALL routing_findrout(nbi, nbj, trip_tmp, basin_sz, basin_inbxid, nbout, outflow, trip_flow, outsz)
5462    !
5463!    IF ( debug ) THEN
5464!       DO ib = nb_in+1,nb
5465!          DO ip=1,sz(ib)
5466!             trip_tmp(pts(ib, ip, 1),pts(ib, ip, 2)) = ib*(-1)-900
5467!          ENDDO
5468!       ENDDO
5469!       WRITE(fmt,"('(',I3,'I6)')") nbi
5470!       WRITE(numout,*)  'BEFORE ------------> New basins '
5471!       WRITE(numout,*) nb, ' sz :', sz(1:nb)
5472!       DO jp=1,nbj
5473!          WRITE(numout,fmt) trip_tmp(1:nbi,jp)
5474!       ENDDO
5475!    ENDIF
5476    !
5477    !  Take out the small sub-basins. That is those which have only one grid box
5478    !  This is only done if we need to save space in the number of basins. Else we
5479    !  can take it easy and keep diverging sub-basins for the moment.
5480    !
5481    IF ( nbbasins .GE. nbasmax ) THEN
5482       DO ib=1,nbout
5483          ! If the sub-basin is of size one and its larger neighbor is flowing into another
5484          ! direction then we put them together.
5485          IF ( outsz(ib) .EQ. 1 .AND. trip(outflow(ib,1), outflow(ib,2)) .GT. 99 ) THEN
5486             !
5487             not_found = .TRUE.
5488             DO id=1,8
5489                ip = outflow(ib,1)
5490                jp = outflow(ib,2)
5491                iip = ip + inc(id,1)
5492                jjp = jp + inc(id,2)
5493                ! Can we look at this points ?
5494                IF ( iip .GE. 1 .AND. iip .LE. nbi .AND. &
5495                     & jjp .GE. 1 .AND. jjp .LE. nbj .AND. not_found) THEN
5496                   ! Did we find a direct neighbor which is an outflow point ?
5497                   IF ( trip_tmp(iip,jjp) .GT. 100 ) THEN
5498                      ! IF so direct the flow towards it and update the tables.
5499                      not_found = .FALSE.
5500                      trip(ip,jp) = id
5501                      trip_tmp(ip,jp) = id
5502                      outsz(ib) = 0
5503                      ! update the table of this basin
5504                      DO ibb=1,nbout
5505                         IF ( iip .EQ. outflow(ibb,1) .AND. jjp .EQ. outflow(ibb,2) ) THEN
5506                            outsz(ibb) = outsz(ibb)+1 
5507                            trip_flow(ip,jp,1) = outflow(ibb,1)
5508                            trip_flow(ip,jp,2) = outflow(ibb,2)
5509                         ENDIF
5510                      ENDDO
5511                   ENDIF
5512                ENDIF
5513             ENDDO
5514          ENDIF
5515       ENDDO
5516    ENDIF
5517    !
5518    !
5519    !  Cut the basin if we have more than 1 left.
5520    !
5521    !
5522    IF ( COUNT(outsz(1:nbout) .GT. 0) .GT. 1 ) THEN
5523       !
5524       nb_in = nb
5525       !
5526       DO ib = 1,nbout
5527          IF ( outsz(ib) .GT. 0) THEN
5528             nb = nb+1
5529             IF ( nb .GT. nbvmax) THEN
5530                WRITE(numout,*) 'nbvmax too small, increase it (routing_cutbasin)'
5531             ENDIF
5532             bname(nb) = basin_inbxid
5533             sz(nb) = 0
5534             DO ip=1,nbi
5535                DO jp=1,nbj
5536                   IF ( (trip_flow(ip,jp,1) + trip_flow(ip,jp,1)) .GT. 0 .AND. &
5537                      & trip_flow(ip,jp,1) .EQ. outflow(ib,1) .AND. &
5538                      & trip_flow(ip,jp,2) .EQ. outflow(ib,2) ) THEN
5539                      sz(nb) = sz(nb) + 1
5540                      pts(nb, sz(nb), 1) = ip
5541                      pts(nb, sz(nb), 2) = jp
5542                   ENDIF
5543                ENDDO
5544             ENDDO
5545          ENDIF
5546       ENDDO
5547       ! A short verification
5548       IF ( SUM(sz(nb_in+1:nb)) .NE. basin_sz) THEN
5549          WRITE(numout,*) 'Lost some points while spliting the basin'
5550          WRITE(numout,*) 'nbout :', nbout
5551          DO ib = nb_in+1,nb
5552             WRITE(numout,*) 'ib, SZ :', ib, sz(ib)
5553          ENDDO
5554          WRITE(fmt,"('(',I3,'I6)')") nbi
5555          WRITE(numout,*)  '-------------> trip '
5556          DO jp=1,nbj
5557             WRITE(numout,fmt) trip_tmp(1:nbi,jp)
5558          ENDDO
5559          CALL ipslerr_p(3,'routing_cutbasin','Lost some points while spliting the basin','','')
5560       ENDIF
5561       
5562       IF ( debug ) THEN
5563          DO ib = nb_in+1,nb
5564             DO ip=1,sz(ib)
5565                trip_tmp(pts(ib, ip, 1),pts(ib, ip, 2)) = ib*(-1)-900
5566             ENDDO
5567          ENDDO
5568          WRITE(fmt,"('(',I3,'I6)')") nbi
5569          WRITE(numout,*)  'AFTER-------------> New basins '
5570          WRITE(numout,*) nb, ' sz :', sz(1:nb)
5571          DO jp=1,nbj
5572             WRITE(numout,fmt) trip_tmp(1:nbi,jp)
5573          ENDDO
5574          IF ( MAXVAl(trip_tmp(1:nbi,1:nbj)) .GT. 0) THEN
5575             CALL ipslerr_p(3,'routing_cutbasin','Error in debug checking','','')
5576          ENDIF
5577       ENDIF
5578    ENDIF
5579    !
5580  END SUBROUTINE routing_cutbasin
5581  !
5582!! ================================================================================================================================
5583!! SUBROUTINE   : routing_hierarchy
5584!!
5585!>\BRIEF        This subroutine finds, for each point, the distance to the outflow
5586!!               point along the flowlines of the basin.
5587!!
5588!! DESCRIPTION (definitions, functional, design, flags) : None
5589!!
5590!! RECENT CHANGE(S): None
5591!!
5592!! MAIN OUTPUT VARIABLE(S):
5593!!
5594!! REFERENCES   : None
5595!!
5596!! FLOWCHART    : None
5597!! \n
5598!_ ================================================================================================================================
5599
5600SUBROUTINE routing_hierarchy(iml, jml, trip, topoindex, hierarchy)
5601    !
5602    IMPLICIT NONE
5603    !
5604!! LOCAL VARIABLES
5605    INTEGER(i_std)                  :: iml          !! X resolution of the high resolution grid
5606    INTEGER(i_std)                  :: jml          !! Y resolution of the high resolution grid
5607    REAL(r_std), DIMENSION(iml,jml) :: trip         !! The trip field (unitless)
5608    REAL(r_std), DIMENSION(iml,jml) :: hierarchy    !!
5609    REAL(r_std), DIMENSION(iml,jml) :: topoindex    !! Topographic index of the residence time (m)
5610    !
5611    INTEGER(i_std), DIMENSION(8,2)  :: inc          !!
5612    INTEGER(i_std)                  :: ip, jp, ib, ntripi, ntripj, cnt, trp !!
5613    REAL(r_std)                     :: topohier     !! The new value of topographically weighted hierarchy (m)
5614    REAL(r_std)                     :: topohier_old !! The old value of topographically weighted hierarchy (m)
5615    CHARACTER(LEN=7)                :: fmt          !!
5616
5617!_ ================================================================================================================================
5618    !
5619    !  The routing code (i=1, j=2)
5620    !
5621    inc(1,1) = 0
5622    inc(1,2) = -1
5623    inc(2,1) = 1
5624    inc(2,2) = -1
5625    inc(3,1) = 1
5626    inc(3,2) = 0
5627    inc(4,1) = 1
5628    inc(4,2) = 1
5629    inc(5,1) = 0
5630    inc(5,2) = 1
5631    inc(6,1) = -1
5632    inc(6,2) = 1
5633    inc(7,1) = -1
5634    inc(7,2) = 0
5635    inc(8,1) = -1
5636    inc(8,2) = -1
5637    !
5638    DO ip=1,iml
5639       DO jp=1,jml
5640          IF ( trip(ip,jp) .LT. undef_sechiba ) THEN
5641             ntripi = ip
5642             ntripj = jp
5643             trp = NINT(trip(ip,jp))
5644             cnt = 1
5645             ! Warn for extreme numbers
5646             IF (  topoindex(ip,jp) .GT. 1.e10 ) THEN
5647                WRITE(numout,*) 'We have a very large topographic index for point ', ip, jp
5648                WRITE(numout,*) 'This can not be right :', topoindex(ip,jp)
5649                CALL ipslerr_p(3,'routing_hierarchy','Too large topographic index','','')
5650             ELSE
5651                topohier = topoindex(ip,jp)
5652             ENDIF
5653             !
5654             DO WHILE ( trp .GT. 0 .AND. trp .LT. 9 .AND. cnt .LT. iml*jml) 
5655                cnt = cnt + 1
5656                ntripi = ntripi + inc(trp,1)
5657                IF ( ntripi .LT. 1) ntripi = iml
5658                IF ( ntripi .GT. iml) ntripi = 1
5659                ntripj = ntripj + inc(trp,2)
5660                topohier_old = topohier
5661                topohier = topohier + topoindex(ntripi, ntripj)
5662                IF ( topohier_old .GT. topohier) THEN
5663                   WRITE(numout,*) 'Big Problem, how comes we climb up a hill ?'
5664                   WRITE(numout,*) 'The old value of topographicaly weighted hierarchy was : ', topohier_old
5665                   WRITE(numout,*) 'The new one is :', topohier
5666                   CALL ipslerr_p(3,'routing_hierarchy','Big Problem, how comes we climb up a hill ?','','')
5667                ENDIF
5668                trp = NINT(trip(ntripi, ntripj))
5669             ENDDO
5670             
5671             IF ( cnt .EQ. iml*jml) THEN
5672                WRITE(numout,*) 'We could not route point (routing_findrout) :', ip, jp
5673                WRITE(numout,*) '-------------> trip '
5674                WRITE(fmt,"('(',I3,'I6)')") iml
5675                DO ib=1,jml
5676                   WRITE(numout,fmt) trip(1:iml,ib)
5677                ENDDO
5678                CALL ipslerr_p(3,'routing_hierarchy','We could not route point','','')
5679             ENDIF
5680             
5681             hierarchy(ip,jp) = topohier
5682             
5683          ENDIF
5684       ENDDO
5685    ENDDO
5686    !
5687    !
5688  END SUBROUTINE routing_hierarchy
5689  !
5690!! ================================================================================================================================
5691!! SUBROUTINE   : routing_findrout
5692!!
5693!>\BRIEF        This subroutine simply computes the route to each outflow point
5694!!              and returns the outflow point for each point in the basin. 
5695!!
5696!! DESCRIPTION (definitions, functional, design, flags) : None
5697!!
5698!! RECENT CHANGE(S): None
5699!!
5700!! MAIN OUTPUT VARIABLE(S):
5701!!
5702!! REFERENCES   : None
5703!!
5704!! FLOWCHART    : None
5705!! \n
5706!_ ================================================================================================================================
5707
5708SUBROUTINE routing_findrout(nbi, nbj, trip, basin_sz, basinid, nbout, outflow, trip_flow, outsz)
5709    !
5710    IMPLICIT NONE
5711    !
5712!! INPUT VARIABLES
5713    INTEGER(i_std)                                          :: nbi       !! Number of point in x within the grid (unitless)
5714    INTEGER(i_std)                                          :: nbj       !! Number of point in y within the grid (unitless)
5715    INTEGER(i_std), DIMENSION(nbvmax,nbvmax)                :: trip      !! The trip field (unitless)
5716    INTEGER(i_std)                                          :: basin_sz  !!
5717    INTEGER(i_std)                                          :: basinid   !!
5718    !
5719!! OUTPUT VARIABLES
5720    INTEGER(i_std), DIMENSION(nbvmax,2), INTENT(out)        :: outflow   !!
5721    INTEGER(i_std), DIMENSION(nbvmax,nbvmax,2), INTENT(out) :: trip_flow !!
5722    INTEGER(i_std), INTENT(out)                             :: nbout     !!
5723    INTEGER(i_std), DIMENSION(nbvmax), INTENT(out)          :: outsz     !!
5724    !
5725!! LOCAL VARIABLES
5726    INTEGER(i_std), DIMENSION(8,2)                          :: inc       !!
5727    INTEGER(i_std)                                          :: ip, jp, ib, cnt, trp, totsz !! Indices (unitless)
5728    CHARACTER(LEN=7)                                        :: fmt       !!
5729
5730!_ ================================================================================================================================
5731    !
5732    !
5733    !  The routing code (i=1, j=2)
5734    !
5735    inc(1,1) = 0
5736    inc(1,2) = -1
5737    inc(2,1) = 1
5738    inc(2,2) = -1
5739    inc(3,1) = 1
5740    inc(3,2) = 0
5741    inc(4,1) = 1
5742    inc(4,2) = 1
5743    inc(5,1) = 0
5744    inc(5,2) = 1
5745    inc(6,1) = -1
5746    inc(6,2) = 1
5747    inc(7,1) = -1
5748    inc(7,2) = 0
5749    inc(8,1) = -1
5750    inc(8,2) = -1
5751    !
5752    !
5753    !  Get the outflows and determine for each point to which outflow point it belong
5754    !
5755    nbout = 0
5756    trip_flow(:,:,:) = 0
5757    DO ip=1,nbi
5758       DO jp=1,nbj
5759          IF ( trip(ip,jp) .GT. 9) THEN
5760             nbout = nbout + 1
5761             outflow(nbout,1) = ip
5762             outflow(nbout,2) = jp
5763          ENDIF
5764          IF ( trip(ip,jp) .GT. 0) THEN
5765             trip_flow(ip,jp,1) = ip
5766             trip_flow(ip,jp,2) = jp
5767          ENDIF
5768       ENDDO
5769    ENDDO
5770    !
5771    ! Follow the flow of the water
5772    !
5773    DO ip=1,nbi
5774       DO jp=1,nbj
5775          IF ( (trip_flow(ip,jp,1) + trip_flow(ip,jp,2)) .GT. 0) THEN
5776             trp = trip(trip_flow(ip,jp,1), trip_flow(ip,jp,2))
5777             cnt = 0
5778             DO WHILE ( trp .GT. 0 .AND. trp .LT. 9 .AND. cnt .LT. nbi*nbj) 
5779                cnt = cnt + 1
5780                trip_flow(ip,jp,1) = trip_flow(ip,jp,1) + inc(trp,1)
5781                trip_flow(ip,jp,2) = trip_flow(ip,jp,2) + inc(trp,2)
5782                trp = trip(trip_flow(ip,jp,1), trip_flow(ip,jp,2))
5783             ENDDO
5784             IF ( cnt .EQ. nbi*nbj) THEN
5785                WRITE(numout,*) 'We could not route point (routing_findrout) :', ip, jp
5786                WRITE(numout,*) '-------------> trip '
5787                WRITE(fmt,"('(',I3,'I6)')") nbi
5788                DO ib=1,nbj
5789                   WRITE(numout,fmt) trip(1:nbi,ib)
5790                ENDDO
5791                CALL ipslerr_p(3,'routing_findrout','We could not route point','','')
5792             ENDIF
5793          ENDIF
5794       ENDDO
5795    ENDDO
5796    !
5797    !  What is the size of the region behind each outflow point ?
5798    !
5799    totsz = 0
5800    DO ip=1,nbout
5801       outsz(ip) = COUNT(trip_flow(:,:,1) .EQ. outflow(ip,1) .AND. trip_flow(:,:,2) .EQ. outflow(ip,2))
5802       totsz = totsz + outsz(ip)
5803    ENDDO
5804    IF ( basin_sz .NE. totsz) THEN
5805       WRITE(numout,*) 'Water got lost while I tried to follow it '
5806       WRITE(numout,*) basin_sz, totsz
5807       WRITE(numout,*) 'Basin id :', basinid
5808       DO ip=1,nbout
5809          WRITE(numout,*) 'ip :', ip, ' outsz :', outsz(ip), ' outflow :', outflow(ip,1), outflow(ip,2)
5810       ENDDO
5811       WRITE(numout,*) '-------------> trip '
5812       WRITE(fmt,"('(',I3,'I6)')") nbi
5813       DO jp=1,nbj
5814          WRITE(numout,fmt) trip(1:nbi,jp)
5815       ENDDO
5816       CALL ipslerr_p(3,'routing_findrout','Water got lost while I tried to follow it','','')
5817    ENDIF
5818    !
5819  END SUBROUTINE routing_findrout
5820  !
5821!! ================================================================================================================================
5822!! SUBROUTINE   : routing_globalize
5823!!
5824!>\BRIEF        This subroutine puts the basins found for grid box in the global map.
5825!!               Connection can only be made later when all information is together.
5826!!
5827!! DESCRIPTION (definitions, functional, design, flags) : None
5828!!
5829!! RECENT CHANGE(S): None
5830!!
5831!! MAIN OUTPUT VARIABLE(S):
5832!! One of the outputs is basin_flowdir. Its convention is 1-8 for the directions from North to North
5833!! West going through South. The negative values will be -3 for return flow, -2 for coastal flow
5834!!
5835!! REFERENCES   : None
5836!!
5837!! FLOWCHART    : None
5838!! \n
5839!_ ================================================================================================================================
5840
5841SUBROUTINE routing_globalize(nbpt, ib, neighbours, area_bx, trip_bx, hierarchy_bx, topoind_bx, min_topoind,&
5842       & nb_basin, basin_inbxid, basin_sz, basin_pts, basin_bxout, coast_pts, nwbas, basin_count,&
5843       & basin_area, basin_hierarchy, basin_topoind, basin_id, basin_flowdir, outflow_grid,&
5844       & nbcoastal, coastal_basin)
5845    !
5846    IMPLICIT NONE
5847    !
5848!! INPUT VARIABLES
5849    INTEGER(i_std), INTENT (in)                :: nbpt                   !! Domain size (unitless)
5850    INTEGER(i_std), INTENT (in)                :: ib                     !! Current basin (unitless)
5851    INTEGER(i_std), INTENT(in)                 :: neighbours(nbpt,NbNeighb)!! Vector of neighbours for each grid point
5852                                                                         !! (1=North and then clockwise)
5853!! LOCAL VARIABLES
5854    REAL(r_std), DIMENSION(nbvmax,nbvmax)      :: area_bx                !! Area of each small box in the grid box (m^2)
5855    INTEGER(i_std), DIMENSION(nbvmax,nbvmax)   :: trip_bx                !! The trip field for each of the smaller boxes (unitless)
5856    REAL(r_std), DIMENSION(nbvmax,nbvmax)      :: hierarchy_bx           !! Level in the basin of the point
5857    REAL(r_std), DIMENSION(nbvmax,nbvmax)      :: topoind_bx             !! Topographic index of the residence time for each of the smaller boxes (m)
5858    REAL(r_std)                                :: min_topoind            !! The current minimum of topographic index (m)
5859    INTEGER(i_std)                             :: nb_basin               !! Number of sub-basins (unitless)
5860    INTEGER(i_std), DIMENSION(nbvmax)          :: basin_inbxid, basin_sz !! ID of basin, number of points in the basin
5861    INTEGER(i_std), DIMENSION(nbvmax,nbvmax,2) :: basin_pts              !! Points in each basin
5862    INTEGER(i_std), DIMENSION(nbvmax)          :: basin_bxout            !! outflow direction
5863    INTEGER(i_std)                             :: coast_pts(nbvmax)      !! The coastal flow points (unitless)
5864    ! global maps
5865    INTEGER(i_std)                             :: nwbas                  !!
5866    INTEGER(i_std), DIMENSION(nbpt)            :: basin_count            !!
5867    INTEGER(i_std), DIMENSION(nbpt,nwbas)      :: basin_id               !!
5868    INTEGER(i_std), DIMENSION(nbpt,nwbas)      :: basin_flowdir          !! Water flow directions in the basin (unitless)
5869    REAL(r_std), DIMENSION(nbpt,nwbas)         :: basin_area             !!
5870    REAL(r_std), DIMENSION(nbpt,nwbas)         :: basin_hierarchy        !!
5871    REAL(r_std), DIMENSION(nbpt,nwbas)         :: basin_topoind          !! Topographic index of the residence time for a basin (m)
5872    INTEGER(i_std), DIMENSION(nbpt,nwbas)      :: outflow_grid           !! Type of outflow on the grid box (unitless)
5873    INTEGER(i_std), DIMENSION(nbpt)            :: nbcoastal              !!
5874    INTEGER(i_std), DIMENSION(nbpt,nwbas)      :: coastal_basin          !!
5875    !
5876    INTEGER(i_std)                             :: ij, iz                 !! Indices (unitless)
5877    CHARACTER(LEN=4)                           :: hierar_method = 'OUTP' !!
5878
5879!_ ================================================================================================================================
5880    !
5881    !
5882    DO ij=1, nb_basin
5883       !
5884       ! Count the basins and keep their ID
5885       !
5886       basin_count(ib) = basin_count(ib)+1
5887       if (basin_count(ib) > nwbas) then
5888          WRITE(numout,*) 'ib=',ib
5889          call ipslerr_p(3,'routing_globalize', &
5890               &      'Problem with basin_count : ', & 
5891               &      'It is greater than number of allocated basin nwbas.', &
5892               &      '(stop to count basins)')
5893       endif
5894       basin_id(ib,basin_count(ib)) = basin_inbxid(ij)
5895       !
5896       ! Transfer the list of basins which flow into the ocean as coastal flow.
5897       !
5898       IF ( basin_id(ib,basin_count(ib)) .LT. 0) THEN
5899          nbcoastal(ib) = basin_sz(ij)
5900          coastal_basin(ib,1:nbcoastal(ib)) = coast_pts(1:nbcoastal(ib))
5901       ENDIF
5902       !
5903       !
5904       ! Compute the area of the basin
5905       !
5906       basin_area(ib,ij) = zero
5907       basin_hierarchy(ib,ij) = zero
5908       !
5909       SELECT CASE (hierar_method)
5910          !
5911          CASE("MINI")
5912             basin_hierarchy(ib,ij) = undef_sechiba
5913          !
5914       END SELECT
5915       basin_topoind(ib,ij) = zero
5916       !
5917       DO iz=1,basin_sz(ij)
5918          !
5919          basin_area(ib,ij) = basin_area(ib,ij) + area_bx(basin_pts(ij,iz,1),basin_pts(ij,iz,2))
5920          basin_topoind(ib,ij) = basin_topoind(ib,ij) + topoind_bx(basin_pts(ij,iz,1),basin_pts(ij,iz,2))
5921          !
5922          ! There are a number of ways to determine the hierarchy of the entire basin.
5923          ! We allow for three here :
5924          !     - Take the mean value
5925          !     - Take the minimum value within the basin
5926          !     - Take the value at the outflow point
5927          ! Probably taking the value of the outflow point is the best solution.
5928          !
5929          SELECT CASE (hierar_method)
5930             !
5931             CASE("MEAN")
5932                ! Mean hierarchy of the basin
5933                basin_hierarchy(ib,ij) = basin_hierarchy(ib,ij) + &
5934                     & hierarchy_bx(basin_pts(ij,iz,1),basin_pts(ij,iz,2))
5935             CASE("MINI")
5936                ! The smallest value of the basin
5937                IF ( hierarchy_bx(basin_pts(ij,iz,1),basin_pts(ij,iz,2)) .LT. basin_hierarchy(ib,ij)) THEN
5938                   basin_hierarchy(ib,ij) = hierarchy_bx(basin_pts(ij,iz,1),basin_pts(ij,iz,2))
5939                ENDIF
5940             CASE("OUTP")
5941                ! Value at the outflow point
5942                IF ( trip_bx(basin_pts(ij,iz,1),basin_pts(ij,iz,2)) .GT. 100 ) THEN
5943                   basin_hierarchy(ib,ij) = hierarchy_bx(basin_pts(ij,iz,1),basin_pts(ij,iz,2))
5944                ENDIF
5945             CASE DEFAULT
5946                WRITE(numout,*) 'Unknown method for computing the hierarchy of the basin'
5947                CALL ipslerr_p(3,'routing_globalize','Unknown method for computing the hierarchy of the basin','','')
5948          END SELECT
5949          !
5950       ENDDO
5951       !
5952       basin_topoind(ib,ij) = basin_topoind(ib,ij)/REAL(basin_sz(ij),r_std)
5953       !
5954       SELECT CASE (hierar_method)
5955          !
5956          CASE("MEAN")
5957             basin_hierarchy(ib,ij) = basin_hierarchy(ib,ij)/REAL(basin_sz(ij),r_std)
5958          !
5959       END SELECT
5960       !
5961       ! To make sure that it has the lowest number if this is an outflow point we reset  basin_hierarchy
5962       !
5963       IF (basin_bxout(ij) .LT. 0) THEN
5964          basin_hierarchy(ib,ij) = min_topoind
5965          basin_topoind(ib,ij) = min_topoind
5966       ENDIF
5967       !
5968       !
5969       ! Keep the outflow boxes and basin
5970       !
5971       basin_flowdir(ib,ij) = basin_bxout(ij)
5972       IF (basin_bxout(ij) .GT. 0) THEN
5973          outflow_grid(ib,ij) = neighbours(ib,basin_bxout(ij))
5974       ELSE
5975          outflow_grid(ib,ij) = basin_bxout(ij)
5976       ENDIF
5977       !
5978       !
5979    ENDDO
5980    !
5981
5982    !
5983  END SUBROUTINE routing_globalize
5984  !
5985!! ================================================================================================================================
5986!! SUBROUTINE   : routing_linkup
5987!!
5988!>\BRIEF         This subroutine makes the connections between the basins and ensure global coherence.
5989!!
5990!! DESCRIPTION (definitions, functional, design, flags) :
5991!! The convention for outflow_grid is :
5992!! outflow_grid = -1 : River flow
5993!! outflow_grid = -2 : Coastal flow
5994!! outflow_grid = -3 : Return flow\n
5995!!
5996!! RECENT CHANGE(S): None
5997!!
5998!! MAIN OUTPUT VARIABLE(S):
5999!!
6000!! REFERENCES   : None
6001!!
6002!! FLOWCHART    : None
6003!! \n
6004!_ ================================================================================================================================
6005
6006SUBROUTINE routing_linkup(nbpt, contfrac, neighbours, nwbas, basin_count, basin_area, basin_id, basin_flowdir, &
6007       & basin_hierarchy, outflow_grid, outflow_basin, inflow_number, inflow_grid, inflow_basin, nbcoastal,&
6008       & coastal_basin, invented_basins)
6009    !
6010    IMPLICIT NONE
6011    !
6012!! INPUT VARIABLES
6013    INTEGER(i_std), INTENT (in)                    :: nbpt                  !! Domain size  (unitless)
6014    REAL(r_std), DIMENSION(nbpt)                   :: contfrac
6015    INTEGER(i_std), DIMENSION(nbpt,NbNeighb), INTENT (in) :: neighbours            !!
6016    REAL(r_std), INTENT(in)                        :: invented_basins       !!
6017    !
6018    INTEGER(i_std)                                 :: nwbas                 !!
6019    INTEGER(i_std), DIMENSION(nbpt)                :: basin_count           !!
6020    INTEGER(i_std), DIMENSION(nbpt,nwbas)          :: basin_id              !!
6021    INTEGER(i_std), DIMENSION(nbpt,nwbas)          :: basin_flowdir         !! Water flow directions in the basin (unitless)
6022    REAL(r_std), DIMENSION(nbpt,nwbas)             :: basin_area            !!
6023    REAL(r_std), DIMENSION(nbpt,nwbas)             :: basin_hierarchy       !!
6024    INTEGER(i_std), DIMENSION(nbpt,nwbas)          :: outflow_grid          !! Type of outflow on the grid box (unitless)
6025    INTEGER(i_std), DIMENSION(nbpt,nwbas)          :: outflow_basin         !!
6026    INTEGER(i_std), DIMENSION(nbpt,nwbas)          :: inflow_number         !!
6027    INTEGER(i_std), DIMENSION(nbpt,nwbas,nbvmax)   :: inflow_basin          !!
6028    INTEGER(i_std), DIMENSION(nbpt,nwbas,nbvmax)   :: inflow_grid           !!
6029    INTEGER(i_std), DIMENSION(nbpt)                :: nbcoastal             !!
6030    INTEGER(i_std), DIMENSION(nbpt,nwbas)          :: coastal_basin         !!
6031    !
6032!! LOCAL VARIABLES
6033    INTEGER(i_std)                                 :: sp, sb, sbl, inp, bid, outdm1, outdp1 !! Indices (unitless)
6034    INTEGER(i_std)                                 :: dp1, dm1, dm1i, dp1i, bp1, bm1 !! Indices (unitless)
6035    INTEGER(i_std)                                 :: dop, bop              !!
6036    INTEGER(i_std)                                 :: fbas(nwbas), nbfbas   !!
6037    REAL(r_std)                                    :: fbas_hierarchy(nwbas) !!
6038    REAL(r_std)                                    :: angle
6039    INTEGER(i_std)                                 :: ff(1)                 !!
6040    !
6041    ! ERRORS
6042    LOGICAL                                        :: error1, error2, error3, error4, error5 !! (true/false)
6043    !
6044!! PARAMETERS
6045    LOGICAL, PARAMETER                             :: check = .TRUE.       !! (true/false)
6046
6047!_ ================================================================================================================================   
6048    error1=.FALSE.
6049    error2=.FALSE.
6050    error3=.FALSE.
6051    error4=.FALSE.
6052    error5=.FALSE.
6053
6054    outflow_basin(:,:) = undef_int
6055    inflow_number(:,:) = 0
6056    !
6057    DO sp=1,nbpt
6058       DO sb=1,basin_count(sp)
6059          !
6060          inp = outflow_grid(sp,sb)
6061          bid = basin_id(sp,sb)
6062          !
6063          ! We only work on this point if it does not flow into the ocean
6064          ! At this point any of the outflows is designated by a negative values in
6065          ! outflow_grid
6066          !
6067          IF ( inp .GT. 0 ) THEN
6068             !
6069             ! Now find the basin in the onflow point (inp)
6070             !
6071             nbfbas = 0
6072             !
6073             !
6074             DO sbl=1,basin_count(inp)
6075                !
6076                ! Either it is a standard basin or one aggregated from ocean flow points.
6077                ! If we flow into a another grid box we have to make sure that its hierarchy in the
6078                ! basin is lower.
6079                !
6080                !
6081                IF ( basin_id(inp,sbl) .GT. 0 ) THEN
6082                   IF ( basin_id(inp,sbl) .EQ. bid .OR. basin_id(inp,sbl) .GT. invented_basins) THEN
6083                      nbfbas =nbfbas + 1
6084                      fbas(nbfbas) = sbl
6085                      fbas_hierarchy(nbfbas) = basin_hierarchy(inp,sbl)
6086                   ENDIF
6087                ELSE
6088                   IF ( COUNT(coastal_basin(inp,1:nbcoastal(inp)) .EQ. bid) .GT. 0 ) THEN
6089                      nbfbas =nbfbas + 1
6090                      fbas(nbfbas) = sbl
6091                      fbas_hierarchy(nbfbas) = basin_hierarchy(inp,sbl)
6092                   ENDIF
6093                ENDIF
6094                !
6095             ENDDO
6096             !
6097             !  If we have more than one basin we will take the one which is lowest
6098             !  in the hierarchy.
6099             !
6100             IF (nbfbas .GE. 1) THEN
6101                ff = MINLOC(fbas_hierarchy(1:nbfbas))
6102                sbl = fbas(ff(1))
6103                !
6104                bop = undef_int
6105                IF ( basin_hierarchy(inp,sbl) .LE. basin_hierarchy(sp,sb) ) THEN
6106                   IF ( basin_hierarchy(inp,sbl) .LT. basin_hierarchy(sp,sb) ) THEN
6107                      bop = sbl
6108                   ELSE
6109                      ! The same hierarchy is allowed if both grids flow in about
6110                      ! the same direction :
6111                      IF ( ( MOD(basin_flowdir(inp,sbl)+1-1, 8)+1 .EQ. basin_flowdir(sp,sb)).OR. &
6112                           & ( basin_flowdir(inp,sbl) .EQ. basin_flowdir(sp,sb)).OR. &
6113                           & ( MOD(basin_flowdir(inp,sbl)+7-1, 8)+1 .EQ. basin_flowdir(sp,sb)) ) THEN
6114                         bop = sbl
6115                      ENDIF
6116                   ENDIF
6117                ENDIF
6118                !
6119                ! If the basin is suitable (bop < undef_int) then take it
6120                !
6121                IF ( bop .LT. undef_int ) THEN
6122                   outflow_basin(sp,sb) = bop
6123                   inflow_number(inp,bop) =  inflow_number(inp,bop) + 1
6124                   IF ( inflow_number(inp,bop) .LE. nbvmax ) THEN
6125                      inflow_grid(inp, bop, inflow_number(inp,bop)) = sp
6126                      inflow_basin(inp, bop, inflow_number(inp,bop)) = sb
6127                   ELSE
6128                      error1=.TRUE.
6129                      EXIT
6130                   ENDIF
6131                ENDIF
6132             ENDIF
6133             !
6134             !
6135          ENDIF
6136          !
6137          !
6138          !
6139          ! Did we find it ?
6140          !
6141          ! In case the outflow point was ocean or we did not find the correct basin we start to look
6142          ! around. We find two options for the outflow direction (dp1 & dm1) and the corresponding
6143          ! basin index (bp1 & bm1).
6144          !
6145          !
6146          IF ( outflow_basin(sp,sb) .EQ. undef_int &
6147               & .AND. basin_flowdir(sp,sb) .GT. 0) THEN
6148             !
6149             dp1i = MOD(basin_flowdir(sp,sb)+1-1, NbNeighb)+1
6150             dp1 = neighbours(sp,dp1i)
6151             dm1i = MOD(basin_flowdir(sp,sb)+7-1, NbNeighb)+1
6152             IF ( dm1i .LT. 1 ) dm1i = 8
6153             dm1 = neighbours(sp,dm1i)
6154             !
6155             !
6156             bp1 = -1
6157             IF ( dp1 .GT. 0 ) THEN
6158                DO sbl=1,basin_count(dp1)
6159                   IF (basin_id(dp1,sbl) .EQ. bid .AND.&
6160                        & basin_hierarchy(sp,sb) .GE. basin_hierarchy(dp1,sbl) .AND. &
6161                        & bp1 .LT. 0) THEN
6162                      IF ( basin_hierarchy(sp,sb) .GT. basin_hierarchy(dp1,sbl) ) THEN
6163                         bp1 = sbl
6164                      ELSE
6165                         ! The same hierarchy is allowed if both grids flow in about
6166                         ! the same direction :
6167                         angle=MODULO(basin_flowdir(dp1,sbl)-basin_flowdir(sp,sb)+8,8)
6168                         IF ( angle >= 4 ) angle = angle-8
6169                         !
6170                         IF ( ABS(angle) <= 1 ) THEN
6171                            bp1 = sbl
6172                         ENDIF
6173                      ENDIF
6174                   ENDIF
6175                ENDDO
6176             ENDIF
6177             !
6178             bm1 = -1
6179             IF ( dm1 .GT. 0 ) THEN
6180                DO sbl=1,basin_count(dm1)
6181                   IF (basin_id(dm1,sbl) .EQ. bid .AND.&
6182                        & basin_hierarchy(sp,sb) .GE. basin_hierarchy(dm1,sbl) .AND. &
6183                        & bm1 .LT. 0) THEN
6184                      IF ( basin_hierarchy(sp,sb) .GT. basin_hierarchy(dm1,sbl) ) THEN
6185                         bm1 = sbl
6186                      ELSE                         
6187                         ! The same hierarchy is allowed if both grids flow in about
6188                         ! the same direction :
6189                         angle=MODULO(basin_flowdir(dm1,sbl)-basin_flowdir(sp,sb)+8,8)
6190                         IF ( angle >= 4 ) angle = angle-8
6191                         !
6192                         IF ( ABS(angle) <= 1 ) THEN
6193                            bm1 = sbl
6194                         ENDIF
6195                      ENDIF
6196                   ENDIF
6197                ENDDO
6198             ENDIF
6199             !
6200             !
6201             ! First deal with the case on land.
6202             !
6203             ! For that we need to check if the water will be able to flow out of the grid dp1 or dm1
6204             ! and not return to our current grid. If it is the current grid
6205             ! then we can not do anything with that neighbour. Thus we set the
6206             ! value of outdm1 and outdp1 back to -1
6207             !
6208             outdp1 = undef_int
6209             IF ( dp1 .GT. 0 .AND. bp1 .GT. 0 ) THEN
6210                ! if the outflow is into the ocean then we put something less than undef_int in outdp1!
6211                IF (basin_flowdir(dp1,bp1) .GT. 0) THEN
6212                   outdp1 = neighbours(dp1,basin_flowdir(dp1,bp1))
6213                   IF ( outdp1 .EQ. sp ) outdp1 = undef_int 
6214                ELSE
6215                   outdp1 = nbpt + 1
6216                ENDIF
6217             ENDIF
6218             outdm1 = undef_int
6219             IF ( dm1 .GT. 0 .AND. bm1 .GT. 0 ) THEN
6220                IF (basin_flowdir(dm1,bm1) .GT. 0) THEN
6221                   outdm1 = neighbours(dm1,basin_flowdir(dm1,bm1))
6222                   IF ( outdm1 .EQ. sp )  outdm1 = undef_int
6223                ELSE
6224                   outdm1 = nbpt + 1
6225                ENDIF
6226             ENDIF
6227             !
6228             ! Now that we know our options we need go through them.
6229             !
6230             dop = undef_int
6231             bop = undef_int
6232             IF ( outdp1 .LT. undef_int .AND. outdm1 .LT. undef_int) THEN
6233                !
6234                ! In this case we let the current basin flow into the smaller one
6235                !
6236                IF ( basin_area(dp1,bp1) .LT.  basin_area(dm1,bm1) ) THEN
6237                   dop = dp1
6238                   bop = bp1
6239                ELSE
6240                   dop = dm1
6241                   bop = bm1
6242                ENDIF
6243                !
6244                !
6245             ELSE IF (  outdp1 .LT. undef_int ) THEN
6246                ! If only the first one is possible
6247                dop = dp1
6248                bop = bp1
6249             ELSE IF ( outdm1 .LT. undef_int ) THEN
6250                ! If only the second one is possible
6251                dop = dm1
6252                bop = bm1
6253             ELSE
6254                !
6255                ! Now we are at the point where none of the neighboring points is suitable
6256                ! or we have a coastal point.
6257                !
6258                ! If there is an option to put the water into the ocean go for it.
6259                !
6260                IF ( outflow_grid(sp,sb) .LT. 0 .OR. dm1 .LT. 0 .OR. dp1 .LT. 0 ) THEN
6261                   dop = -1
6262                ELSE
6263                   !
6264                   ! If we are on a land point with only land neighbors but no one suitable to let the
6265                   ! water flow into we have to look for a solution in the current grid box.
6266                   !
6267                   !
6268                   IF ( bp1 .LT. 0 .AND. bm1 .LT. 0 ) THEN
6269                      !
6270                      ! Do we have more than one basin with the same ID ?
6271                      !
6272                      IF ( COUNT(basin_id(sp,1:basin_count(sp)) .EQ. bid) .GE. 2) THEN
6273                         !
6274                         ! Now we can try the option of flowing into the basin of the same grid box.
6275                         !
6276                         DO sbl=1,basin_count(sp)
6277                            IF (sbl .NE. sb .AND. basin_id(sp,sbl) .EQ. bid) THEN
6278                               ! In case this basin has a lower hierarchy or flows into a totaly
6279                               ! different direction we go for it.
6280                               IF ( (basin_hierarchy(sp,sb) .GE. basin_hierarchy(sp,sbl)) .OR. &
6281                                    & (basin_flowdir(sp,sbl) .LT. dm1i .AND.&
6282                                    & basin_flowdir(sp,sbl) .GT. dp1i) ) THEN
6283                                  dop = sp
6284                                  bop = sbl
6285                                  IF (check) THEN
6286                                     IF (basin_hierarchy(sp,sb) .LT. basin_hierarchy(sp,sbl)) THEN
6287                                        WRITE(numout,*) '>>>>>>> POINT CORRECTED against hierarchy :',&
6288                                             & sp, sb, 'into', sbl
6289                                     ENDIF
6290                                  ENDIF
6291                               ENDIF
6292                               !
6293                            ENDIF
6294                         ENDDO
6295                         !
6296                      ENDIF
6297                   ENDIF
6298                ENDIF
6299                !
6300                IF ( dop .EQ. undef_int .AND. bop .EQ. undef_int ) THEN
6301                   IF (check) THEN
6302                      WRITE(numout,*) 'Why are we here with point ', sp, sb
6303                      WRITE(numout,*) 'Coordinates : (lon,lat) = ', lalo_g(sp,2), lalo_g(sp,1)
6304                      WRITE(numout,*) 'neighbours :', neighbours_g(sp,:)
6305                      WRITE(numout,*) 'Contfrac : = ', contfrac(sp)
6306                      WRITE(numout,*) 'Local Basin ID :', basin_id(sp,1:basin_count(sp))
6307                      WRITE(numout,*) 'Local hierarchies :', basin_hierarchy(sp,1:basin_count(sp))
6308                      WRITE(numout,*) 'Local basin_flowdir :', basin_flowdir(sp,1:basin_count(sp))
6309                      WRITE(numout,*) 'Local outflowgrid :', outflow_grid(sp,1:basin_count(sp))
6310                      WRITE(numout,*) 'outflow_grid :', inp
6311                      WRITE(numout,*) 'Coodinates outflow : (lon,lat) = ', lalo_g(inp,2), lalo_g(inp,1)
6312                      WRITE(numout,*) 'Contfrac : = ', contfrac(inp)
6313                      WRITE(numout,*) 'Outflow Basin ID :', basin_id(inp,1:basin_count(inp))
6314                      WRITE(numout,*) 'Outflow hierarchies :', basin_hierarchy(inp,1:basin_count(inp))
6315                      WRITE(numout,*) 'Outflow basin_flowdir :', basin_flowdir(inp,1:basin_count(inp))
6316                      WRITE(numout,*) 'Explored options +1 :', dp1, bp1, outdp1
6317                      WRITE(numout,*) 'Explored +1 Basin ID :', basin_id(dp1,1:basin_count(dp1))
6318                      WRITE(numout,*) 'Explored +1 hierarchies :', basin_hierarchy(dp1,1:basin_count(dp1))
6319                      WRITE(numout,*) 'Explored +1 basin_flowdir :', basin_flowdir(dp1,1:basin_count(dp1))
6320                      WRITE(numout,*) 'Explored options -1 :', dm1, bm1, outdm1
6321                      WRITE(numout,*) 'Explored -1 Basin ID :', basin_id(dm1,1:basin_count(dm1))
6322                      WRITE(numout,*) 'Explored -1 hierarchies :', basin_hierarchy(dm1,1:basin_count(dm1))
6323                      WRITE(numout,*) 'Explored -1 basin_flowdir :', basin_flowdir(dm1,1:basin_count(dm1))
6324                      WRITE(numout,*) '****************************'
6325                      CALL FLUSH(numout)
6326                   ENDIF
6327                   IF ( contfrac(sp) > 0.01 ) THEN
6328                      error2=.TRUE.
6329                      EXIT
6330                   ENDIF
6331                ENDIF
6332                !
6333             ENDIF
6334             !
6335             ! Now that we know where we want the water to flow to we write the
6336             ! the information in the right fields.
6337             !
6338             IF ( dop .GT. 0 .AND. dop .NE. undef_int ) THEN
6339                outflow_grid(sp,sb) = dop
6340                outflow_basin(sp,sb) = bop
6341                inflow_number(dop,bop) =  inflow_number(dop,bop) + 1
6342                IF ( inflow_number(dop,bop) .LE. nbvmax ) THEN
6343                   inflow_grid(dop, bop, inflow_number(dop,bop)) = sp
6344                   inflow_basin(dop, bop, inflow_number(dop,bop)) = sb
6345                ELSE
6346                   error3=.TRUE.
6347                   EXIT
6348                ENDIF
6349                !
6350             ELSE
6351                outflow_grid(sp,sb) = -2
6352                outflow_basin(sp,sb) = undef_int
6353             ENDIF
6354             !
6355          ENDIF
6356          !
6357          !
6358          ! If we still have not found anything then we have to check that there is not a basin
6359          ! within the same grid box which has a lower hierarchy.
6360          !
6361          !
6362          IF ( outflow_grid(sp,sb) .GT. 0 .AND. outflow_basin(sp,sb) .EQ. undef_int &
6363               & .AND. basin_flowdir(sp,sb) .GT. 0) THEN
6364             !
6365             
6366             IF (check) &
6367                  WRITE(numout,*) 'There is no reason to here, this part of the code should be dead :', sp,sb
6368             !
6369             DO sbl=1,basin_count(sp)
6370                !
6371                ! Three conditions are needed to let the water flow into another basin of the
6372                ! same grid :
6373                ! - another basin than the current one
6374                ! - same ID
6375                ! - of lower hierarchy.
6376                !
6377                IF ( (sbl .NE. sb) .AND. (basin_id(sp,sbl) .EQ. bid)&
6378                     & .AND. (basin_hierarchy(sp,sb) .GT. basin_hierarchy(sp,sbl)) ) THEN
6379                   outflow_basin(sp,sb) = sbl
6380                   inflow_number(sp,sbl) =  inflow_number(sp,sbl) + 1
6381                   IF ( inflow_number(sp,sbl) .LE. nbvmax ) THEN
6382                      IF ( sp .EQ. 42 .AND. sbl .EQ. 1) THEN
6383                         IF (check) &
6384                              WRITE(numout,*) 'ADD INFLOW (3):', sp, sb
6385                      ENDIF
6386                      inflow_grid(sp, sbl, inflow_number(sp,sbl)) = sp
6387                      inflow_basin(sp, sbl, inflow_number(sp,sbl)) = sb
6388                   ELSE
6389                      error4=.TRUE.
6390                      EXIT
6391                   ENDIF
6392                ENDIF
6393             ENDDO
6394          ENDIF
6395          !
6396          ! Ok that is it, we give up :-)
6397          !
6398          IF ( outflow_grid(sp,sb) .GT. 0 .AND. outflow_basin(sp,sb) .EQ. undef_int &
6399               & .AND. basin_flowdir(sp,sb) .GT. 0) THEN
6400             !
6401             error5=.TRUE.
6402             EXIT
6403          ENDIF
6404       ENDDO
6405       !
6406    ENDDO
6407    IF (error1) THEN
6408       WRITE(numout,*) " routing_linkup : bop .LT. undef_int",bop
6409       CALL ipslerr_p(3,'routing_linkup', &
6410            "bop .LT. undef_int",'Increase nbvmax','stop routing_linkup')
6411    ENDIF
6412    IF (error2) THEN
6413       CALL ipslerr_p(3,'routing_linkup', &
6414            &      'In the routine which make connections between the basins and ensure global coherence,', & 
6415            &      'there is a problem with outflow linkup without any valid direction. Try with check=.TRUE.', &
6416            &      '(Perhaps there is a problem with the grid.)')
6417    ENDIF
6418    IF (error3) THEN
6419       WRITE(numout,*) " routing_linkup : dop .GT. 0 .AND. dop .NE. undef_int",dop
6420       CALL ipslerr_p(3,'routing_linkup', &
6421            "dop .GT. 0 .AND. dop .NE. undef_int",'Increase nbvmax. Try with check=.TRUE.','stop routing_linkup')
6422    ENDIF
6423    IF (error4) THEN
6424       WRITE(numout,*) " routing_linkup : (sbl .NE. sb) .AND. (basin_id(sp,sbl) .EQ. bid) ", & 
6425            &  " .AND. (basin_hierarchy(sp,sb) .GT. basin_hierarchy(sp,sbl))",sbl,sb,basin_id(sp,sbl),bid, & 
6426            &  basin_hierarchy(sp,sb),basin_hierarchy(sp,sbl)
6427       CALL ipslerr_p(3,'routing_linkup', &
6428            "(sbl .NE. sb) .AND. (basin_id(sp,sbl) .EQ. bid) .AND. (basin_hierarchy(sp,sb) .GT. basin_hierarchy(sp,sbl))" &
6429            ,'Increase nbvmax. Try with check=.TRUE.','stop routing_linkup')
6430    ENDIF
6431    IF (error5) THEN
6432       WRITE(numout,*) 'We could not find the basin into which we need to flow'
6433       WRITE(numout,*) 'Grid point ', sp, ' and basin ', sb
6434       WRITE(numout,*) 'Explored neighbours :', dm1, dp1 
6435       WRITE(numout,*) 'Outflow direction :', basin_flowdir(sp,sb)
6436       WRITE(numout,*) 'Outlfow grid :', outflow_grid(sp,sb)
6437       WRITE(numout,*) 'Outlfow basin :',outflow_basin(sp,sb)
6438       WRITE(numout,*) 'basin ID:',basin_id(sp,sb)
6439       WRITE(numout,*) 'Hierarchy :', basin_hierarchy(sp,sb)
6440       CALL ipslerr_p(3,'routing_linkup', &
6441            "We could not find the basin into which we need to flow",'Try with check=.TRUE.','stop routing_linkup')
6442    ENDIF
6443    !
6444    ! Check for each outflow basin that it exists
6445    !
6446    DO sp=1,nbpt
6447       DO sb=1,basin_count(sp)
6448          !
6449          inp = outflow_grid(sp,sb)
6450          sbl = outflow_basin(sp,sb)
6451          IF ( inp .GE. 0 ) THEN
6452             IF ( basin_count(inp) .LT. sbl ) THEN
6453                WRITE(numout,*) 'point :', sp, ' basin :', sb
6454                WRITE(numout,*) 'Flows into point :', inp, ' basin :', sbl
6455                WRITE(numout,*) 'But it flows into now here as basin count = ', basin_count(inp)
6456                CALL ipslerr_p(3,'routing_linkup','Problem with outflow','','')
6457             ENDIF
6458          ENDIF
6459       ENDDO
6460    ENDDO
6461    !
6462  END SUBROUTINE routing_linkup
6463  !
6464!! ================================================================================================================================
6465!! SUBROUTINE   : routing_fetch
6466!!
6467!>\BRIEF        This subroutine computes the fetch of each basin. This means that for each basin we
6468!!               will know how much area is upstream. It will help decide how to procede with the
6469!!               the truncation later and allow to set correctly in outflow_grid the distinction
6470!!               between coastal and river flow.
6471!!
6472!! DESCRIPTION (definitions, functional, design, flags) : None
6473!!
6474!! RECENT CHANGE(S): None
6475!!
6476!! MAIN OUTPUT VARIABLE(S):
6477!!
6478!! REFERENCES   : None
6479!!
6480!! FLOWCHART    : None
6481!! \n
6482!_ ================================================================================================================================
6483
6484SUBROUTINE routing_fetch(nbpt, resolution, contfrac, nwbas, basin_count, basin_area, basin_id,&
6485       & outflow_grid, outflow_basin, fetch_basin)
6486    !
6487    IMPLICIT NONE
6488    !
6489!! INPUT VARIABLES
6490    INTEGER(i_std), INTENT(in)                           :: nbpt          !! Domain size  (unitless)
6491    !
6492    REAL(r_std), DIMENSION(nbpt,2), INTENT(in)           :: resolution    !! The size of each grid box in X and Y (m)
6493    REAL(r_std), DIMENSION(nbpt), INTENT(in)             :: contfrac      !! Fraction of land in each grid box (unitless;0-1)
6494    !
6495    INTEGER(i_std)                                       :: nwbas         !!
6496    INTEGER(i_std), DIMENSION(nbpt), INTENT(in)          :: basin_count   !!
6497    REAL(r_std), DIMENSION(nbpt,nwbas), INTENT(inout)    :: basin_area    !!
6498    INTEGER(i_std), DIMENSION(nbpt,nwbas), INTENT(in)    :: basin_id      !!
6499    INTEGER(i_std), DIMENSION(nbpt,nwbas), INTENT(inout) :: outflow_grid  !! Type of outflow on the grid box (unitless)
6500    INTEGER(i_std), DIMENSION(nbpt,nwbas), INTENT(in)    :: outflow_basin !!
6501!
6502!! OUTPUT VARIABLES
6503    REAL(r_std), DIMENSION(nbpt,nwbas), INTENT(out)      :: fetch_basin   !!
6504    !
6505!! LOCAL VARIABLES
6506    INTEGER(i_std)                                        :: ib, ij, ff(1), it, itt, igrif, ibasf, nboutflow !! Indices (unitless)
6507    REAL(r_std)                                           :: contarea     !!
6508    REAL(r_std)                                           :: totbasins    !!
6509    REAL(r_std), DIMENSION(nbpt*nbvmax)                   :: tmp_area     !!
6510    INTEGER(i_std), DIMENSION(nbpt*nbvmax,2)              :: tmpindex     !!
6511
6512!_ ================================================================================================================================
6513    !
6514    !
6515    ! Normalize the area of all basins
6516    !
6517    DO ib=1,nbpt
6518       !
6519       totbasins = SUM(basin_area(ib,1:basin_count(ib)))
6520       contarea = resolution(ib,1)*resolution(ib,2)*contfrac(ib)
6521       !
6522       DO ij=1,basin_count(ib)
6523          basin_area(ib,ij) = basin_area(ib,ij)/totbasins*contarea
6524       ENDDO
6525       !
6526    ENDDO
6527    WRITE(numout,*) 'Normalization done'
6528    !
6529    ! Compute the area upstream of each basin
6530    !
6531    fetch_basin(:,:) = zero
6532    !
6533    !
6534    DO ib=1,nbpt
6535       !
6536       DO ij=1,basin_count(ib)
6537          !
6538          fetch_basin(ib, ij) = fetch_basin(ib, ij) + basin_area(ib,ij)
6539          !
6540          igrif = outflow_grid(ib,ij)
6541          ibasf = outflow_basin(ib,ij)
6542          !
6543          itt = 0
6544          DO WHILE (igrif .GT. 0)
6545             fetch_basin(igrif,ibasf) =  fetch_basin(igrif,ibasf) + basin_area(ib, ij)
6546             it = outflow_grid(igrif, ibasf)
6547             ibasf = outflow_basin(igrif, ibasf)
6548             igrif = it
6549             itt = itt + 1
6550             IF ( itt .GT. 500) THEN
6551                WRITE(numout,&
6552                     "('Grid ',I5, ' and basin ',I5, 'did not converge after iteration ',I5)") ib, ij, itt
6553                WRITE(numout,*) 'Basin ID :', basin_id(igrif,ibasf)
6554                WRITE(numout,&
6555                     "('We are stuck with the flow into grid ',I5,' and basin ',I5)") igrif, ibasf
6556                WRITE(numout,*) "Coordinates : ", lalo_g(igrif,2), lalo_g(igrif,1)
6557                IF ( itt .GT. 510) THEN
6558                   CALL ipslerr_p(3,'routing_fetch','Problem...','','')
6559                ENDIF
6560             ENDIF
6561          ENDDO
6562          !
6563       ENDDO
6564       !
6565    ENDDO
6566    !
6567    WRITE(numout,*) 'The smallest FETCH :', MINVAL(fetch_basin)
6568    WRITE(numout,*) 'The largest FETCH :', MAXVAL(fetch_basin)
6569    !
6570    ! Now we set for the 'num_largest' largest basins the outflow condition as stream flow
6571    ! (i.e. outflow_grid = -1) and all other outflow basins are set to coastal flow
6572    ! (i.e. outflow_grid = -2). The return flow is not touched.
6573    !
6574    nboutflow = 0
6575    !
6576    DO ib=1,nbpt
6577       !
6578       DO ij=1,basin_count(ib)
6579          !
6580          ! We do not need any more the river flow flag as we are going to reset it.
6581          !
6582          IF ( outflow_grid(ib,ij) .EQ. -1) THEN
6583             outflow_grid(ib,ij) = -2
6584          ENDIF
6585          !
6586          IF ( outflow_grid(ib,ij) .EQ. -2) THEN
6587             !
6588             nboutflow = nboutflow + 1
6589             tmp_area(nboutflow) = fetch_basin(ib,ij)
6590             tmpindex(nboutflow,1) = ib
6591             tmpindex(nboutflow,2) = ij
6592             !
6593          ENDIF
6594          !
6595       ENDDO
6596    ENDDO
6597    !
6598    DO ib=1, num_largest
6599       ff = MAXLOC(tmp_area(1:nboutflow))
6600       outflow_grid(tmpindex(ff(1),1), tmpindex(ff(1),2)) = -1
6601       tmp_area(ff(1)) = zero
6602    ENDDO
6603    !
6604  END SUBROUTINE routing_fetch
6605  !
6606!! ================================================================================================================================
6607!! SUBROUTINE   : routing_truncate
6608!!
6609!>\BRIEF         This subroutine reduces the number of basins per grid to the value chosen by the user.
6610!!               It also computes the final field which will be used to route the water at the
6611!!               requested truncation. 
6612!!
6613!! DESCRIPTION (definitions, functional, design, flags) :
6614!! Truncate if needed and find the path closest to the high resolution data.
6615!!
6616!! The algorithm :
6617!!
6618!! We only go through this procedure only as many times as there are basins to take out at most.
6619!! This is important as it allows the simplifications to spread from one grid to the other.
6620!! The for each step of the iteration and at each grid point we check the following options for
6621!! simplifying the pathways of water :
6622!! 1) If the basin of a grid flows into another basin of the same grid. Kill the one which only
6623!!    served as a transition
6624!! 2) If in one grid box we have a number of basins which flow into the ocean as coastal flow.
6625!!    We kill the smallest one and put into the largest basin. There is no need to manage many
6626!!    basins going into the ocean as coastal flows.
6627!! 3) If we have streams run in parallel from one gird box to the others (that is these are
6628!!    different basins) we will put the smaller one in the larger one. This may hapen at any
6629!!    level of the flow but in theory it should propagate downstream.
6630!! 4) If we have two basins with the same ID but flow into different grid boxes we sacrifice
6631!!    the smallest one and route it through the largest.
6632!!
6633!! Obviously if any of the options find something then we skip the rest and take out the basin.:\n
6634!!
6635!! RECENT CHANGE(S): None
6636!!
6637!! MAIN OUTPUT VARIABLE(S):
6638!!
6639!! REFERENCES   : None
6640!!
6641!! FLOWCHART    : None
6642!! \n
6643!_ ================================================================================================================================
6644
6645SUBROUTINE routing_truncate(nbpt, resolution, contfrac, nwbas, basin_count, basin_area, basin_topoind,&
6646       & fetch_basin, basin_id, basin_flowdir, outflow_grid, outflow_basin, inflow_number,&
6647       & inflow_grid, inflow_basin)
6648    !
6649    IMPLICIT NONE
6650    !
6651!! PARAMETERS
6652    INTEGER(i_std), PARAMETER                       :: pickmax = 200  !!
6653
6654!! INPUT VARIABLES
6655    INTEGER(i_std)                                  :: nbpt           !! Domain size  (unitless)
6656    !
6657    REAL(r_std), DIMENSION(nbpt,2)                  :: resolution     !! The size of each grid box in X and Y (m)
6658    REAL(r_std), DIMENSION(nbpt), INTENT(in)        :: contfrac       !! Fraction of land in each grid box (unitless;0-1)
6659    !
6660    INTEGER(i_std)                                  :: nwbas          !!
6661    INTEGER(i_std), DIMENSION(nbpt)                 :: basin_count    !!
6662    INTEGER(i_std), DIMENSION(nbpt,nwbas)           :: basin_id       !!
6663    INTEGER(i_std), DIMENSION(nbpt,nwbas)           :: basin_flowdir  !! Water flow directions in the basin (unitless)
6664    REAL(r_std), DIMENSION(nbpt,nwbas)              :: basin_area     !!
6665    REAL(r_std), DIMENSION(nbpt,nwbas)              :: basin_topoind  !! Topographic index of the residence time for a basin (m)
6666    REAL(r_std), DIMENSION(nbpt,nwbas)              :: fetch_basin    !!
6667    INTEGER(i_std), DIMENSION(nbpt,nwbas)           :: outflow_grid   !! Type of outflow on the grid box (unitless)
6668    INTEGER(i_std), DIMENSION(nbpt,nwbas)           :: outflow_basin  !!
6669    INTEGER(i_std), DIMENSION(nbpt,nwbas)           :: inflow_number  !!
6670    INTEGER(i_std), DIMENSION(nbpt,nwbas,nwbas)     :: inflow_basin   !!
6671    INTEGER(i_std), DIMENSION(nbpt,nwbas,nwbas)     :: inflow_grid    !!
6672    !
6673!! LOCAL VARIABLES
6674    INTEGER(i_std)                                  :: ib, ij, ibf, ijf, igrif, ibasf, cnt, pold, bold, ff(2) !! Indices (unitless)
6675    INTEGER(i_std)                                  :: ii, kbas, sbas, ik, iter, ibt, obj !! Indices (unitless)
6676    REAL(r_std), DIMENSION(nbpt,nbasmax)            :: floflo         !!
6677    REAL(r_std), DIMENSION(nbpt)                    :: gridarea       !!
6678    REAL(r_std), DIMENSION(nbpt)                    :: gridbasinarea  !!
6679    REAL(r_std)                                     :: ratio          !!
6680    INTEGER(i_std), DIMENSION(pickmax,2)            :: largest_basins !!
6681    INTEGER(i_std), DIMENSION(pickmax)              :: tmp_ids        !!
6682    INTEGER(i_std)                                  :: multbas        !!
6683    INTEGER(i_std)                                  :: iml(1)         !! X resolution of the high resolution grid
6684    INTEGER(i_std), DIMENSION(pickmax)              :: multbas_sz     !!
6685    REAL(r_std), DIMENSION(pickmax)                 :: tmp_area       !!
6686    INTEGER(i_std), DIMENSION(pickmax,pickmax)      :: multbas_list   !!
6687    !
6688    INTEGER(i_std)                                  :: nbtruncate     !!
6689    INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:) :: indextrunc     !!
6690!$OMP THREADPRIVATE(indextrunc)
6691
6692!_ ================================================================================================================================
6693    !
6694    !
6695    IF ( .NOT. ALLOCATED(indextrunc)) THEN
6696       ALLOCATE(indextrunc(nbpt))
6697    ENDIF
6698    !
6699    ! We have to go through the grid as least as often as we have to reduce the number of basins
6700    ! For good measure we add 3 more passages.
6701    !
6702    !
6703    DO iter = 1, MAXVAL(basin_count) - nbasmax +3
6704       !
6705       ! Get the points over which we wish to truncate
6706       !
6707       nbtruncate = 0
6708       DO ib = 1, nbpt
6709          IF ( basin_count(ib) .GT. nbasmax ) THEN
6710             nbtruncate = nbtruncate + 1
6711             indextrunc(nbtruncate) = ib
6712          ENDIF
6713       ENDDO
6714       !
6715       ! Go through the basins which need to be truncated.       
6716       !
6717       DO ibt=1,nbtruncate
6718          !
6719          ib = indextrunc(ibt)
6720          !
6721          ! Check if we have basin which flows into a basin in the same grid
6722          ! kbas = basin we will have to kill
6723          ! sbas = basin which takes over kbas
6724          !
6725          kbas = 0
6726          sbas = 0
6727          !
6728          ! 1) Can we find a basin which flows into a basin of the same grid ?
6729          !
6730          DO ij=1,basin_count(ib)
6731             DO ii=1,basin_count(ib)
6732                IF ( outflow_grid(ib,ii) .EQ. ib .AND. outflow_basin(ib, ii) .EQ. ij .AND. kbas*sbas .NE. 0) THEN
6733                   kbas = ii
6734                   sbas = ij
6735                ENDIF
6736             ENDDO
6737          ENDDO
6738          !
6739          ! 2) Merge two basins which flow into the ocean as coastal or return flow
6740          ! (outflow_grid = -2 or -3). Well obviously only if we have more than 1 and
6741          ! have not found anything yet!
6742          !
6743          IF ( (COUNT(outflow_grid(ib,1:basin_count(ib)) .EQ. -2) .GT. 1 .OR.&
6744               & COUNT(outflow_grid(ib,1:basin_count(ib)) .EQ. -3) .GT. 1) .AND.&
6745               & kbas*sbas .EQ. 0) THEN
6746             !
6747             multbas = 0
6748             multbas_sz(:) = 0
6749             !
6750             IF ( COUNT(outflow_grid(ib,1:basin_count(ib)) .EQ. -2) .GT. 1 ) THEN
6751                obj = -2
6752             ELSE
6753                obj = -3
6754             ENDIF
6755             !
6756             ! First we get the list of all basins which go out as coastal or return flow (obj)
6757             !
6758             DO ij=1,basin_count(ib)
6759                IF ( outflow_grid(ib,ij) .EQ. obj ) THEN
6760                   multbas = multbas + 1
6761                   multbas_sz(multbas) = ij
6762                   tmp_area(multbas) = fetch_basin(ib,ij)
6763                ENDIF
6764             ENDDO
6765             !
6766             ! Now the take the smallest to be transfered to the largest
6767             !
6768             iml = MAXLOC(tmp_area(1:multbas), MASK = tmp_area(1:multbas) .GT. zero)
6769             sbas = multbas_sz(iml(1))
6770             iml = MINLOC(tmp_area(1:multbas), MASK = tmp_area(1:multbas) .GT. zero)
6771             kbas = multbas_sz(iml(1))
6772             !
6773          ENDIF
6774          !
6775          !   3) If we have basins flowing into the same grid but different basins then we put them
6776          !   together. Obviously we first work with the grid which has most streams running into it
6777          !   and putting the smallest in the largests catchments.
6778          !
6779          IF ( kbas*sbas .EQ. 0) THEN
6780             !
6781             tmp_ids(1:basin_count(ib)) = outflow_grid(ib,1:basin_count(ib))
6782             multbas = 0
6783             multbas_sz(:) = 0
6784             !
6785             ! First obtain the list of basins which flow into the same basin
6786             !
6787             DO ij=1,basin_count(ib)
6788                IF ( outflow_grid(ib,ij) .GT. 0 .AND.&
6789                     & COUNT(tmp_ids(1:basin_count(ib)) .EQ. outflow_grid(ib,ij)) .GT. 1) THEN
6790                   multbas = multbas + 1
6791                   DO ii=1,basin_count(ib)
6792                      IF ( tmp_ids(ii) .EQ. outflow_grid(ib,ij)) THEN
6793                         multbas_sz(multbas) = multbas_sz(multbas) + 1
6794                         multbas_list(multbas,multbas_sz(multbas)) = ii
6795                         tmp_ids(ii) = -99
6796                      ENDIF
6797                   ENDDO
6798                ELSE
6799                   tmp_ids(ij) = -99
6800                ENDIF
6801             ENDDO
6802             !
6803             ! Did we come up with any basins to deal with this way ?
6804             !
6805             IF ( multbas .GT. 0 ) THEN
6806                !
6807                iml = MAXLOC(multbas_sz(1:multbas))
6808                ik = iml(1)
6809                !
6810                ! Take the smallest and largest of these basins !
6811                !
6812                DO ii=1,multbas_sz(ik)
6813                   tmp_area(ii) = fetch_basin(ib, multbas_list(ik,ii))
6814                ENDDO
6815                !
6816                iml = MAXLOC(tmp_area(1:multbas_sz(ik)), MASK = tmp_area(1:multbas_sz(ik)) .GT. zero)
6817                sbas = multbas_list(ik,iml(1))
6818                iml = MINLOC(tmp_area(1:multbas_sz(ik)), MASK = tmp_area(1:multbas_sz(ik)) .GT. zero)
6819                kbas = multbas_list(ik,iml(1))
6820                !
6821             ENDIF
6822             !
6823          ENDIF
6824          !
6825          !   4) If we have twice the same basin we put them together even if they flow into different
6826          !   directions. If one of them goes to the ocean it takes the advantage.
6827          !
6828          IF ( kbas*sbas .EQ. 0) THEN
6829             !
6830             tmp_ids(1:basin_count(ib)) = basin_id(ib,1:basin_count(ib))
6831             multbas = 0
6832             multbas_sz(:) = 0
6833             !
6834             ! First obtain the list of basins which have sub-basins in this grid box.
6835             ! (these are identified by their IDs)
6836             !
6837             DO ij=1,basin_count(ib)
6838                IF ( COUNT(tmp_ids(1:basin_count(ib)) .EQ. basin_id(ib,ij)) .GT. 1) THEN
6839                   multbas = multbas + 1
6840                   DO ii=1,basin_count(ib)
6841                      IF ( tmp_ids(ii) .EQ. basin_id(ib,ij)) THEN
6842                         multbas_sz(multbas) = multbas_sz(multbas) + 1
6843                         multbas_list(multbas,multbas_sz(multbas)) = ii
6844                         tmp_ids(ii) = -99
6845                      ENDIF
6846                   ENDDO
6847                ELSE
6848                   tmp_ids(ij) = -99
6849                ENDIF
6850             ENDDO
6851             !
6852             ! We are going to work on the basin with the largest number of sub-basins.
6853             ! (IF we have a basin which has subbasins !)
6854             !
6855             IF ( multbas .GT. 0 ) THEN
6856                !
6857                iml = MAXLOC(multbas_sz(1:multbas))
6858                ik = iml(1)
6859                !
6860                ! If one of the basins goes to the ocean then it is going to have the priority
6861                !
6862                tmp_area(:) = zero
6863                IF ( COUNT(outflow_grid(ib,multbas_list(ik,1:multbas_sz(ik))) .LT. 0) .GT. 0) THEN
6864                   DO ii=1,multbas_sz(ik)
6865                      IF ( outflow_grid(ib,multbas_list(ik,ii)) .LT. 0 .AND. sbas .EQ. 0 ) THEN
6866                         sbas = multbas_list(ik,ii)
6867                      ELSE
6868                         tmp_area(ii) = fetch_basin(ib, multbas_list(ik,ii))
6869                      ENDIF
6870                   ENDDO
6871                   ! take the smallest of the subbasins
6872                   iml = MINLOC(tmp_area(1:multbas_sz(ik)), MASK = tmp_area(1:multbas_sz(ik)) .GT. zero)
6873                   kbas = multbas_list(ik,iml(1))
6874                ELSE
6875                   !
6876                   ! Else we take simply the largest and smallest
6877                   !
6878                   DO ii=1,multbas_sz(ik)
6879                      tmp_area(ii) = fetch_basin(ib, multbas_list(ik,ii))
6880                   ENDDO
6881                   iml = MAXLOC(tmp_area(1:multbas_sz(ik)), MASK = tmp_area(1:multbas_sz(ik)) .GT. zero)
6882                   sbas = multbas_list(ik,iml(1))
6883                   iml = MINLOC(tmp_area(1:multbas_sz(ik)), MASK = tmp_area(1:multbas_sz(ik)) .GT. zero)
6884                   kbas = multbas_list(ik,iml(1))
6885                   !
6886                ENDIF
6887                !
6888                !
6889             ENDIF
6890          ENDIF
6891          !
6892          !
6893          !
6894          ! Then we call routing_killbas to clean up the basins in this grid
6895          !
6896          IF ( kbas .GT. 0 .AND. sbas .GT. 0 ) THEN
6897             CALL routing_killbas(nbpt, ib, kbas, sbas, nwbas, basin_count, basin_area, basin_topoind,&
6898                  & fetch_basin, basin_id, basin_flowdir, outflow_grid, outflow_basin, inflow_number,&
6899                  & inflow_grid, inflow_basin)
6900          ENDIF
6901          !
6902       ENDDO
6903       !
6904       !     
6905    ENDDO
6906    !
6907    ! If there are any grids left with too many basins we need to take out the big hammer !
6908    ! We will only do it if this represents less than 5% of all points.
6909    !
6910    IF ( COUNT(basin_count .GT. nbasmax) .GT. 0 ) THEN
6911       !
6912       !
6913       IF ( COUNT(basin_count .GT. nbasmax)/nbpt*100 .GT. 5 ) THEN
6914          WRITE(numout,*) 'We have ', COUNT(basin_count .GT. nbasmax)/nbpt*100, '% of all points which do not yet'
6915          WRITE(numout,*) 'have the right trunctaction. That is too much to apply a brutal method'
6916          DO ib = 1, nbpt
6917             IF ( basin_count(ib) .GT. nbasmax ) THEN
6918                !
6919                WRITE(numout,*) 'We did not find a basin which could be supressed. We will'
6920                WRITE(numout,*) 'not be able to reduce the truncation in grid ', ib
6921                DO ij=1,basin_count(ib)
6922                   WRITE(numout,*) 'grid, basin nb and id :', ib, ij, basin_id(ib,ij)
6923                   WRITE(numout,*) 'Outflow grid and basin ->', outflow_grid(ib,ij), outflow_basin(ib, ij)
6924                ENDDO
6925             ENDIF
6926          ENDDO
6927          CALL ipslerr_p(3,'routing_truncate','No basin found which could be supressed.','','')
6928       ELSE
6929          !
6930          !
6931          DO ib = 1,nbpt
6932             DO WHILE ( basin_count(ib) .GT. nbasmax )
6933                !
6934                IF (printlev>=3) WRITE(numout,*) 'HAMMER, ib, basin_count :', ib, basin_count(ib)
6935                !
6936                ! Here we simply put the smallest basins into the largest ones. It is really a brute force
6937                ! method but it will only be applied if everything has failed.
6938                !
6939                DO ii = 1,basin_count(ib)
6940                   tmp_area(ii) = fetch_basin(ib, ii)
6941                ENDDO
6942                !
6943                iml = MAXLOC(tmp_area(1:basin_count(ib)), MASK = tmp_area(1:basin_count(ib)) .GT. 0.)
6944                sbas =iml(1)
6945                iml = MINLOC(tmp_area(1:basin_count(ib)), MASK = tmp_area(1:basin_count(ib)) .GT. 0.)
6946                kbas = iml(1)
6947                !
6948                IF ( kbas .GT. 0 .AND. sbas .GT. 0 ) THEN
6949                   CALL routing_killbas(nbpt, ib, kbas, sbas, nwbas, basin_count, basin_area, basin_topoind,&
6950                        & fetch_basin, basin_id, basin_flowdir, outflow_grid, outflow_basin, inflow_number,&
6951                        & inflow_grid, inflow_basin)
6952                ENDIF
6953             ENDDO
6954          ENDDO
6955          !
6956       ENDIF
6957       !
6958       !
6959    ENDIF
6960    !
6961    ! Now that we have reached the right truncation (resolution) we will start
6962    ! to produce the variables we will use to route the water.
6963    !
6964    DO ib=1,nbpt
6965       !
6966       ! For non existing basins the route_tobasin variable is put to zero. This will allow us
6967       ! to pick up the number of basin afterwards.
6968       !
6969       route_togrid(ib,:) = ib
6970       route_tobasin(ib,:) = 0
6971       routing_area(ib,:) = zero
6972       !
6973    ENDDO
6974    !
6975    ! Transfer the info into the definitive variables
6976    !
6977    DO ib=1,nbpt
6978       DO ij=1,basin_count(ib)
6979          routing_area(ib,ij) = basin_area(ib,ij)
6980          topo_resid(ib,ij) = basin_topoind(ib,ij)
6981          global_basinid(ib,ij) = basin_id(ib,ij)
6982          route_togrid(ib,ij) = outflow_grid(ib,ij)
6983          route_tobasin(ib,ij) = outflow_basin(ib,ij)
6984       ENDDO
6985    ENDDO
6986    !
6987    !
6988    ! Set the new convention for the outflow conditions
6989    ! Now it is based in the outflow basin and the outflow grid will
6990    ! be the same as the current.
6991    ! returnflow to the grid : nbasmax + 1
6992    ! coastal flow           : nbasmax + 2
6993    ! river outflow          : nbasmax + 3
6994    !
6995    ! Here we put everything here in coastal flow. It is later where we will
6996    ! put the largest basins into river outflow.
6997    !
6998    DO ib=1,nbpt
6999       DO ij=1,basin_count(ib)
7000          ! River flows
7001          IF ( route_togrid(ib,ij) .EQ. -1 ) THEN
7002             route_tobasin(ib,ij) = nbasmax + 2
7003             route_togrid(ib,ij) = ib
7004          ! Coastal flows
7005          ELSE IF ( route_togrid(ib,ij) .EQ. -2 ) THEN
7006             route_tobasin(ib,ij) = nbasmax + 2
7007             route_togrid(ib,ij) = ib
7008          ! Return flow
7009          ELSE IF ( route_togrid(ib,ij) .EQ. -3 ) THEN
7010             route_tobasin(ib,ij) = nbasmax + 1
7011             route_togrid(ib,ij) = ib
7012          ENDIF
7013       ENDDO
7014    ENDDO
7015    !
7016    ! A second check on the data. Just make sure that each basin flows somewhere.
7017    !
7018    DO ib=1,nbpt
7019       DO ij=1,basin_count(ib)
7020          ibf = route_togrid(ib,ij)
7021          ijf = route_tobasin(ib,ij)
7022          IF ( ijf .GT. basin_count(ibf) .AND.  ijf .LE. nbasmax) THEN
7023             WRITE(numout,*) 'Second check'
7024             WRITE(numout,*) 'point :', ib, ' basin :', ij
7025             WRITE(numout,*) 'Flows into point :', ibf, ' basin :', ijf
7026             WRITE(numout,*) 'But it flows into now here as basin count = ', basin_count(ibf)
7027             CALL ipslerr_p(3,'routing_truncate','Problem with routing..','','')
7028          ENDIF
7029       ENDDO
7030    ENDDO
7031    !
7032    ! Verify areas of the continents
7033    !
7034    floflo(:,:) = zero
7035    gridarea(:) = contfrac(:)*resolution(:,1)*resolution(:,2)
7036    DO ib=1,nbpt
7037       gridbasinarea(ib) = SUM(routing_area(ib,:))
7038    ENDDO
7039    !
7040    DO ib=1,nbpt
7041       DO ij=1,basin_count(ib)
7042          cnt = 0
7043          igrif = ib
7044          ibasf = ij
7045          DO WHILE (ibasf .LE. nbasmax .AND. cnt .LT. nbasmax*nbpt)
7046             cnt = cnt + 1
7047             pold = igrif
7048             bold = ibasf
7049             igrif = route_togrid(pold, bold)
7050             ibasf = route_tobasin(pold, bold)
7051             IF ( ibasf .GT. basin_count(igrif)  .AND.  ibasf .LE. nbasmax) THEN
7052                WRITE(numout,*) 'We should not be here as the basin flows into the pampa'
7053                WRITE(numout,*) 'Last correct point :', pold, bold
7054                WRITE(numout,*) 'It pointed to in the new variables :', route_togrid(pold, bold),route_tobasin(pold, bold) 
7055                WRITE(numout,*) 'The old variables gave :', outflow_grid(pold, bold), outflow_basin(pold, bold) 
7056                WRITE(numout,*) 'Where we ended up :', igrif,ibasf
7057                CALL ipslerr_p(3,'routing_truncate','Problem with routing..','','')
7058             ENDIF
7059          ENDDO
7060          !
7061          IF ( ibasf .GT. nbasmax ) THEN
7062             floflo(igrif,bold) = floflo(igrif,bold) + routing_area(ib,ij)
7063          ELSE
7064             WRITE(numout,*) 'The flow did not end up in the ocean or in the grid cell.'
7065             WRITE(numout,*) 'For grid ', ib, ' and basin ', ij
7066             WRITE(numout,*) 'The last grid was ', igrif, ' and basin ', ibasf
7067             CALL ipslerr_p(3,'routing_truncate','Problem with routing..','','')
7068          ENDIF
7069       ENDDO
7070    ENDDO
7071    !
7072    DO ib=1,nbpt
7073       IF ( gridbasinarea(ib) > zero ) THEN
7074          ratio = gridarea(ib)/gridbasinarea(ib)
7075          routing_area(ib,:) = routing_area(ib,:)*ratio
7076       ELSE
7077          WRITE(numout,*) 'gridbasinarea(ib) <= zero. We should stop here :', ib
7078       ENDIF
7079    ENDDO
7080    !
7081    WRITE(numout,*) 'Sum of area of all outflow areas :',SUM(routing_area)
7082    WRITE(numout,*) 'Surface of all continents :', SUM(gridarea)
7083    !
7084    ! Redo the the distinction between river outflow and coastal flow. We can not
7085    ! take into account the return flow points.
7086    !
7087    ibf = 0
7088    DO ib=1, pickmax
7089       ff = MAXLOC(floflo)
7090       ! tdo - To take into account rivers that do not flow to the oceans
7091       IF ( route_tobasin(ff(1), ff(2)) .GT. nbasmax ) THEN
7092!       IF ( route_tobasin(ff(1), ff(2)) .EQ. nbasmax + 2) THEN
7093          ibf = ibf + 1
7094          largest_basins(ibf,:) = ff(:)
7095       ENDIF
7096       floflo(ff(1), ff(2)) = zero
7097    ENDDO
7098    !
7099    ! Put the largest basins into river flows.
7100    !
7101    IF ( ibf .LT.  num_largest) THEN
7102       WRITE(numout,*) 'Not enough basins to choose the ',  num_largest, 'largest'
7103       CALL ipslerr_p(3,'routing_truncate','Not enough basins','','')
7104    ENDIF
7105    !
7106    !
7107    !
7108    DO ib=1, num_largest
7109       route_tobasin(largest_basins(ib,1),largest_basins(ib,2)) = nbasmax + 3
7110    ENDDO
7111    !
7112    WRITE(numout,*) 'NUMBER OF RIVERS :', COUNT(route_tobasin .GE. nbasmax + 3)
7113    !
7114  END SUBROUTINE  routing_truncate
7115  !
7116!! ================================================================================================================================
7117!! SUBROUTINE   : routing_killbas
7118!!
7119!>\BRIEF        The aim of this subroutine is to kill a basin (that is put into another larger one).
7120!!              When we do this we need to be careful and change all associated variables. 
7121!!
7122!! DESCRIPTION (definitions, functional, design, flags) : None
7123!!
7124!! RECENT CHANGE(S): None
7125!!
7126!! MAIN OUTPUT VARIABLE(S):
7127!!
7128!! REFERENCES   : None
7129!!
7130!! FLOWCHART    : None
7131!! \n
7132!_ ================================================================================================================================
7133
7134SUBROUTINE routing_killbas(nbpt, ib, tokill, totakeover, nwbas, basin_count, basin_area, basin_topoind,&
7135       & fetch_basin, basin_id, basin_flowdir, outflow_grid, outflow_basin, inflow_number,&
7136       & inflow_grid, inflow_basin)
7137    !
7138    !
7139    IMPLICIT NONE
7140    !
7141    INTEGER(i_std)                              :: tokill        !!
7142    INTEGER(i_std)                              :: totakeover    !!
7143    INTEGER(i_std)                              :: nbpt          !! Domain size  (unitless)
7144    INTEGER(i_std)                              :: ib            !! Current basin (unitless)
7145    !
7146    INTEGER(i_std)                              :: nwbas         !!
7147    INTEGER(i_std), DIMENSION(nbpt)             :: basin_count   !!
7148    INTEGER(i_std), DIMENSION(nbpt,nwbas)       :: basin_id      !!
7149    INTEGER(i_std), DIMENSION(nbpt,nwbas)       :: basin_flowdir !! Water flow directions in the basin (unitless)
7150    REAL(r_std), DIMENSION(nbpt,nwbas)          :: basin_area    !!
7151    REAL(r_std), DIMENSION(nbpt,nwbas)          :: basin_topoind !! Topographic index of the residence time for a basin (m)
7152    REAL(r_std), DIMENSION(nbpt,nwbas)          :: fetch_basin   !!
7153    INTEGER(i_std), DIMENSION(nbpt,nwbas)       :: outflow_grid  !! Type of outflow on the grid box (unitless)
7154    INTEGER(i_std), DIMENSION(nbpt,nwbas)       :: outflow_basin !!
7155    INTEGER(i_std), DIMENSION(nbpt,nwbas)       :: inflow_number !!
7156    INTEGER(i_std), DIMENSION(nbpt,nwbas,nwbas) :: inflow_basin  !!
7157    INTEGER(i_std), DIMENSION(nbpt,nwbas,nwbas) :: inflow_grid   !!
7158    !
7159!! LOCAL VARIABLES
7160    INTEGER(i_std)                              :: inf, ibs, ing, inb, ibasf, igrif, it !! Indices (unitless)
7161    LOGICAL                                     :: doshift       !! (true/false)
7162
7163!_ ================================================================================================================================
7164    !
7165    ! Update the information needed in the basin "totakeover"
7166    ! For the moment only area
7167    !
7168    IF (printlev>=3) THEN
7169       WRITE(numout,*) 'KILL BASIN :', ib, tokill, totakeover, basin_id(ib,tokill), basin_id(ib,totakeover)
7170    END IF
7171    !
7172    basin_area(ib, totakeover) = basin_area(ib, totakeover) +  basin_area(ib, tokill)
7173    basin_topoind(ib, totakeover) = (basin_topoind(ib, totakeover) + basin_topoind(ib, tokill))/2.0
7174    !
7175    ! Add the fetch of the basin will kill to the one which gets the water
7176    !
7177    fetch_basin(ib, totakeover) = fetch_basin(ib, totakeover) + fetch_basin(ib, tokill)
7178    igrif = outflow_grid(ib,totakeover)
7179    ibasf = outflow_basin(ib,totakeover)
7180    !
7181    inf = 0
7182    DO WHILE (igrif .GT. 0)
7183       fetch_basin(igrif,ibasf) =  fetch_basin(igrif,ibasf) + fetch_basin(ib, tokill) 
7184       it = outflow_grid(igrif, ibasf)
7185       ibasf = outflow_basin(igrif, ibasf)
7186       igrif = it
7187       inf = inf + 1
7188    ENDDO
7189    !
7190    ! Take out the basin we have just rerouted from the fetch of the basins in which it used to flow.
7191    !
7192    igrif = outflow_grid(ib,tokill)
7193    ibasf = outflow_basin(ib,tokill)
7194    !
7195    DO WHILE (igrif .GT. 0)
7196       fetch_basin(igrif,ibasf) =  fetch_basin(igrif,ibasf) - fetch_basin(ib, tokill)
7197       it = outflow_grid(igrif, ibasf)
7198       ibasf = outflow_basin(igrif, ibasf)
7199       igrif = it
7200    ENDDO   
7201    !
7202    !  Redirect the flows which went into the basin to be killed before we change everything
7203    !
7204    DO inf = 1, inflow_number(ib, tokill)
7205       outflow_basin(inflow_grid(ib, tokill, inf), inflow_basin(ib, tokill, inf)) = totakeover
7206       inflow_number(ib, totakeover) = inflow_number(ib, totakeover) + 1
7207       inflow_grid(ib, totakeover,  inflow_number(ib, totakeover)) = inflow_grid(ib, tokill, inf)
7208       inflow_basin(ib, totakeover,  inflow_number(ib, totakeover)) = inflow_basin(ib, tokill, inf)
7209    ENDDO
7210    !
7211    ! Take out the basin to be killed from the list of inflow basins of the downstream basin
7212    ! (In case the basin does not flow into an ocean or lake)
7213    !
7214    IF ( outflow_grid(ib,tokill) .GT. 0) THEN
7215       !
7216       ing = outflow_grid(ib, tokill)
7217       inb = outflow_basin(ib, tokill)
7218       doshift = .FALSE.
7219       !
7220       DO inf = 1, inflow_number(ing, inb)
7221          IF ( doshift ) THEN
7222             inflow_grid(ing, inb, inf-1) = inflow_grid(ing, inb, inf)
7223             inflow_basin(ing, inb, inf-1) = inflow_basin(ing, inb, inf)
7224          ENDIF
7225          IF ( inflow_grid(ing, inb, inf) .EQ. ib .AND. inflow_basin(ing, inb, inf) .EQ. tokill) THEN
7226             doshift = .TRUE.
7227          ENDIF
7228       ENDDO
7229       !
7230       ! This is only to allow for the last check
7231       !
7232       inf = inflow_number(ing, inb)
7233       IF ( inflow_grid(ing, inb, inf) .EQ. ib .AND. inflow_basin(ing, inb, inf) .EQ. tokill) THEN
7234          doshift = .TRUE.
7235       ENDIF
7236       !
7237       IF ( .NOT. doshift ) THEN
7238          WRITE(numout,*) 'Strange we did not find the basin to kill in the downstream basin'
7239          CALL ipslerr_p(3,'routing_killbas','Basin not found','','')
7240       ENDIF
7241       inflow_number(ing, inb) = inflow_number(ing, inb) - 1
7242       
7243    ENDIF
7244    !
7245    ! Now remove from the arrays the information of basin "tokill"
7246    !
7247    basin_id(ib, tokill:basin_count(ib)-1) = basin_id(ib, tokill+1:basin_count(ib))
7248    basin_flowdir(ib, tokill:basin_count(ib)-1) = basin_flowdir(ib, tokill+1:basin_count(ib))
7249    basin_area(ib, tokill:basin_count(ib)-1) = basin_area(ib, tokill+1:basin_count(ib))
7250    basin_area(ib, basin_count(ib):nwbas) = zero
7251    basin_topoind(ib, tokill:basin_count(ib)-1) = basin_topoind(ib, tokill+1:basin_count(ib))
7252    basin_topoind(ib, basin_count(ib):nwbas) = zero
7253    fetch_basin(ib, tokill:basin_count(ib)-1) = fetch_basin(ib, tokill+1:basin_count(ib))
7254    fetch_basin(ib, basin_count(ib):nwbas) = zero
7255    !
7256    ! Before we remove the information from the outflow fields we have to correct the corresponding inflow fields
7257    ! of the grids into which the flow goes
7258    !
7259    DO ibs = tokill+1,basin_count(ib)
7260       ing = outflow_grid(ib, ibs)
7261       inb = outflow_basin(ib, ibs)
7262       IF ( ing .GT. 0 ) THEN
7263          DO inf = 1, inflow_number(ing, inb)
7264             IF ( inflow_grid(ing,inb,inf) .EQ. ib .AND. inflow_basin(ing,inb,inf) .EQ. ibs) THEN
7265                inflow_basin(ing,inb,inf) = ibs - 1
7266             ENDIF
7267          ENDDO
7268       ENDIF
7269    ENDDO
7270    outflow_grid(ib, tokill:basin_count(ib)-1) = outflow_grid(ib, tokill+1:basin_count(ib))
7271    outflow_basin(ib, tokill:basin_count(ib)-1) = outflow_basin(ib, tokill+1:basin_count(ib))
7272    !
7273    ! Basins which moved down also need to redirect their incoming flows.
7274    !
7275    DO ibs=tokill+1, basin_count(ib)
7276       DO inf = 1, inflow_number(ib, ibs)
7277          outflow_basin(inflow_grid(ib, ibs, inf), inflow_basin(ib, ibs, inf)) = ibs-1
7278       ENDDO
7279    ENDDO
7280    !
7281    ! Shift the inflow basins
7282    !
7283    DO it = tokill+1,basin_count(ib)
7284       inflow_grid(ib, it-1, 1:inflow_number(ib,it)) =  inflow_grid(ib, it, 1:inflow_number(ib,it))
7285       inflow_basin(ib, it-1, 1:inflow_number(ib,it)) =  inflow_basin(ib, it, 1:inflow_number(ib,it))
7286       inflow_number(ib,it-1) = inflow_number(ib,it)
7287    ENDDO
7288    !
7289    basin_count(ib) = basin_count(ib) - 1
7290    !
7291  END SUBROUTINE routing_killbas 
7292  !
7293!! ================================================================================================================================
7294!! SUBROUTINE   : routing_names
7295!!
7296!>\BRIEF         This subroutine lists the name of the largest basins which are explicitly listed in the basin
7297!!               description file used by ORCHIDEE.
7298!!
7299!! DESCRIPTION (definitions, functional, design, flags) : None
7300!!
7301!! RECENT CHANGE(S): None
7302!!
7303!! MAIN OUTPUT VARIABLE(S):
7304!!
7305!! REFERENCES   : None
7306!!
7307!! FLOWCHART    : None
7308!! \n
7309!_ ================================================================================================================================
7310
7311SUBROUTINE routing_names(numlar, basin_names)
7312    !
7313    IMPLICIT NONE
7314    !
7315    ! Arguments
7316    !
7317    INTEGER(i_std), INTENT(in)             :: numlar              !!
7318    CHARACTER(LEN=*), INTENT(inout)        :: basin_names(numlar) !! Name of the basins (unitless)
7319!! PARAMETERS
7320    INTEGER(i_std), PARAMETER              :: listleng=349        !!
7321    !
7322!! LOCAL VARIABLES
7323    INTEGER(i_std)                         :: lenstr, i           !!
7324    CHARACTER(LEN=60), DIMENSION(listleng) :: list_names          !!
7325    CHARACTER(LEN=60)                      :: tmp_str             !!
7326
7327!_ ================================================================================================================================
7328    !
7329
7330    lenstr = LEN(basin_names(1))
7331    !
7332    list_names(1) = "Amazon"
7333    list_names(2) = "Nile"
7334    list_names(3) = "Zaire"
7335    list_names(4) = "Mississippi"
7336    list_names(5) = "Amur"
7337    list_names(6) = "Parana"
7338    list_names(7) = "Yenisei"
7339    list_names(8) = "Ob"
7340    list_names(9) = "Lena"
7341    list_names(10) = "Niger"
7342    list_names(11) = "Zambezi"
7343    list_names(12) = "Erg Iguidi (Sahara)"
7344    list_names(13) = "Chang Jiang (Yangtze)"
7345    list_names(14) = "Mackenzie"
7346    list_names(15) = "Ganges"
7347    list_names(16) = "Chari"
7348    list_names(17) = "Volga"
7349    list_names(18) = "St. Lawrence"
7350    list_names(19) = "Indus"
7351    list_names(20) = "Syr-Darya"
7352    list_names(21) = "Nelson"
7353    list_names(22) = "Orinoco"
7354    list_names(23) = "Murray"
7355    list_names(24) = "Great Artesian Basin"
7356    list_names(25) = "Shatt el Arab"
7357    list_names(26) = "Orange"
7358    list_names(27) = "Huang He"
7359    list_names(28) = "Yukon"
7360    list_names(29) = "Senegal"
7361    list_names(30) = "Chott Jerid"
7362    list_names(31) = "Jubba"
7363    list_names(32) = "Colorado (Ari)"
7364    list_names(33) = "Rio Grande (US)"
7365    list_names(34) = "Danube"
7366    list_names(35) = "Mekong"
7367    list_names(36) = "Tocantins"
7368    list_names(37) = "Wadi al Farigh"
7369    list_names(38) = "Tarim"
7370    list_names(39) = "Columbia"
7371    list_names(40) = "Komadugu Yobe (Tchad)"
7372    list_names(41) = "Kolyma"
7373    list_names(42) = "Sao Francisco"
7374    list_names(43) = "Amu-Darya"
7375    list_names(44) = "GHAASBasin51"
7376    list_names(45) = "Dnepr"
7377    list_names(46) = "GHAASBasin61"
7378    list_names(47) = "Don"
7379    list_names(48) = "Colorado (Arg)"
7380    list_names(49) = "Limpopo"
7381    list_names(50) = "GHAASBasin50"
7382    list_names(51) = "Zhujiang"
7383    list_names(52) = "Irrawaddy"
7384    list_names(53) = "Volta"
7385    list_names(54) = "GHAASBasin54"
7386    list_names(55) = "Farah"
7387    list_names(56) = "Khatanga"
7388    list_names(57) = "Dvina"
7389    list_names(58) = "Urugay"
7390    list_names(59) = "Qarqan"
7391    list_names(60) = "GHAASBasin75"
7392    list_names(61) = "Parnaiba"
7393    list_names(62) = "GHAASBasin73"
7394    list_names(63) = "Indigirka"
7395    list_names(64) = "Churchill (Hud)"
7396    list_names(65) = "Godavari"
7397    list_names(66) = "Pur - Taz"
7398    list_names(67) = "Pechora"
7399    list_names(68) = "Baker"
7400    list_names(69) = "Ural"
7401    list_names(70) = "Neva"
7402    list_names(71) = "Liao"
7403    list_names(72) = "Salween"
7404    list_names(73) = "GHAASBasin73"
7405    list_names(74) = "Jordan"
7406    list_names(75) = "GHAASBasin78"
7407    list_names(76) = "Magdalena"
7408    list_names(77) = "Krishna"
7409    list_names(78) = "Salado"
7410    list_names(79) = "Fraser"
7411    list_names(80) = "Hai Ho"
7412    list_names(81) = "Huai"
7413    list_names(82) = "Yana"
7414    list_names(83) = "GHAASBasin95"
7415    list_names(84) = "GHAASBasin105"
7416    list_names(85) = "Kura"
7417    list_names(86) = "Olenek"
7418    list_names(87) = "Ogooue"
7419    list_names(88) = "Taymyr"
7420    list_names(89) = "Negro Arg"
7421    list_names(90) = "Chubut"
7422    list_names(91) = "GHAASBasin91"
7423    list_names(92) = "GHAASBasin122"
7424    list_names(93) = "GHAASBasin120"
7425    list_names(94) = "Sacramento"
7426    list_names(95) = "Fitzroy West"
7427    list_names(96) = "Grande de Santiago"
7428    list_names(97) = "Rufiji"
7429    list_names(98) = "Wisla"
7430    list_names(99) = "GHAASBasin47"
7431    list_names(100) = "GHAASBasin127"
7432    list_names(101) = "Hong"
7433    list_names(102) = "GHAASBasin97"
7434    list_names(103) = "Swan-Avon"
7435    list_names(104) = "Rhine"
7436    list_names(105) = "Cuanza"
7437    list_names(106) = "GHAASBasin106"
7438    list_names(107) = "GHAASBasin142"
7439    list_names(108) = "Roviuna"
7440    list_names(109) = "Essequibo"
7441    list_names(110) = "Elbe"
7442    list_names(111) = "Koksoak"
7443    list_names(112) = "Chao Phraya"
7444    list_names(113) = "Brahmani"
7445    list_names(114) = "GHAASBasin165"
7446    list_names(115) = "Pyasina"
7447    list_names(116) = "Fitzroy East"
7448    list_names(117) = "GHAASBasin173"
7449    list_names(118) = "Albany"
7450    list_names(119) = "Sanaga"
7451    list_names(120) = "GHAASBasin120"
7452    list_names(121) = "GHAASBasin178"
7453    list_names(122) = "GHAASBasin148"
7454    list_names(123) = "Brazos (Tex)"
7455    list_names(124) = "GHAASBasin124"
7456    list_names(125) = "Alabama"
7457    list_names(126) = "GHAASBasin174"
7458    list_names(127) = "GHAASBasin179"
7459    list_names(128) = "Balsas"
7460    list_names(129) = "GHAASBasin172"
7461    list_names(130) = "Burdekin"
7462    list_names(131) = "Colorado (Texas)"
7463    list_names(132) = "GHAASBasin150"
7464    list_names(133) = "Odra"
7465    list_names(134) = "Loire"
7466    list_names(135) = "GHAASBasin98"
7467    list_names(136) = "Galana"
7468    list_names(137) = "Kuskowin"
7469    list_names(138) = "Moose"
7470    list_names(139) = "Narmada"
7471    list_names(140) = "GHAASBasin140"
7472    list_names(141) = "GHAASBasin141"
7473    list_names(142) = "Flinders"
7474    list_names(143) = "Kizil Irmak"
7475    list_names(144) = "GHAASBasin144"
7476    list_names(145) = "Save"
7477    list_names(146) = "Roper"
7478    list_names(147) = "Churchill (Atlantic)"
7479    list_names(148) = "GHAASBasin148"
7480    list_names(149) = "Victoria"
7481    list_names(150) = "Back"
7482    list_names(151) = "Bandama"
7483    list_names(152) = "Severn (Can)"
7484    list_names(153) = "Po"
7485    list_names(154) = "GHAASBasin154"
7486    list_names(155) = "GHAASBasin155"
7487    list_names(156) = "GHAASBasin156"
7488    list_names(157) = "Rhone"
7489    list_names(158) = "Tana (Ken)"
7490    list_names(159) = "La Grande"
7491    list_names(160) = "GHAASBasin160"
7492    list_names(161) = "Cunene"
7493    list_names(162) = "Douro"
7494    list_names(163) = "GHAASBasin163"
7495    list_names(164) = "Nemanus"
7496    list_names(165) = "GHAASBasin165"
7497    list_names(166) = "Anabar"
7498    list_names(167) = "Hayes"
7499    list_names(168) = "Mearim"
7500    list_names(169) = "GHAASBasin169"
7501    list_names(170) = "Panuco"
7502    list_names(171) = "GHAASBasin171"
7503    list_names(172) = "Doce"
7504    list_names(173) = "Gasgoyne"
7505    list_names(174) = "GHAASBasin174"
7506    list_names(175) = "GHAASBasin175"
7507    list_names(176) = "Ashburton"
7508    list_names(177) = "GHAASBasin177"
7509    list_names(178) = "Peel"
7510    list_names(179) = "Daugava"
7511    list_names(180) = "GHAASBasin180"
7512    list_names(181) = "Ebro"
7513    list_names(182) = "Comoe"
7514    list_names(183) = "Jacui"
7515    list_names(184) = "GHAASBasin184"
7516    list_names(185) = "Kapuas"
7517    list_names(186) = "GHAASBasin186"
7518    list_names(187) = "Penzhina"
7519    list_names(188) = "Cauweri"
7520    list_names(189) = "GHAASBasin189"
7521    list_names(190) = "Mamberamo"
7522    list_names(191) = "Sepik"
7523    list_names(192) = "GHAASBasin192"
7524    list_names(193) = "Sassandra"
7525    list_names(194) = "GHAASBasin194"
7526    list_names(195) = "GHAASBasin195"
7527    list_names(196) = "Nottaway"
7528    list_names(197) = "Barito"
7529    list_names(198) = "GHAASBasin198"
7530    list_names(199) = "Seine"
7531    list_names(200) = "Tejo"
7532    list_names(201) = "GHAASBasin201"
7533    list_names(202) = "Gambia"
7534    list_names(203) = "Susquehanna"
7535    list_names(204) = "Dnestr"
7536    list_names(205) = "Murchinson"
7537    list_names(206) = "Deseado"
7538    list_names(207) = "Mitchell"
7539    list_names(208) = "Mahakam"
7540    list_names(209) = "GHAASBasin209"
7541    list_names(210) = "Pangani"
7542    list_names(211) = "GHAASBasin211"
7543    list_names(212) = "GHAASBasin212"
7544    list_names(213) = "GHAASBasin213"
7545    list_names(214) = "GHAASBasin214"
7546    list_names(215) = "GHAASBasin215"
7547    list_names(216) = "Bug"
7548    list_names(217) = "GHAASBasin217"
7549    list_names(218) = "Usumacinta"
7550    list_names(219) = "Jequitinhonha"
7551    list_names(220) = "GHAASBasin220"
7552    list_names(221) = "Corantijn"
7553    list_names(222) = "Fuchun Jiang"
7554    list_names(223) = "Copper"
7555    list_names(224) = "Tapti"
7556    list_names(225) = "Menjiang"
7557    list_names(226) = "Karun"
7558    list_names(227) = "Mezen"
7559    list_names(228) = "Guadiana"
7560    list_names(229) = "Maroni"
7561    list_names(230) = "GHAASBasin230"
7562    list_names(231) = "Uda"
7563    list_names(232) = "GHAASBasin232"
7564    list_names(233) = "Kuban"
7565    list_names(234) = "Colville"
7566    list_names(235) = "Thaane"
7567    list_names(236) = "Alazeya"
7568    list_names(237) = "Paraiba do Sul"
7569    list_names(238) = "GHAASBasin238"
7570    list_names(239) = "Fortesque"
7571    list_names(240) = "GHAASBasin240"
7572    list_names(241) = "GHAASBasin241"
7573    list_names(242) = "Winisk"
7574    list_names(243) = "GHAASBasin243"
7575    list_names(244) = "GHAASBasin244"
7576    list_names(245) = "Ikopa"
7577    list_names(246) = "Gilbert"
7578    list_names(247) = "Kouilou"
7579    list_names(248) = "Fly"
7580    list_names(249) = "GHAASBasin249"
7581    list_names(250) = "GHAASBasin250"
7582    list_names(251) = "GHAASBasin251"
7583    list_names(252) = "Mangoky"
7584    list_names(253) = "Damodar"
7585    list_names(254) = "Onega"
7586    list_names(255) = "Moulouya"
7587    list_names(256) = "GHAASBasin256"
7588    list_names(257) = "Ord"
7589    list_names(258) = "GHAASBasin258"
7590    list_names(259) = "GHAASBasin259"
7591    list_names(260) = "GHAASBasin260"
7592    list_names(261) = "GHAASBasin261"
7593    list_names(262) = "Narva"
7594    list_names(263) = "GHAASBasin263"
7595    list_names(264) = "Seal"
7596    list_names(265) = "Cheliff"
7597    list_names(266) = "Garonne"
7598    list_names(267) = "Rupert"
7599    list_names(268) = "GHAASBasin268"
7600    list_names(269) = "Brahmani"
7601    list_names(270) = "Sakarya"
7602    list_names(271) = "Gourits"
7603    list_names(272) = "Sittang"
7604    list_names(273) = "Rajang"
7605    list_names(274) = "Evros"
7606    list_names(275) = "Appalachicola"
7607    list_names(276) = "Attawapiskat"
7608    list_names(277) = "Lurio"
7609    list_names(278) = "Daly"
7610    list_names(279) = "Penner"
7611    list_names(280) = "GHAASBasin280"
7612    list_names(281) = "GHAASBasin281"
7613    list_names(282) = "Guadalquivir"
7614    list_names(283) = "Nadym"
7615    list_names(284) = "GHAASBasin284"
7616    list_names(285) = "Saint John"
7617    list_names(286) = "GHAASBasin286"
7618    list_names(287) = "Cross"
7619    list_names(288) = "Omoloy"
7620    list_names(289) = "Oueme"
7621    list_names(290) = "GHAASBasin290"
7622    list_names(291) = "Gota"
7623    list_names(292) = "Nueces"
7624    list_names(293) = "Stikine"
7625    list_names(294) = "Yalu"
7626    list_names(295) = "Arnaud"
7627    list_names(296) = "GHAASBasin296"
7628    list_names(297) = "Jequitinhonha"
7629    list_names(298) = "Kamchatka"
7630    list_names(299) = "GHAASBasin299"
7631    list_names(300) = "Grijalva"
7632    list_names(301) = "GHAASBasin301"
7633    list_names(302) = "Kemijoki"
7634    list_names(303) = "Olifants"
7635    list_names(304) = "GHAASBasin304"
7636    list_names(305) = "Tsiribihina"
7637    list_names(306) = "Coppermine"
7638    list_names(307) = "GHAASBasin307"
7639    list_names(308) = "GHAASBasin308"
7640    list_names(309) = "Kovda"
7641    list_names(310) = "Trinity"
7642    list_names(311) = "Glama"
7643    list_names(312) = "GHAASBasin312"
7644    list_names(313) = "Luan"
7645    list_names(314) = "Leichhardt"
7646    list_names(315) = "GHAASBasin315"
7647    list_names(316) = "Gurupi"
7648    list_names(317) = "GR Baleine"
7649    list_names(318) = "Aux Feuilles"
7650    list_names(319) = "GHAASBasin319"
7651    list_names(320) = "Weser"
7652    list_names(321) = "GHAASBasin321"
7653    list_names(322) = "GHAASBasin322"
7654    list_names(323) = "Yesil"
7655    list_names(324) = "Incomati"
7656    list_names(325) = "GHAASBasin325"
7657    list_names(326) = "GHAASBasin326"
7658    list_names(327) = "Pungoe"
7659    list_names(328) = "GHAASBasin328"
7660    list_names(329) = "Meuse"
7661    list_names(330) = "Eastmain"
7662    list_names(331) = "Araguari"
7663    list_names(332) = "Hudson"
7664    list_names(333) = "GHAASBasin333"
7665    list_names(334) = "GHAASBasin334"
7666    list_names(335) = "GHAASBasin335"
7667    list_names(336) = "GHAASBasin336"
7668    list_names(337) = "Kobuk"
7669    list_names(338) = "Altamaha"
7670    list_names(339) = "GHAASBasin339"
7671    list_names(340) = "Mand"
7672    list_names(341) = "Santee"
7673    list_names(342) = "GHAASBasin342"
7674    list_names(343) = "GHAASBasin343"
7675    list_names(344) = "GHAASBasin344"
7676    list_names(345) = "Hari"
7677    list_names(346) = "GHAASBasin346"
7678    list_names(347) = "Wami"
7679    list_names(348) = "GHAASBasin348"
7680    list_names(349) = "GHAASBasin349"
7681    !
7682    basin_names(:) = '    '
7683    !
7684    DO i=1,numlar
7685       tmp_str = list_names(i)
7686       basin_names(i) = tmp_str(1:MIN(lenstr,LEN_TRIM(tmp_str)))
7687    ENDDO
7688    !
7689  END SUBROUTINE routing_names
7690  !
7691!! ================================================================================================================================
7692!! SUBROUTINE   : routing_irrigmap
7693!!
7694!>\BRIEF         This  subroutine interpolates the 0.5x0.5 degree based map of irrigated areas to the resolution of the model.
7695!!
7696!! DESCRIPTION (definitions, functional, design, flags) : None
7697!!
7698!! RECENT CHANGE(S): None
7699!!
7700!! MAIN OUTPUT VARIABLE(S):
7701!!
7702!! REFERENCES   : None
7703!!
7704!! FLOWCHART    : None
7705!! \n
7706!_ ================================================================================================================================
7707
7708SUBROUTINE routing_irrigmap (nbpt, index, lalo, neighbours, resolution, contfrac, &
7709       &                       init_irrig, irrigated, init_flood, floodplains, init_swamp, swamp, hist_id, hist2_id)
7710    !
7711    IMPLICIT NONE
7712    !
7713!! PARAMETERS
7714    INTEGER(i_std), PARAMETER                      :: ilake = 1             !! Number of type of lakes area (unitless)
7715    INTEGER(i_std), PARAMETER                      :: idam = 2              !! Number of type of dams area (unitless)
7716    INTEGER(i_std), PARAMETER                      :: iflood = 3            !! Number of type of floodplains area (unitless)
7717    INTEGER(i_std), PARAMETER                      :: iswamp = 4            !! Number of type of swamps area (unitless)
7718    INTEGER(i_std), PARAMETER                      :: isal = 5              !! Number of type of salines area (unitless)
7719    INTEGER(i_std), PARAMETER                      :: ipond = 6             !! Number of type of ponds area (unitless)
7720    INTEGER(i_std), PARAMETER                      :: ntype = 6             !! Number of types of flooded surfaces (unitless)
7721
7722!! INPUT VARIABLES
7723    INTEGER(i_std), INTENT(in)                     :: nbpt                  !! Domain size  (unitless)
7724    INTEGER(i_std), INTENT(in)                     :: index(nbpt)           !! Index on the global map.
7725    REAL(r_std), INTENT(in)                        :: lalo(nbpt,2)          !! Vector of latitude and longitudes (beware of the order !)
7726    INTEGER(i_std), INTENT(in)                     :: neighbours(nbpt,NbNeighb)!! Vector of neighbours for each grid point
7727    REAL(r_std), INTENT(in)                        :: resolution(nbpt,2)    !! The size of each grid box in X and Y (m)
7728    REAL(r_std), INTENT(in)                        :: contfrac(nbpt)        !! Fraction of land in each grid box (unitless;0-1)
7729    INTEGER(i_std), INTENT(in)                     :: hist_id               !! Access to history file (unitless)
7730    INTEGER(i_std), INTENT(in)                     :: hist2_id              !! Access to history file 2 (unitless)
7731    LOGICAL, INTENT(in)                            :: init_irrig            !! Logical to initialize the irrigation (true/false)
7732    LOGICAL, INTENT(in)                            :: init_flood            !! Logical to initialize the floodplains (true/false)
7733    LOGICAL, INTENT(in)                            :: init_swamp            !! Logical to initialize the swamps (true/false)
7734    !
7735!! OUTPUT VARIABLES
7736    REAL(r_std), INTENT(out)                       :: irrigated(:)          !! Irrigated surface in each grid box (m^2)
7737    REAL(r_std), INTENT(out)                       :: floodplains(:)        !! Surface which can be inundated in each grid box (m^2)
7738    REAL(r_std), INTENT(out)                       :: swamp(:)              !! Surface which can be swamp in each grid box (m^2)
7739    !
7740!! LOCAL VARIABLES
7741    ! Interpolation variables
7742    !
7743    INTEGER(i_std)                                 :: nbpmax, nix, njx, fopt !!
7744    CHARACTER(LEN=30)                              :: callsign              !!
7745    REAL(r_std), ALLOCATABLE, DIMENSION(:,:,:)     :: resol_lu              !! Resolution read on the map
7746    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:)    :: mask                  !! Mask to exclude some points (unitless)
7747    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)       :: irrsub_area           !! Area on the fine grid (m^2)
7748    INTEGER(i_std), ALLOCATABLE, DIMENSION(:,:,:)  :: irrsub_index          !! Indices of the points we need on the fine grid (unitless)
7749    INTEGER                                        :: ALLOC_ERR             !!
7750    LOGICAL                                        :: ok_interpol = .FALSE. !! Flag for interpolation (true/false)
7751    !
7752    CHARACTER(LEN=80)                              :: filename              !! Name of the netcdf file (unitless)
7753    INTEGER(i_std)                                 :: iml, jml, lml, tml, fid, ib, ip, jp, itype !! Indices (unitless)
7754    REAL(r_std)                                    :: lev(1), date, dt, coslat !!
7755    INTEGER(i_std)                                 :: itau(1)               !!
7756    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)       :: latrel                !! Latitude
7757    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)       :: lonrel                !! Longitude
7758    REAL(r_std), ALLOCATABLE, DIMENSION(:,:)       :: irrigated_frac        !! Irrigated fraction of the grid box (unitless;0-1)
7759    REAL(r_std), ALLOCATABLE, DIMENSION(:,:,:)     :: flood_fracmax         !! Maximal flooded fraction of the grid box (unitless;0-1)
7760    REAL(r_std)                                    :: area_irrig            !! Irrigated surface in the grid box (m^2)
7761    REAL(r_std)                                    :: area_flood(ntype)     !! Flooded surface in the grid box (m^2)
7762!!$    REAL(r_std)                                :: irrigmap(nbpt)
7763!!$    REAL(r_std)                                :: floodmap(nbpt)
7764!!$    REAL(r_std)                                :: swampmap(nbpt)
7765
7766!_ ================================================================================================================================
7767
7768    !
7769    !Config Key   = IRRIGATION_FILE
7770    !Config Desc  = Name of file which contains the map of irrigated areas
7771    !Config Def   = floodplains.nc
7772    !Config If    = DO_IRRIGATION OR DO_FLOODPLAINS
7773    !Config Help  = The name of the file to be opened to read the field
7774    !Config         with the area in m^2 of the area irrigated within each
7775    !Config         0.5 0.5 deg grid box. The map currently used is the one
7776    !Config         developed by the Center for Environmental Systems Research
7777    !Config         in Kassel (1995).
7778    !Config Units = [FILE]
7779    !
7780    filename = 'floodplains.nc'
7781    CALL getin_p('IRRIGATION_FILE',filename)
7782    !
7783    IF (is_root_prc) THEN
7784       CALL flininfo(filename,iml, jml, lml, tml, fid)
7785       CALL flinclo(fid)
7786    ELSE
7787       iml = 0
7788       jml = 0
7789       lml = 0
7790       tml = 0
7791    ENDIF
7792    !
7793    CALL bcast(iml)
7794    CALL bcast(jml)
7795    CALL bcast(lml)
7796    CALL bcast(tml)
7797    !
7798    !
7799    !
7800    ALLOCATE (latrel(iml,jml), STAT=ALLOC_ERR)
7801    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for latrel','','')
7802
7803    ALLOCATE (lonrel(iml,jml), STAT=ALLOC_ERR)
7804    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for lonrel','','')
7805
7806    ALLOCATE (irrigated_frac(iml,jml), STAT=ALLOC_ERR)
7807    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for irrigated_frac','','')
7808
7809    ALLOCATE (flood_fracmax(iml,jml,ntype), STAT=ALLOC_ERR)
7810    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for flood_fracmax','','')
7811
7812    IF (is_root_prc) CALL flinopen(filename, .FALSE., iml, jml, lml, lonrel, latrel, lev, tml, itau, date, dt, fid)
7813
7814    CALL bcast(lonrel)
7815    CALL bcast(latrel)
7816    !
7817    IF (is_root_prc) CALL flinget(fid, 'irrig', iml, jml, lml, tml, 1, 1, irrigated_frac)
7818    CALL bcast(irrigated_frac)
7819    IF (is_root_prc) CALL flinget(fid, 'lake', iml, jml, lml, tml, 1, 1, flood_fracmax(:,:,ilake))
7820    IF (is_root_prc) CALL flinget(fid, 'dam', iml, jml, lml, tml, 1, 1, flood_fracmax(:,:,idam))
7821    IF (is_root_prc) CALL flinget(fid, 'flood', iml, jml, lml, tml, 1, 1, flood_fracmax(:,:,iflood))
7822    IF (is_root_prc) CALL flinget(fid, 'swamp', iml, jml, lml, tml, 1, 1, flood_fracmax(:,:,iswamp))
7823    IF (is_root_prc) CALL flinget(fid, 'saline', iml, jml, lml, tml, 1, 1, flood_fracmax(:,:,isal))
7824    IF (is_root_prc) CALL flinget(fid, 'pond', iml, jml, lml, tml, 1, 1, flood_fracmax(:,:,ipond))
7825    CALL bcast(flood_fracmax)
7826    !
7827    IF (is_root_prc) CALL flinclo(fid)
7828    !
7829    ! Set to zero all fraction which are less than 0.5%
7830    !
7831    DO ip=1,iml
7832       DO jp=1,jml
7833          !
7834          IF ( irrigated_frac(ip,jp) .LT. undef_sechiba-un) THEN
7835             irrigated_frac(ip,jp) = irrigated_frac(ip,jp)/100.
7836             IF ( irrigated_frac(ip,jp) < 0.005 ) irrigated_frac(ip,jp) = zero
7837          ENDIF
7838          !
7839          DO itype=1,ntype
7840             IF ( flood_fracmax(ip,jp,itype) .LT. undef_sechiba-1.) THEN
7841                flood_fracmax(ip,jp,itype) = flood_fracmax(ip,jp,itype)/100
7842                IF ( flood_fracmax(ip,jp,itype) < 0.005 )  flood_fracmax(ip,jp,itype) = zero
7843             ENDIF
7844          ENDDO
7845          !
7846       ENDDO
7847    ENDDO
7848   
7849    IF (printlev>=2) THEN
7850       WRITE(numout,*) 'lonrel : ', MAXVAL(lonrel), MINVAL(lonrel)
7851       WRITE(numout,*) 'latrel : ', MAXVAL(latrel), MINVAL(latrel)
7852       WRITE(numout,*) 'irrigated_frac : ', MINVAL(irrigated_frac, MASK=irrigated_frac .GT. 0), &
7853            MAXVAL(irrigated_frac, MASK=irrigated_frac .LT. undef_sechiba)
7854       WRITE(numout,*) 'flood_fracmax : ', MINVAL(flood_fracmax, MASK=flood_fracmax .GT. 0), &
7855            MAXVAL(flood_fracmax, MASK=flood_fracmax .LT. undef_sechiba)
7856    END IF
7857
7858    ! Consider all points a priori
7859    !
7860    ALLOCATE(resol_lu(iml,jml,2), STAT=ALLOC_ERR)
7861    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for resol_lu','','')
7862
7863    ALLOCATE(mask(iml,jml), STAT=ALLOC_ERR)
7864    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for mask','','')
7865    mask(:,:) = 0
7866
7867    DO ip=1,iml
7868       DO jp=1,jml
7869          !
7870          ! Exclude the points where we are close to the missing value.
7871          !
7872!MG This condition cannot be applied in floodplains/swamps configuration because
7873!   the same mask would be used for the interpolation of irrigation, floodplains and swamps maps.
7874!          IF ( irrigated_frac(ip,jp) < undef_sechiba ) THEN
7875             mask(ip,jp) = 1
7876!          ENDIF
7877          !
7878          ! Resolution in longitude
7879          !
7880          coslat = MAX( COS( latrel(ip,jp) * pi/180. ), mincos )     
7881          IF ( ip .EQ. 1 ) THEN
7882             resol_lu(ip,jp,1) = ABS( lonrel(ip+1,jp) - lonrel(ip,jp) ) * pi/180. * R_Earth * coslat
7883          ELSEIF ( ip .EQ. iml ) THEN
7884             resol_lu(ip,jp,1) = ABS( lonrel(ip,jp) - lonrel(ip-1,jp) ) * pi/180. * R_Earth * coslat
7885          ELSE
7886             resol_lu(ip,jp,1) = ABS( lonrel(ip+1,jp) - lonrel(ip-1,jp) )/2. * pi/180. * R_Earth * coslat
7887          ENDIF
7888          !
7889          ! Resolution in latitude
7890          !
7891          IF ( jp .EQ. 1 ) THEN
7892             resol_lu(ip,jp,2) = ABS( latrel(ip,jp) - latrel(ip,jp+1) ) * pi/180. * R_Earth
7893          ELSEIF ( jp .EQ. jml ) THEN
7894             resol_lu(ip,jp,2) = ABS( latrel(ip,jp-1) - latrel(ip,jp) ) * pi/180. * R_Earth
7895          ELSE
7896             resol_lu(ip,jp,2) =  ABS( latrel(ip,jp-1) - latrel(ip,jp+1) )/2. * pi/180. * R_Earth
7897          ENDIF
7898          !
7899       ENDDO
7900    ENDDO
7901    !
7902    ! The number of maximum vegetation map points in the GCM grid is estimated.
7903    ! Some lmargin is taken.
7904    !
7905    callsign = 'Irrigation map'
7906    ok_interpol = .FALSE.
7907    IF (is_root_prc) THEN
7908       nix=INT(MAXVAL(resolution_g(:,1))/MAXVAL(resol_lu(:,:,1)))+2
7909       njx=INT(MAXVAL(resolution_g(:,2))/MAXVAL(resol_lu(:,:,2)))+2
7910       nbpmax = nix*njx*2
7911       IF (printlev>=1) THEN
7912          WRITE(numout,*) "Projection arrays for ",callsign," : "
7913          WRITE(numout,*) "nbpmax = ",nbpmax, nix, njx
7914       END IF
7915    ENDIF
7916    CALL bcast(nbpmax)
7917
7918    ALLOCATE(irrsub_index(nbpt, nbpmax, 2), STAT=ALLOC_ERR)
7919    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for irrsub_index','','')
7920    irrsub_index(:,:,:)=0
7921
7922    ALLOCATE(irrsub_area(nbpt, nbpmax), STAT=ALLOC_ERR)
7923    IF (ALLOC_ERR /= 0) CALL ipslerr_p(3,'routing_irrigmap','Pb in allocate for irrsub_area','','')
7924    irrsub_area(:,:)=zero
7925
7926    CALL aggregate_p(nbpt, lalo, neighbours, resolution, contfrac, &
7927         &                iml, jml, lonrel, latrel, mask, callsign, &
7928         &                nbpmax, irrsub_index, irrsub_area, ok_interpol)
7929    !
7930    !
7931    WHERE (irrsub_area < 0) irrsub_area=zero
7932   
7933    ! Test here if not all sub_area are larger than 0 if so, then we need to increase nbpmax
7934    !
7935    DO ib=1,nbpt
7936       !
7937       area_irrig = 0.0
7938       area_flood = 0.0
7939       !
7940       DO fopt=1,COUNT(irrsub_area(ib,:) > zero)
7941          !
7942          ip = irrsub_index(ib, fopt, 1)
7943          jp = irrsub_index(ib, fopt, 2)
7944          !
7945          IF (irrigated_frac(ip,jp) .LT. undef_sechiba-1.) THEN
7946             area_irrig = area_irrig + irrsub_area(ib,fopt)*irrigated_frac(ip,jp)
7947          ENDIF
7948          !
7949          DO itype=1,ntype
7950             IF (flood_fracmax(ip,jp,itype) .LT. undef_sechiba-1.) THEN
7951                area_flood(itype) = area_flood(itype) + irrsub_area(ib,fopt)*flood_fracmax(ip,jp,itype)
7952             ENDIF
7953          ENDDO
7954       ENDDO
7955       !
7956       ! Put the total irrigated and flooded areas in the output variables
7957       !
7958       IF ( init_irrig ) THEN
7959          irrigated(ib) = MIN(area_irrig, resolution(ib,1)*resolution(ib,2)*contfrac(ib))
7960          IF ( irrigated(ib) < 0 ) THEN
7961             WRITE(numout,*) 'We have a problem here : ', irrigated(ib) 
7962             WRITE(numout,*) 'resolution :', resolution(ib,1), resolution(ib,2)
7963             WRITE(numout,*) area_irrig
7964             CALL ipslerr_p(3,'routing_irrigmap','Problem with irrigated...','','')
7965          ENDIF
7966!!$          ! Compute a diagnostic of the map.
7967!!$          IF(contfrac(ib).GT.zero) THEN
7968!!$             irrigmap (ib) = irrigated(ib) / ( resolution(ib,1)*resolution(ib,2)*contfrac(ib) )
7969!!$          ELSE
7970!!$             irrigmap (ib) = zero
7971!!$          ENDIF
7972          !
7973       ENDIF
7974       !
7975       IF ( init_flood ) THEN
7976          floodplains(ib) = MIN(area_flood(iflood)+area_flood(idam)+area_flood(isal), &
7977               & resolution(ib,1)*resolution(ib,2)*contfrac(ib))
7978          IF ( floodplains(ib) < 0 ) THEN
7979             WRITE(numout,*) 'We have a problem here : ', floodplains(ib) 
7980             WRITE(numout,*) 'resolution :', resolution(ib,1), resolution(ib,2)
7981             WRITE(numout,*) area_flood
7982             CALL ipslerr_p(3,'routing_irrigmap','Problem with floodplains..','','')
7983          ENDIF
7984!!$          ! Compute a diagnostic of the map.
7985!!$          IF(contfrac(ib).GT.zero) THEN
7986!!$             floodmap(ib) = floodplains(ib) / ( resolution(ib,1)*resolution(ib,2)*contfrac(ib) )
7987!!$          ELSE
7988!!$             floodmap(ib) = 0.0
7989!!$          ENDIF
7990       ENDIF
7991       !
7992       IF ( init_swamp ) THEN
7993          swamp(ib) = MIN(area_flood(iswamp), resolution(ib,1)*resolution(ib,2)*contfrac(ib))
7994          IF ( swamp(ib) < 0 ) THEN
7995             WRITE(numout,*) 'We have a problem here : ', swamp(ib) 
7996             WRITE(numout,*) 'resolution :', resolution(ib,1), resolution(ib,2)
7997             WRITE(numout,*) area_flood
7998             CALL ipslerr_p(3,'routing_irrigmap','Problem with swamp...','','')
7999          ENDIF
8000!!$          ! Compute a diagnostic of the map.
8001!!$          IF(contfrac(ib).GT.zero) THEN
8002!!$             swampmap(ib) = swamp(ib) / ( resolution(ib,1)*resolution(ib,2)*contfrac(ib) )
8003!!$          ELSE
8004!!$             swampmap(ib) = zero
8005!!$          ENDIF
8006       ENDIF
8007       !
8008       !
8009    ENDDO
8010    !
8011    !
8012   
8013    IF (printlev>=1) THEN
8014       IF ( init_irrig ) WRITE(numout,*) "Diagnostics irrigated :", MINVAL(irrigated), MAXVAL(irrigated)
8015       IF ( init_flood ) WRITE(numout,*) "Diagnostics floodplains :", MINVAL(floodplains), MAXVAL(floodplains)
8016       IF ( init_swamp ) WRITE(numout,*) "Diagnostics swamp :", MINVAL(swamp), MAXVAL(swamp)
8017    END IF
8018
8019! No compensation is done for overlapping floodplains, swamp and irrig. At least overlapping will not
8020! happen between floodplains and swamp alone
8021!    IF ( init_irrig .AND. init_flood ) THEN
8022!       DO ib = 1, nbpt
8023!          surp = (floodplains(ib)+swamp(ib)+irrigated(ib)) / (resolution(ib,1)*resolution(ib,2)*contfrac(ib))
8024!          IF ( surp .GT. un ) THEN
8025!             floodplains(ib) = floodplains(ib) / surp
8026!             swamp(ib) = swamp(ib) / surp
8027!             irrigated(ib) = irrigated(ib) / surp
8028!          ENDIF
8029!       ENDDO
8030!    ENDIF
8031    !
8032    DEALLOCATE (irrsub_area)
8033    DEALLOCATE (irrsub_index)
8034    !
8035    DEALLOCATE (mask)
8036    DEALLOCATE (resol_lu)
8037    !
8038    DEALLOCATE (lonrel)
8039    DEALLOCATE (latrel)
8040    !
8041  END SUBROUTINE routing_irrigmap
8042  !
8043!! ================================================================================================================================
8044!! SUBROUTINE   : routing_waterbal
8045!!
8046!>\BRIEF         This subroutine checks the water balance in the routing module.
8047!!
8048!! DESCRIPTION (definitions, functional, design, flags) : None
8049!!
8050!! RECENT CHANGE(S): None
8051!!
8052!! MAIN OUTPUT VARIABLE(S):
8053!!
8054!! REFERENCES   : None
8055!!
8056!! FLOWCHART    : None
8057!! \n
8058!_ ================================================================================================================================
8059
8060SUBROUTINE routing_waterbal(nbpt, reinit, floodout, runoff, drainage, returnflow, &
8061               & reinfiltration, irrigation, riverflow, coastalflow)
8062    !
8063    IMPLICIT NONE
8064    !
8065!! INPUT VARIABLES
8066    INTEGER(i_std), INTENT(in) :: nbpt                 !! Domain size  (unitless)
8067    LOGICAL, INTENT(in)        :: reinit               !! Controls behaviour (true/false)
8068    REAL(r_std), INTENT(in)    :: floodout(nbpt)       !! Grid-point flow out of floodplains (kg/m^2/dt)
8069    REAL(r_std), INTENT(in)    :: runoff(nbpt)         !! Grid-point runoff (kg/m^2/dt)
8070    REAL(r_std), INTENT(in)    :: drainage(nbpt)       !! Grid-point drainage (kg/m^2/dt)
8071    REAL(r_std), INTENT(in)    :: returnflow(nbpt)     !! The water flow from lakes and swamps which returns to the grid box.
8072                                                       !! This water will go back into the hydrol module to allow re-evaporation (kg/m^2/dt)
8073    REAL(r_std), INTENT(in)    :: reinfiltration(nbpt) !! Water flow from ponds and floodplains which returns to the grid box (kg/m^2/dt)
8074    REAL(r_std), INTENT(in)    :: irrigation(nbpt)     !! Irrigation flux. This is the water taken from the reservoirs and beeing put into the upper layers of the soil (kg/m^2/dt)
8075    REAL(r_std), INTENT(in)    :: riverflow(nbpt)      !! Outflow of the major rivers. The flux will be located on the continental grid but this should be a coastal point (kg/dt)
8076    REAL(r_std), INTENT(in)    :: coastalflow(nbpt)    !! Outflow on coastal points by small basins. This is the water which flows in a disperse way into the ocean (kg/dt)
8077    !
8078    ! We sum-up all the water we have in the warious reservoirs
8079    !
8080    REAL(r_std), SAVE          :: totw_flood           !! Sum of all the water amount in the floodplains reservoirs (kg)
8081!$OMP THREADPRIVATE(totw_flood)
8082    REAL(r_std), SAVE          :: totw_stream          !! Sum of all the water amount in the stream reservoirs (kg)
8083!$OMP THREADPRIVATE(totw_stream)
8084    REAL(r_std), SAVE          :: totw_fast            !! Sum of all the water amount in the fast reservoirs (kg)
8085!$OMP THREADPRIVATE(totw_fast)
8086    REAL(r_std), SAVE          :: totw_slow            !! Sum of all the water amount in the slow reservoirs (kg)
8087!$OMP THREADPRIVATE(totw_slow)
8088    REAL(r_std), SAVE          :: totw_lake            !! Sum of all the water amount in the lake reservoirs (kg)
8089!$OMP THREADPRIVATE(totw_lake)
8090    REAL(r_std), SAVE          :: totw_pond            !! Sum of all the water amount in the pond reservoirs (kg)
8091!$OMP THREADPRIVATE(totw_pond)
8092    REAL(r_std), SAVE          :: totw_in              !! Sum of the water flow in to the routing scheme
8093!$OMP THREADPRIVATE(totw_in)
8094    REAL(r_std), SAVE          :: totw_out             !! Sum of the water flow out to the routing scheme
8095!$OMP THREADPRIVATE(totw_out)
8096    REAL(r_std), SAVE          :: totw_return          !!
8097!$OMP THREADPRIVATE(totw_return)
8098    REAL(r_std), SAVE          :: totw_irrig           !!
8099!$OMP THREADPRIVATE(totw_irrig)
8100    REAL(r_std), SAVE          :: totw_river           !!
8101!$OMP THREADPRIVATE(totw_river)
8102    REAL(r_std), SAVE          :: totw_coastal         !!
8103!$OMP THREADPRIVATE(totw_coastal)
8104    REAL(r_std)                :: totarea              !! Total area of basin (m^2)
8105    REAL(r_std)                :: area                 !! Total area of routing (m^2)
8106    INTEGER(i_std)             :: ig                   !!
8107    !
8108    ! Just to make sure we do not get too large numbers !
8109    !
8110!! PARAMETERS
8111    REAL(r_std), PARAMETER     :: scaling = 1.0E+6     !!
8112    REAL(r_std), PARAMETER     :: allowed_err = 50.    !!
8113
8114!_ ================================================================================================================================
8115    !
8116    IF ( reinit ) THEN
8117       !
8118       totw_flood = zero
8119       totw_stream = zero
8120       totw_fast = zero
8121       totw_slow = zero
8122       totw_lake = zero
8123       totw_pond = zero 
8124       totw_in = zero
8125       !
8126       DO ig=1,nbpt
8127          !
8128          totarea = SUM(routing_area(ig,:))
8129          !
8130          totw_flood = totw_flood + SUM(flood_reservoir(ig,:)/scaling)
8131          totw_stream = totw_stream + SUM(stream_reservoir(ig,:)/scaling)
8132          totw_fast = totw_fast + SUM(fast_reservoir(ig,:)/scaling)
8133          totw_slow = totw_slow + SUM(slow_reservoir(ig,:)/scaling)
8134          totw_lake = totw_lake + lake_reservoir(ig)/scaling
8135          totw_pond = totw_pond + pond_reservoir(ig)/scaling
8136          !
8137          totw_in = totw_in + (runoff(ig)*totarea + drainage(ig)*totarea - floodout(ig)*totarea)/scaling
8138          !
8139       ENDDO
8140       !
8141    ELSE
8142       !
8143       totw_out = zero
8144       totw_return = zero
8145       totw_irrig = zero
8146       totw_river = zero
8147       totw_coastal = zero
8148       area = zero
8149       !
8150       DO ig=1,nbpt
8151          !
8152          totarea = SUM(routing_area(ig,:))
8153          !
8154          totw_flood = totw_flood - SUM(flood_reservoir(ig,:)/scaling)
8155          totw_stream = totw_stream - SUM(stream_reservoir(ig,:)/scaling)
8156          totw_fast = totw_fast - SUM(fast_reservoir(ig,:)/scaling)
8157          totw_slow = totw_slow - SUM(slow_reservoir(ig,:)/scaling)
8158          totw_lake = totw_lake - lake_reservoir(ig)/scaling
8159          totw_pond = totw_pond - pond_reservoir(ig)/scaling
8160          !
8161          totw_return = totw_return + (reinfiltration(ig)+returnflow(ig))*totarea/scaling
8162          totw_irrig = totw_irrig + irrigation(ig)*totarea/scaling
8163          totw_river = totw_river + riverflow(ig)/scaling
8164          totw_coastal = totw_coastal + coastalflow(ig)/scaling
8165          !
8166          area = area + totarea
8167          !
8168       ENDDO
8169       totw_out = totw_return + totw_irrig + totw_river + totw_coastal
8170       !
8171       ! Now we have all the information to balance our water
8172       !
8173       IF ( ABS((totw_flood + totw_stream + totw_fast + totw_slow + totw_lake + totw_pond) - &
8174            & (totw_out - totw_in)) > allowed_err ) THEN
8175          WRITE(numout,*) 'WARNING : Water not conserved in routing. Limit at ', allowed_err, ' 10^6 kg'
8176          WRITE(numout,*) '--Water-- change : flood stream fast ', totw_flood, totw_stream, totw_fast
8177          WRITE(numout,*) '--Water-- change : slow, lake ', totw_slow, totw_lake
8178          WRITE(numout,*) '--Water>>> change in the routing res. : ', totw_flood + totw_stream + totw_fast + totw_slow + totw_lake
8179          WRITE(numout,*) '--Water input : ', totw_in
8180          WRITE(numout,*) '--Water output : ', totw_out
8181          WRITE(numout,*) '--Water output : return, irrig ', totw_return, totw_irrig
8182          WRITE(numout,*) '--Water output : river, coastal ',totw_river, totw_coastal
8183          WRITE(numout,*) '--Water>>> change by fluxes : ', totw_out - totw_in, ' Diff [mm/dt]: ',   &
8184               & ((totw_flood + totw_stream + totw_fast + totw_slow + totw_lake) - (totw_out - totw_in))/area
8185
8186          ! Stop the model
8187          CALL ipslerr_p(3, 'routing_waterbal', 'Water is not conserved in routing.','','')
8188       ENDIF
8189       !
8190    ENDIF
8191    !
8192  END SUBROUTINE routing_waterbal
8193  !
8194  !
8195END MODULE routing
Note: See TracBrowser for help on using the repository browser.