routing_reg.f90 152 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
MODULE routing_reg

  USE defprec
  USE grid
  USE constantes_var
  USE routing_tools

  IMPLICIT NONE

  INTEGER(i_std), SAVE :: nbvmax=440 !! The maximum number of basins we can handle at any time during the generation of the maps (unitless)
  INTEGER(i_std), SAVE :: nbxmax=63 !! The maximum number of points in one direction (NS or WE) using in routing_reg_getgrid (unitless)
  INTEGER(i_std), SAVE :: maxpercent=2 !! The maximum area percentage of a sub-basin in a grib-box (default = 2%)
  INTEGER(i_std), SAVE :: num_largest = 50

  INTEGER(i_std), SAVE :: nbpt_save
  INTEGER(i_std), SAVE :: nbasmax_save

  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: routing_area_glo !! Surface of basin (m^2)
19
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:,:) :: routing_cg_glo !! Centre of gravity of HTU (Lat, Lon)
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: topo_resid_glo !! Topographic index of the retention time (m)
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: route_togrid_glo !! Grid into which the basin flows (unitless)
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: route_tobasin_glo !! Basin in to which the water goes (unitless)
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:) :: route_nbintobas_glo !! Number of basin into current one (unitless)
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:) :: origin_nbintobas_glo !! Number of sub-grid basin into current one before truncation (unitless)
  INTEGER(i_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: global_basinid_glo !! ID of basin (unitless)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:,:) :: route_outlet_glo !! Coordinate of outlet (-)
  REAL(r_std), SAVE, ALLOCATABLE, DIMENSION(:,:) :: route_type_glo !! Coordinate of outlet (-)
  
CONTAINS
!! ================================================================================================================================
!! SUBROUTINE : routing_reg_getgrid
!!
!>\BRIEF This subroutine extracts from the global high resolution fields
!! the data for the current grid box we are dealing with.
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! Convention for trip on the input :
!! The trip field follows the following convention for the flow of the water :
!! trip = 1 : flow = N
!! trip = 2 : flow = NE
!! trip = 3 : flow = E
!! trip = 4 : flow = SE
!! trip = 5 : flow = S
!! trip = 6 : flow = SW
!! trip = 7 : flow = W
!! trip = 8 : flow = NW
!! trip = 97 : return flow into the ground
!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here
!! trip = 99 : river flow into the oceans
!!
!! On output, the grid boxes of the basin map which flow out of the GCM grid are identified
!! by numbers larger than 100 :
!! trip = 101 : flow = N out of the coarse grid
!! trip = 102 : flow = NE out of the coarse grid
!! trip = 103 : flow = E out of the coarse grid
!! trip = 104 : flow = SE out of the coarse grid
!! trip = 105 : flow = S out of the coarse grid
!! trip = 106 : flow = SW out of the coarse grid
!! trip = 107 : flow = W out of the coarse grid
!! trip = 108 : flow = NW out of the coarse grid
!! Inside the grid the convention remains the same as above (ie between 1 and 99).:\n
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES : None
!!
!! FLOWCHART : None
!! \n 
!_ ================================================================================================================================

  SUBROUTINE routing_reg_getgrid(nbpt, ib, sub_pts, sub_index, sub_area, max_basins, min_topoind, &
       & lon_rel, lat_rel, lalo, resolution, contfrac, trip, basins, topoindex, fac, hierarchy, &
       & nbi, nbj, area_bx, trip_bx, basin_bx, topoind_bx, fac_bx, hierarchy_bx, lon_bx, lat_bx, lshead_bx)
    !
    IMPLICIT NONE
    !
!! INPUT VARIABLES
    INTEGER(i_std), INTENT(in) :: nbpt !! Domain size (unitless)
    INTEGER(i_std), INTENT(in) :: ib !! Current basin (unitless)
    INTEGER(i_std), INTENT(in) :: sub_pts(nbpt) !! Number of high resolution points on this grid (unitless)
    INTEGER(i_std), INTENT(in) :: sub_index(nbpt,nbvmax,2) !! Indices of the points we need on the fine grid (unitless)
    REAL(r_std), INTENT(inout) :: max_basins !! The current maximum of basins
    REAL(r_std), INTENT(in) :: min_topoind !! The current minimum of topographic index (m)
    REAL(r_std), INTENT(in) :: sub_area(nbpt,nbvmax) !! Area on the fine grid (m^2)
    !
    REAL(r_std), INTENT(in) :: lon_rel(nbpt,nbvmax) !!
    REAL(r_std), INTENT(in) :: lat_rel(nbpt,nbvmax) !! coordinates of the fine grid
    !
    REAL(r_std), INTENT(in) :: lalo(nbpt,2) !! Vector of latitude and longitudes (beware of the order !)
    REAL(r_std), INTENT(in) :: resolution(nbpt,2) !! The size of each grid box in X and Y (m)
    REAL(r_std), INTENT(in) :: contfrac(nbpt) !! Fraction of land in each grid box (unitless;0-1)
    !
    REAL(r_std), INTENT(inout) :: trip(nbpt,nbvmax) !! The trip field (unitless)
    REAL(r_std), INTENT(inout) :: basins(nbpt,nbvmax) !! data on the fine grid
    REAL(r_std), INTENT(inout) :: topoindex(nbpt,nbvmax) !! Topographic index of the residence time (m)
    REAL(r_std), INTENT(inout) :: hierarchy(nbpt,nbvmax) !! data on the fine grid
    REAL(r_std), INTENT(inout) :: fac(nbpt,nbvmax) !! data on the fine grid
    !
!! OUTPUT VARIABLES
    INTEGER(i_std), INTENT(out) :: nbi, nbj !! Number of point in x and y within the grid (unitless)
    REAL(r_std), INTENT(out) :: area_bx(nbxmax,nbxmax) !! Area of each small box in the grid box (m^2)
    REAL(r_std), INTENT(out) :: hierarchy_bx(nbxmax,nbxmax) !! Level in the basin of the point
    REAL(r_std), INTENT(out) :: fac_bx(nbxmax,nbxmax) !! Flow accumulation
    REAL(r_std), INTENT(out) :: lon_bx(nbxmax,nbxmax) !!
    REAL(r_std), INTENT(out) :: lat_bx(nbxmax,nbxmax) !!
    REAL(r_std), INTENT(out) :: lshead_bx(nbxmax,nbxmax) !! Large scale heading for outflow points.
    REAL(r_std), INTENT(out) :: topoind_bx(nbxmax,nbxmax) !! Topographic index of the residence time for each of the smaller boxes (m)
    INTEGER(i_std), INTENT(out) :: trip_bx(nbxmax,nbxmax) !! The trip field for each of the smaller boxes (unitless)
    INTEGER(i_std), INTENT(out) :: basin_bx(nbxmax,nbxmax) !!
    !
!! LOCAL VARIABLES
    INTEGER(i_std) :: ip, jp, ll(1), iloc, jloc !! Indices (unitless)
    INTEGER(i_std) :: ipp, jpp
    INTEGER(i_std), DIMENSION(8,2) :: inc
    REAL(r_std) :: cenlon, cenlat, dlon, dlat, deslon, deslat, facti, factj
    REAL(r_std) :: lonstr(nbxmax*nbxmax) !!
    REAL(r_std) :: latstr(nbxmax*nbxmax) !!
    !

!_ ================================================================================================================================
    !
    ! The routing code (i=1, j=2)
    !
    inc(1,1) = 0
    inc(1,2) = -1
    inc(2,1) = 1
    inc(2,2) = -1
    inc(3,1) = 1
    inc(3,2) = 0
    inc(4,1) = 1
    inc(4,2) = 1
    inc(5,1) = 0
    inc(5,2) = 1
    inc(6,1) = -1
    inc(6,2) = 1
    inc(7,1) = -1
    inc(7,2) = 0
    inc(8,1) = -1
    inc(8,2) = -1
    !
    ! Set everything to undef to locate easily empty points
    !
    trip_bx(:,:) = undef_int
    basin_bx(:,:) = undef_int
    topoind_bx(:,:) = undef_sechiba
    area_bx(:,:) = undef_sechiba
    hierarchy_bx(:,:) = undef_sechiba
    fac_bx(:,:) = undef_sechiba
    lon_bx(:,:) = undef_sechiba
    lat_bx(:,:) = undef_sechiba
    lshead_bx(:,:) = undef_sechiba
    cenlon = zero
    cenlat = zero
    !
    IF ( sub_pts(ib) > 0 ) THEN
       !
       DO ip=1,sub_pts(ib)
          IF ( ip >nbxmax*nbxmax ) THEN
             CALL ipslerr_p(3,'routing_reg_getgrid','nbxmax too small when filling lonstr',&
                  &           'Please change method to estimate nbxmax','')
          ENDIF
          lonstr(ip) = lon_rel(ib, ip)
          latstr(ip) = lat_rel(ib, ip)
       ENDDO
       !
       ! Get the size of the area and order the coordinates to go from North to South and West to East
       !
       CALL routing_sortcoord(sub_pts(ib), lonstr, 'WE', nbi)
       CALL routing_sortcoord(sub_pts(ib), latstr, 'NS', nbj)
       !
       ! Verify dimension and allocated space
       !
       IF ( nbi > nbxmax .OR. nbj > nbxmax ) THEN
          WRITE(numout,*) "size of area : nbi=",nbi,"nbj=",nbj, "nbxmax=", nbxmax
          CALL ipslerr_p(3,'routing_reg_getgrid','nbxmax too small','Please change method to estimate nbxmax','')
       ENDIF
       !
       ! Transfer the data in such a way that (1,1) is the North Western corner and
       ! (nbi, nbj) the South Eastern.
       !
       DO ip=1,sub_pts(ib)
          ll = MINLOC(ABS(lonstr(1:nbi) - lon_rel(ib, ip)))
          iloc = ll(1)
          ll = MINLOC(ABS(latstr(1:nbj) - lat_rel(ib, ip)))
          jloc = ll(1)
          !
          trip_bx(iloc, jloc) = NINT(trip(ib, ip))
          basin_bx(iloc, jloc) = NINT(basins(ib, ip))
          area_bx(iloc, jloc) = sub_area(ib, ip)
          topoind_bx(iloc, jloc) = topoindex(ib, ip)
          hierarchy_bx(iloc, jloc) = hierarchy(ib, ip)
          fac_bx(iloc, jloc) = fac(ib, ip)
          lon_bx(iloc, jloc) = lon_rel(ib, ip)
          lat_bx(iloc, jloc) = lat_rel(ib, ip)
          cenlon = cenlon + lon_rel(ib, ip)/sub_pts(ib)
          cenlat = cenlat + lat_rel(ib, ip)/sub_pts(ib)
       ENDDO
       !
    ELSE
       !
       ! This is the case where the model invented a continental point
       !
       nbi = 1
       nbj = 1
       iloc = 1
       jloc = 1
       trip_bx(iloc, jloc) = 98
       basin_bx(iloc, jloc) = NINT(max_basins + 1)
       max_basins = max_basins + 1
       area_bx(iloc, jloc) = resolution(ib,1)*resolution(ib,2)*contfrac(ib)
       topoind_bx(iloc, jloc) = min_topoind
       ! Be careful here: We deal with basin_hierarchy(ib,ij) = min_topoind later!
       hierarchy_bx(iloc, jloc) = min_topoind
       fac_bx(iloc, jloc) = zero
       lon_bx(iloc, jloc) = lalo(ib,2)
       lat_bx(iloc, jloc) = lalo(ib,1)
       !
    ENDIF
    !
    ! Tag in trip all the outflow conditions. The table is thus :
    ! trip = 100+n : Outflow into another grid box
    ! trip = 99 : River outflow into the ocean
    ! trip = 98 : This will be coastal flow (not organized as a basin)
    ! trip = 97 : return flow into the soil (local)
    !
    DO jp=1,nbj
       DO ip=1,nbi
          !
          ! Compute the destination of the flow on the high resolution grid (if possible !) to see if it still within the points
          ! belonging to the grid we are working on.
          !
          IF ( trip_bx(ip,jp) < 97 ) THEN
             !
             ipp = ip+inc(trip_bx(ip,jp),1)
             jpp = jp+inc(trip_bx(ip,jp),2)
             !
             ! Check if the indices are outside of the box, then we have a point on the domain border
             !
             IF ( ipp < 1 .OR. ipp > nbi .OR. jpp < 1 .OR. jpp > nbj ) THEN
                IF (routing_nextgrid(ib,trip_bx(ip,jp)) < -1 ) THEN
                   trip_bx(ip,jp) = 98
                ELSE
                   trip_bx(ip,jp) = trip_bx(ip,jp) + 100
                ENDIF
             ELSE
                !
                ! It can also be a border point if the neighbour is not defined
                ! 
                IF ( basin_bx(ipp,jpp) > undef_int-1 ) THEN
                   IF (routing_nextgrid(ib,trip_bx(ip,jp)) < -1 ) THEN
                      trip_bx(ip,jp) = 98
                   ELSE
                      trip_bx(ip,jp) = trip_bx(ip,jp) + 100
                   ENDIF
                ENDIF
             ENDIF
          ELSE IF ( trip_bx(ip,jp) > 100 .AND. trip_bx(ip,jp) < 109 ) THEN
             WRITE(numout,*) 'WARNING : Point flows our of routing.nc file '
             WRITE(numout,*) 'WARNING : Point : basin = ', basin_bx(ip,jp)
             WRITE(numout,*) 'WARNING : Point : coord = ', lon_bx(ip, jp), lat_bx(ip, jp)
             WRITE(numout,*) 'WARNING : Please consider using a larger domaine for the routing.nc file'
             trip_bx(ip,jp) = 98
          ENDIF
          !
       ENDDO
    ENDDO
    !
    ! Compute the large scale flow direction for each outflow point (trip_bx > 100). This
    ! is done by walking into the direction indicated by the small scale trip. The distance of this walk
    ! will depend how far we are from the corner of the polygon. If we are in
    ! the middle of a segment we walk less far than when we are on either corner.
    !
    dlon=ABS(corners_g(ib,NbSegments,1)-corners_g(ib,1,1))
    dlat=ABS(corners_g(ib,NbSegments,2)-corners_g(ib,1,2))
    DO ip=1,NbSegments-1
       dlon = MAX(dlon,ABS(corners_g(ib,ip+1,1)-corners_g(ib,ip,1)))
       dlat = MAX(dlat,ABS(corners_g(ib,ip+1,2)-corners_g(ib,ip,2)))
    ENDDO
    !
    DO jp=1,nbj
       DO ip=1,nbi
          !
          IF ( trip_bx(ip,jp) < undef_int ) THEN
             lshead_bx(ip,jp) = zero
             IF ( trip_bx(ip,jp) > 100 ) THEN
                IF ( nbi > 1 ) THEN
                   facti = REAL(ABS((nbi-1)/2.0-(ip-1)), r_std)/((nbi-1)/2.0)
                ELSE
                   facti = un
                ENDIF
                deslon = lon_bx(ip,jp) + inc(trip_bx(ip,jp)-100,1)*dlon/2.0*facti
                IF ( nbj > 1 ) THEN
                   factj = REAL(ABS((nbj-1)/2.0-(jp-1)), r_std)/((nbj-1)/2.0)
                ELSE
                   factj = un
                ENDIF
                deslat = lat_bx(ip,jp) - inc(trip_bx(ip,jp)-100,2)*dlat/2.0*factj
                lshead_bx(ip,jp) = MOD(haversine_heading(deslon, deslat, cenlon, cenlat)+180.0, 360.0)
             ENDIF
          ENDIF
       ENDDO
    ENDDO
    !
  END SUBROUTINE routing_reg_getgrid
  !
!! ================================================================================================================================
!! SUBROUTINE : routing_reg_findbasins
!!
!>\BRIEF This subroutine finds the basins and does some clean up.
!! The aim is to return the list off all points which are within the
!! same basin of the grid box. This is the faster version of the old routing_reg_findbasins
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!! We will also collect all points which directly flow into the ocean in one basin
!! Make sure that we do not have a basin with two outflows and other exceptions.
!! At this stage no effort is made to come down to the truncation of the model.
!!
!! Convention for trip \n
!! ------------------- \n
!! Inside of the box : \n
!! trip = 1 : flow = N \n
!! trip = 2 : flow = NE \n
!! trip = 3 : flow = E \n
!! trip = 4 : flow = SE \n
!! trip = 5 : flow = S \n
!! trip = 6 : flow = SW \n
!! trip = 7 : flow = W \n
!! trip = 8 : flow = NW \n
!! trip = 97 : return flow into the ground \n
!! trip = 98 : coastal flow (diffuse flow into the oceans) These values are created here \n
!! trip = 99 : river flow into the oceans \n
!!
!! Out flow from the grid : \n
!! trip = 101 : flow = N out of the coarse grid \n
!! trip = 102 : flow = NE out of the coarse grid \n
!! trip = 103 : flow = E out of the coarse grid \n
!! trip = 104 : flow = SE out of the coarse grid \n
!! trip = 105 : flow = S out of the coarse grid \n
!! trip = 106 : flow = SW out of the coarse grid \n
!! trip = 107 : flow = W out of the coarse grid \n
!! trip = 108 : flow = NW out of the coarse grid! \n
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES : None
!!
!! FLOWCHART : None
!! \n
!_ ================================================================================================================================

  SUBROUTINE routing_reg_findbasins(ib, nbi, nbj, trip, basin, fac, hierarchy, topoind, lshead, diaglalo, &
       & nb_basin, basin_inbxid, basin_outlet,  basin_outtp, basin_sz, basin_bxout, basin_bbout, basin_pts, &
       & basin_lshead, coast_pts, lontmp, lattmp)
    !
    IMPLICIT NONE
    !
!! INPUT VARIABLES
    INTEGER(i_std), INTENT(in) :: ib !! 
    INTEGER(i_std), INTENT(in) :: nbi !! Number of point in x within the grid (unitless)
    INTEGER(i_std), INTENT(in) :: nbj !! Number of point in y within the grid (unitless)
    REAL(r_std), INTENT(in) :: hierarchy(:,:) !!
    REAL(r_std), INTENT(in) :: fac(:,:) !!
    REAL(r_std), INTENT(in) :: lshead(:,:)
    REAL(r_std), DIMENSION(:,:), INTENT(in) :: diaglalo !! Point (in Lat/Lon) where diagnostics will be printed.
    !
    ! Modified
    !
    INTEGER(i_std), INTENT(inout) :: trip(:,:) !! The trip field (unitless)
    INTEGER(i_std), INTENT(inout) :: basin(:,:) !!
    REAL(r_std), INTENT(inout) :: topoind(:,:) !! Topographic index of the residence time (m)
    !
    ! For debug and get coordinate of river outlet
    !
    REAL(r_std), INTENT(in) :: lontmp(:,:) !! Longitude
    REAL(r_std), INTENT(in) :: lattmp(:,:) !! Latitude
    !
!! OUTPUT VARIABLES
    INTEGER(i_std), INTENT(out) :: nb_basin               !! Number of sub-basins (unitless)
    INTEGER(i_std), INTENT(out) :: basin_inbxid(nbvmax)   !!
    REAL(r_std), INTENT(out)    :: basin_outlet(nbvmax,2) !!
    REAL(r_std), INTENT(out)    :: basin_outtp(nbvmax)    !!
    INTEGER(i_std), INTENT(out) :: basin_sz(nbvmax)       !!
    INTEGER(i_std), INTENT(out) :: basin_bxout(nbvmax)    !!
    REAL(r_std), INTENT(out)    :: basin_lshead(nbvmax)   !!
    INTEGER(i_std), INTENT(out) :: basin_bbout(nbvmax)    !!
    INTEGER(i_std), INTENT(out) :: basin_pts(nbvmax, nbvmax, 2) !!
    INTEGER(i_std), INTENT(out) :: coast_pts(nbvmax)      !! The coastal flow points (unitless)
    !
!! LOCAL VARIABLES
    LOGICAL, PARAMETER :: debug=.TRUE.
    CHARACTER(LEN=7) :: fmt !!
    CHARACTER(LEN=9) :: fmtr !!
    !
    LOGICAL :: newpoint !! (true/false)
    INTEGER(i_std), DIMENSION(8,2) :: inc !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: outtmp !!
    !
    INTEGER(i_std) :: nbb, p, cnt, ibas !! To count number of subbasin
    INTEGER(i_std) :: il, jl, ill, jll, ij, iz!!
    INTEGER(i_std) :: totsz, checksz !!
    !
    INTEGER(i_std) :: tbname(nbvmax) !!
    INTEGER(i_std) :: tsz(nbvmax) !!
    INTEGER(i_std) :: tpts(nbvmax,nbvmax,2) !!
    INTEGER(i_std) :: toutdir(nbvmax) !!
    INTEGER(i_std) :: toutbas(nbvmax) !!
    INTEGER(i_std) :: toutloc(nbvmax,2) !!
    REAL(r_std) :: tlon(nbvmax) !!
    REAL(r_std) :: tlat(nbvmax) !!
    REAL(r_std) :: touttp(nbvmax) !!
    REAL(r_std) :: toutlshead(nbvmax) !!
    !
    INTEGER(i_std) :: tmpsz(nbvmax) !!
    INTEGER(i_std) :: ip, jp, jpp(1), ipb !!
    INTEGER(i_std) :: ie, je !!
    INTEGER(i_std) :: sortind(nbvmax) !!
    !
    INTEGER(i_std) :: itrans !!
    INTEGER(i_std) :: trans(nbvmax) !!
    !
    INTEGER(i_std) :: new_nb !! Number of sub-basins (unitless)
    INTEGER(i_std) :: mp !! Number of dividing sub-basin in mainstream (unitless)
    INTEGER(i_std) :: new_bname(nbvmax) !!
    INTEGER(i_std) :: new_outdir(nbvmax) !!
    REAL(r_std)    :: new_heading(nbvmax)!!
    INTEGER(i_std) :: new_outbas(nbvmax) !!
    INTEGER(i_std) :: new_outloc(nbvmax,2) !!
    REAL(r_std)    :: new_lon(nbvmax) !!
    REAL(r_std)    :: new_lat(nbvmax) !!
    INTEGER(i_std) :: new_sz(nbvmax) !!
    INTEGER(i_std) :: new_pts(nbvmax, nbvmax, 2) !!
    INTEGER(i_std) :: oldorder, neworder !!
    !
    INTEGER(i_std) :: option !! Option to calculate topoindex

!_ ================================================================================================================================
    !
    IF ( debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "Point: ", ib
       WRITE(numout,*) "Coord:", lalo(ib,2), lalo(ib,1)
       WRITE(numout,*) "Per: ", nbi, nbj
       !
       WRITE(fmt,"('(',I3,'I6)')") nbi
       WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) trip(1:nbi,je)
       ENDDO
    ENDIF
    !
    ! The routing code (i=1, j=2)
    !
    inc(1,1) = 0
    inc(1,2) = -1
    inc(2,1) = 1
    inc(2,2) = -1
    inc(3,1) = 1
    inc(3,2) = 0
    inc(4,1) = 1
    inc(4,2) = 1
    inc(5,1) = 0
    inc(5,2) = 1
    inc(6,1) = -1
    inc(6,2) = 1
    inc(7,1) = -1
    inc(7,2) = 0
    inc(8,1) = -1
    inc(8,2) = -1
    !
    ! 1.0 Find number of outflow point (>= 97)
    ! So basically, we get nb_basin, basin_bxout, basin_inbxid
    ! (with nbb, toutdir, tbname)
    !
    nbb = 0
    tbname(:) = undef_int
    toutdir(:) = 0
    toutloc(:,:) = 0
    outtmp(:,:) = -1
    !
    toutbas(:) = undef_int
    touttp(:) = undef_int
    toutlshead(:) = undef_sechiba
    !
    DO ip=1,nbi
       DO jp=1,nbj
          !
          !
          IF ( basin(ip,jp) .LT. undef_int) THEN
             ! Because, there is maybe difference between undef_int and undef in routing.nc
             !IF ( trip(ip,jp) .GE. 97 .AND. trip(ip,jp) .LT. undef_int ) THEN
             IF ( trip(ip,jp) .GE. 97 .AND. trip(ip,jp) .LT. 109 ) THEN
                nbb = nbb + 1
                IF ( nbb .GT. nbvmax ) CALL ipslerr_p(3,'routing_reg_findbasins','nbvmax too small','first section','')
                tbname(nbb) = basin(ip,jp)
                toutdir(nbb) = trip(ip,jp)-100
                toutlshead(nbb) = lshead(ip,jp)
                touttp(nbb) = trip(ip,jp)
                toutloc(nbb,1) = ip
                toutloc(nbb,2) = jp
                tlat(nbb) = lattmp(ip,jp)
                tlon(nbb) = lontmp(ip,jp)
                outtmp(ip,jp) = nbb
             ENDIF
          ENDIF
       ENDDO
    ENDDO
    !
    ! 2.0 Follow the flow of the water to get size and gather point for each
    ! sub-basin. So we get basin_sz, basin_pts (with tsz, tpts)
    !
    totsz = 0
    tsz(:) = 0
    tpts(:,:,:) = 0
    !
    DO ip=1,nbi
       DO jp=1,nbj
         IF ( basin(ip,jp) .LT. undef_int) THEN
         ! Think about basin .LT. undef_int here
         !IF ( trip(ip,jp) .GT. 0 .AND. trip(ip,jp) .LT. undef_int ) THEN
         IF ( trip(ip,jp) .GT. 0 .AND. trip(ip,jp) .LT. 109 ) THEN
           p = trip(ip,jp)
           cnt = 0
           il = ip ; jl = jp
           newpoint = .TRUE.
           DO WHILE ( p .GT. 0 .AND. p .LT. 9 .AND. cnt .LT. nbi*nbj .AND. newpoint )
              cnt = cnt + 1
              ill = il + inc(p,1)
              jll = jl + inc(p,2)
              il = ill ; jl = jll
              p = trip(il,jl)
              IF ( outtmp(il,jl) .NE. -1 ) newpoint = .FALSE.
           ENDDO
           !
           !
           IF ( cnt .EQ. nbi*nbj) THEN
              IF ( debug ) THEN
                 WRITE(numout,*) "Error: cnt .EQ. nbi*nbj, ib= ",ib
                 WRITE(numout,*) "Point: ", ip, jp
                 WRITE(numout,*) "Per: ", nbi, nbj
                 WRITE(numout,*) "Number of outlet: ", nbb, cnt
                 WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmt,"('(',I3,'I6)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmt) outtmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) trip(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) basin(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lontmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lattmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ HIERARCHY IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) hierarchy(1:nbi,je)
                 ENDDO
                 CALL FLUSH(numout)
              ENDIF
              CALL ipslerr_p(3,'routing_reg_findbasins','We could not route point','','')
           ENDIF
           !
           IF ( outtmp(il,jl) .NE. -1 ) THEN
              ibas = outtmp(il,jl)
              tsz(ibas) = tsz(ibas) + 1
              IF ( tsz(ibas) .GT. nbvmax ) CALL ipslerr_p(3,'routing_reg_findbasins','nbvmax too small','second section','')
              tpts(ibas, tsz(ibas), 1) = ip
              tpts(ibas, tsz(ibas), 2) = jp
              outtmp(ip,jp) = outtmp(il,jl)
           ELSE
              IF ( debug ) THEN
                 WRITE(numout,*) "Error: outtmp(il,jl) .EQ. -1 ", ib
                 WRITE(numout,*) "Point: ", ip, jp
                 WRITE(numout,*) "Per: ", nbi, nbj
                 WRITE(numout,*) "Number of outlet: ", nbb
                 WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmt,"('(',I3,'I6)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmt) outtmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) trip(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN FINDBASINS ++++++++++++++++++++'
                 DO je=1,nbj
                    WRITE(numout,fmt) basin(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lontmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) lattmp(1:nbi,je)
                 ENDDO
                 !
                 WRITE(numout,*) '+++++++++++++++++++ HIERARCHY IN FINDBASINS ++++++++++++++++++++'
                 WRITE(fmtr,"('(',I3,'F8.1)')") nbi
                 DO je=1,nbj
                    WRITE(numout,fmtr) hierarchy(1:nbi,je)
                 ENDDO
              ENDIF
              CALL FLUSH(numout)
              WRITE (numout,*) ' outtmp(il,jl):', outtmp(il,jl)
              WRITE (numout,*) ' trip(il,jl):', trip(il,jl)
              CALL ipslerr_p(3,'routing_reg_findbasins','We could not find right outlet','','')
           ENDIF
           !
           totsz = totsz + 1
         ENDIF
         ! Testing this IF
         ENDIF
       ENDDO
    ENDDO
    !
    IF (  debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "=== To check grid before dividing sub-basin ==="
       WRITE(numout,*) "Number of points: ", nbi, nbj
       WRITE(numout,*) "Number of outlet: ", nbb
       WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmt,"('(',I3,'I6)')") nbi
       DO je=1,nbj
          WRITE(numout,fmt) outtmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) trip(1:nbi,je)
       ENDDO
    ENDIF
    !
    ! 4.0 Use the level 1 of the Pfafstetter coding system to divide the large
    ! sub-grid basin. The large sub-grid basin here is defined by the area 
    ! larger than 9% of grid box area. This threshold should be discussed later.
    !
    ! Make a loop through all sub-grid basins to find if there is big sub-grid basin.
    !
    ! We need at least one subbasin with size greater than 4 (to have at least one
    ! tributary). If you run ORCHIDEE with high resolution, such as 5 km, you
    ! don't need to divide the subbasin too small.
    !
    ! Check if there is still subbasin with area larger than [maxpercent] % of total area
    !
    DO WHILE ( COUNT(tsz(:)/REAL(totsz) >= maxpercent/REAL(100) ) > 0 .AND. COUNT(tsz(:) >= 4 ) > 0 )
       !
       cnt = 0   
       DO ibas = 1, nbb
          ! Only take the subbasin is bigger than 4 points
          IF (( tsz(ibas)/REAL(totsz) .GE. maxpercent/REAL(100) ) .AND. ( tsz(ibas) .GE. 4 )) THEN
             cnt = cnt + 1
             trans(cnt) = ibas
          ENDIF
       ENDDO
       !
       ! cnt should be greater or equal 1 here
       DO ipb = 1, cnt 
          !
          ibas = trans(ipb)
          !
          CALL routing_reg_divbas(nbi, nbj, ibas, toutloc(ibas,1), toutloc(ibas,2), tsz(ibas), toutbas(ibas), toutdir(ibas), & 
             & toutlshead(ibas), tpts, trip, basin, fac, lontmp, lattmp, & 
             & new_nb, mp, new_bname, new_outdir, new_heading, new_outbas, new_lat, new_lon, new_outloc, new_sz, new_pts)
          !
          ! If the dividing step is ok 
          !
          IF ( new_nb .NE. 0 ) THEN
             !
             ! If we have split the basin then we need to change the old one
             !
             tbname(ibas) = new_bname(1)
             toutdir(ibas) = new_outdir(1)
             toutlshead(ibas) = new_heading(1)
             !
             IF ( new_outbas(1) .NE. undef_int ) THEN
                IF ( mp .NE. 1 ) THEN
                   toutbas(ibas) = new_outbas(1)+nbb-1
                ELSE
                   toutbas(ibas) = new_outbas(1)
                ENDIF
             ENDIF
             !
             toutloc(ibas,:) = new_outloc(1,:)
             tlat(ibas) = new_lat(1)
             tlon(ibas) = new_lon(1)
             !
             touttp(ibas) = trip(new_outloc(1,1),new_outloc(1,2))
             !
             tsz(ibas) = new_sz(1)
             tpts(ibas,:,:) = new_pts(1,:,:)
             DO p = 1, tsz(ibas) 
                outtmp(tpts(ibas,p,1),tpts(ibas,p,2)) = ibas
             ENDDO
             !
             !  Add the new sub-grid basins to the end of the list
             !
             IF ( nbb+new_nb-1 .LE. nbvmax) THEN
                DO ip = 2, new_nb
                   tbname(nbb+ip-1) = new_bname(ip)
                   toutdir(nbb+ip-1) = new_outdir(ip)
                   toutlshead(nbb+ip-1) = new_heading(ip)
                   !
                   ! Trung: Should come back here soon (small bug can come from
                   ! Trung: this point)
                   !
                   IF ( new_outbas(ip) .EQ. 1 .AND. ip .NE. mp ) THEN
                      toutbas(nbb+ip-1) = ibas
                   ELSE IF ( ip .NE. mp ) THEN 
                      toutbas(nbb+ip-1) = new_outbas(ip)+nbb-1
                   ELSE
                      toutbas(nbb+ip-1) = new_outbas(ip)
                   ENDIF
                   !
                   toutloc(nbb+ip-1,:) = new_outloc(ip,:)
                   tlat(nbb+ip-1) = new_lat(ip)
                   tlon(nbb+ip-1) = new_lon(ip)
                   !
                   touttp(nbb+ip-1) = trip(new_outloc(ip,1),new_outloc(ip,2))
                   !
                   tsz(nbb+ip-1) = new_sz(ip)
                   tpts(nbb+ip-1,:,:) = new_pts(ip,:,:)
                   DO p = 1, tsz(nbb+ip-1) 
                      outtmp(tpts(nbb+ip-1,p,1),tpts(nbb+ip-1,p,2)) = nbb+ip-1
                   ENDDO
                ENDDO
                nbb = nbb+new_nb-1
             ELSE
                WRITE(numout,*) 'Increase nbvmax. It is too small to contain all the basins (routing_reg_findbasins)'
                CALL ipslerr_p(3,'routing_reg_findbasins','Increase nbvmax.','It is too small to contain all the basins','')
             ENDIF
             !
          ELSE
             !
             ! Print some information if the division failed
             !
             WRITE(numout,*) 'Can not divide sub-basins (routing_reg_findbasins): ',ibas
             CALL ipslerr_p(3,'routing_reg_findbasins','new_nb = 0','Something is wrong with routing_reg_divbas','')
             ! 
          ENDIF
       ENDDO
       !
    ENDDO
    !
    ! 3.0 Gather coastal points
    !
    itrans = 0
    coast_pts(:) = undef_int
    !
    ! Get all the points we can collect (negative value of IDs in routing.nc)
    !
    DO ip=1,nbb
       IF ( tsz(ip) .EQ. 1 .AND. trip(tpts(ip,1,1),tpts(ip,1,2)) .EQ. 98 .AND. tbname(ip) .LT. 0 ) THEN
          itrans = itrans + 1
          trans(itrans) = ip
       ENDIF
    ENDDO
    !
    ! Put everything in the first basin (beware of tbname(trans(1)) can be negative)
    !
    IF ( itrans .GT. 1) THEN
       ipb = trans(1)
       coast_pts(tsz(ipb)) = tbname(ipb)
       tbname(ipb) = -1
       DO ip=2,itrans
          tsz(ipb) = tsz(ipb) + 1
          coast_pts(tsz(ipb)) = tbname(trans(ip))
          tsz(trans(ip)) = 0
          tpts(ipb, tsz(ipb), 1) = tpts(trans(ip), 1, 1)
          tpts(ipb, tsz(ipb), 2) = tpts(trans(ip), 1, 2)
          !
          outtmp(tpts(ipb, tsz(ipb), 1),tpts(ipb, tsz(ipb), 2)) = ipb
       ENDDO
    ENDIF
    !
    ! A.0 To check each grid when testing this subroutine
    !
    IF (  debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "=== To check grid after dividing sub-basin ==="
       WRITE(numout,*) "Number of points: ", nbi, nbj
       WRITE(numout,*) "Number of outlet: ", nbb
       WRITE(numout,*) '+++++++++++++++++++ OUTLET IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmt,"('(',I3,'I6)')") nbi
       DO je=1,nbj
          WRITE(numout,fmt) outtmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ TRIP IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) trip(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN FINDBASINS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) basin(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) lontmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) lattmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ HIERARCHY IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) hierarchy(1:nbi,je)
       ENDDO
       WRITE(numout,*) "=== ====================================== ==="
       !
       WRITE(numout,*) '+++++++++++++++++++ FAC IN FINDBASINS ++++++++++++++++++++'
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       DO je=1,nbj
          WRITE(numout,fmtr) fac(1:nbi,je)
       ENDDO
       WRITE(numout,*) "=== ====================================== ==="
    ENDIF
    !
    ! 5.0 Sort the output by size of the various basins.
    !
    nb_basin = COUNT(tsz(1:nbb) .GT. 0)
    tmpsz(:) = -1
    tmpsz(1:nbb) = tsz(1:nbb)
    DO ip=1,nbb
       jpp = MAXLOC(tmpsz(:))
       IF ( tsz(jpp(1)) .GT. 0) THEN
          sortind(ip) = jpp(1)
          tmpsz(jpp(1)) = -1
       ENDIF
    ENDDO
    basin_inbxid(1:nb_basin) = tbname(sortind(1:nb_basin))
    basin_outlet(1:nb_basin,1) = tlat(sortind(1:nb_basin))
    basin_outlet(1:nb_basin,2) = tlon(sortind(1:nb_basin))
    basin_outtp(1:nb_basin) = touttp(sortind(1:nb_basin))
    basin_sz(1:nb_basin) = tsz(sortind(1:nb_basin))
    basin_pts(1:nb_basin,:,:) = tpts(sortind(1:nb_basin),:,:)
    basin_bxout(1:nb_basin) = toutdir(sortind(1:nb_basin))
    basin_lshead(1:nb_basin) = toutlshead(sortind(1:nb_basin))
    !
    ! Correct toutbas after sorting
    !
    basin_bbout(1:nb_basin) = undef_int
    DO ip = 1, nb_basin
       IF ( toutbas(sortind(ip)) .NE. undef_int ) THEN
          neworder = 0
          oldorder = toutbas(sortind(ip))
          DO ie = 1, nb_basin
             IF ( sortind(ie) .EQ. oldorder ) THEN
                neworder = ie
             ENDIF
          ENDDO
          IF ( neworder .NE. 0 ) THEN
             basin_bbout(ip) = neworder 
          ELSE
             WRITE(numout,*) 'ip, sortind(ip) :', ip, sortind(ip)
             WRITE(numout,*) 'toutbas(sortind(ip)) :', toutbas(sortind(ip))
             WRITE(numout,*) 'Found new order :', neworder
             !
             WRITE(numout,*) 'nb_basin & nbb :', nb_basin, nbb
             WRITE(numout,*) 'sortind(1:nb_basin) :', sortind(1:nb_basin)
             WRITE(numout,*) 'tsz(sortind(1:nb_basin)) :', tsz(sortind(1:nb_basin))
             WRITE(numout,*) 'tsz(1:nbb) :', tsz(1:nbb)
             WRITE(numout,*) 'toutbas(sortind(1:nb_basin)) :', toutbas(sortind(1:nb_basin))
             WRITE(numout,*) 'toutdir(sortind(1:nb_basin)) :', toutdir(sortind(1:nb_basin))
             WRITE(numout,*) 'tbname(sortind(1:nb_basin)) :', tbname(sortind(1:nb_basin))
             WRITE(numout,*) 'toutbas(1:nbb) :', toutbas(1:nbb)
             !
             CALL ipslerr_p(3,'routing_reg_findbasins','We got problem when sorting toutbas','','') 
          ENDIF
       ENDIF
    ENDDO 
    !
    IF (  debug .AND. routing_diagbox(ib, diaglalo) ) THEN
       WRITE(numout,*) "Grid box: ", ib
       WRITE(numout,*) "Number of points: ", nbi, nbj
       WRITE(numout,*) mpi_rank, "=== To check coastal point simplify ==="
       WRITE(numout,*) "Number of outlet: "
       WRITE(numout,*) " + Before gather: ", nbb
       WRITE(numout,*) " + After gather: ", nb_basin
       WRITE(numout,*) mpi_rank, "=== To check dividing sub-basin process ==="
       ip = COUNT(basin_bxout(1:nb_basin) .GE. -3 .AND. basin_bxout(1:nb_basin) .LE. -1 )
       WRITE(numout,*) "Outlet to lake, ocean: ", ip
       ip = COUNT(basin_bxout(1:nb_basin) .GE. 1 .AND. basin_bxout(1:nb_basin) .LE. 8 )
       WRITE(numout,*) "Outlet to other grid box: ", ip
       ip = COUNT(basin_bxout(1:nb_basin) .EQ. -4)
       WRITE(numout,*) "Outlet in the same grid box: ", ip
       ip = COUNT(basin_bbout(1:nb_basin) .NE. undef_int)
       WRITE(numout,*) "Should be the same value as above: ", ip
    ENDIF
    !
    ! 6.0 Make simple verification
    ! What is the size of the region behind each outflow point ?
    ! We can only check if we have at least as many outflows as basins
    !
    checksz = 0
    DO ip=1,nbb
       checksz = checksz + tsz(ip)
    ENDDO
    IF ( checksz .NE. totsz) THEN
       WRITE(numout,*) 'Water got lost while I tried to find basins'
       WRITE(numout,*) checksz, ' /= ', totsz
       CALL ipslerr_p(3,'routing_reg_findbasins','Water got lost while I tried to find basins','','')
    ENDIF
    !
    ip = COUNT(trip(1:nbi,1:nbj) .GE. 97 .AND. trip(1:nbi,1:nbj) .LT. undef_int)
    ip = ip + COUNT(trip(1:nbi,1:nbj) .EQ. -4)
    IF ( ip .LT. nb_basin ) THEN
       WRITE(numout,*) 'We found some coastal point here :', ip
       WRITE(numout,*) 'nb_basin :', nb_basin
       WRITE(numout,*) 'Basin sized :', basin_sz(1:nb_basin)
    ENDIF
    !
    ! 7.0 If we calculate topoindex with option 3
    !     we need to accumulate the topoind_bx along the flow
    !
    ! Get option for calculating topoindex
    !
    !Config Key = TOPOINDEX
    !Config Desc = Options to calculate topoindex
    !Config Def = 3
    !Config Help = This flag allows to calculate topoindex with different options
    !Config Units = [-]
    !
    option = 3
!!$    CALL getin('TOPOINDEX', option)
!!$    !
!!$    ! Checking option: until now (May 2016) there is only 3 acceptable options
!!$    ! = 1 : topoindex .EQ. 1000. everywhere
!!$    ! = 2 : simple average as the method in the older routing scheme
!!$    ! = 3 : accumulate the "topoind" from routing.nc along the flow (as Agnes DUCHARNE's suggestion)
!!$    !
!!$    IF ( option .LT. 1 .OR. option .GT. 3 ) THEN
!!$       WRITE(numout,*) ' You chose wrong option for calculating topoindex: ', option
!!$       WRITE(numout,*) ' It should be: 1, 2 or 3'
!!$       STOP 'routing_reg_globalize'
!!$    ENDIF
    !
    ! Work only using option number 3
    !
    IF ( option .EQ. 3 ) THEN
       ! Loop for all sub-basins and each point belongs to that sub-basin
       DO ij=1,nb_basin
          DO iz=1,basin_sz(ij)
             ! Get the coordinate of this point
             ip = basin_pts(ij,iz,1)
             jp = basin_pts(ij,iz,2)
             ! Start to accumulate "topoind" if this is not a outlet point
             IF ( trip(ip,jp) .GT. 0 .AND. trip(ip,jp) .LT. 97 ) THEN
                p = trip(ip,jp)
                cnt = 0
                il = ip ; jl = jp
                DO WHILE ( p .GT. 0 .AND. p .LT. 9 .AND. cnt .LT. nbi*nbj )
                   cnt = cnt + 1
                   ill = il + inc(p,1)
                   jll = jl + inc(p,2)
                   ! Of course, if you are careful, you will want to check if
                   ! this point still belongs to current sub-basin. Here I
                   ! assume that the sub-routine routing_reg_divbas worked well.
                   ! So we don't need to check.
                   topoind(basin_pts(ij,iz,1),basin_pts(ij,iz,2))=topoind(basin_pts(ij,iz,1),basin_pts(ij,iz,2))+topoind(ill,jll)
                   !
                   il = ill ; jl = jll
                   p = trip(il,jl)
                ENDDO
             ENDIF
             !
          ENDDO
       ENDDO
    ENDIF
    !
  END SUBROUTINE routing_reg_findbasins
  !
!! ================================================================================================================================
!! SUBROUTINE : routing_reg_divbas
!!
!>\BRIEF This subroutine divide the large sub-grid basins to smaller ones. It is
!! based on The Pfafstetter Coding System for Watershed Identification. You can
!! find information here (for example):
!! http://ponce.sdsu.edu/pfafstetter_system_revised_presentation.html
!!
!! DESCRIPTION (definitions, functional, design, flags) :
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!!
!! REFERENCES : None
!!
!! FLOWCHART : None
!! \n
!_ ================================================================================================================================

  SUBROUTINE routing_reg_divbas(nbi, nbj, ibas, iloc, jloc, tsz, tout, toutd, headd, &
                & tpts, trip, basin, fac, lon, lat,      &
                & new_nb, oic, new_bname, new_outdir, new_head, new_outbas, new_lat, new_lon, new_outloc, new_sz, new_pts)
    !
    IMPLICIT NONE
    !
!! INPUT VARIABLES
    INTEGER(i_std), INTENT(in) :: nbi !! Number of point in x within the grid (unitless)
    INTEGER(i_std), INTENT(in) :: nbj !! Number of point in y within the grid (unitless)
    INTEGER(i_std), INTENT(in) :: ibas !! Order of the basin will be divided 
    INTEGER(i_std), INTENT(in) :: iloc, jloc !! Outlet location
    !
    INTEGER(i_std), INTENT(in) :: tsz !! Size of sub-basin
    INTEGER(i_std), INTENT(in) :: tout !! Outlet type
    INTEGER(i_std), INTENT(in) :: toutd !! Outlet direction
    REAL(r_std), INTENT(in)    :: headd
    INTEGER(i_std), INTENT(in) :: tpts(:,:,:) !!
    INTEGER(i_std), INTENT(in) :: basin(:,:) !!
    REAL(r_std), INTENT(in) :: fac(:,:) !!
    REAL(r_std), INTENT(in) :: lon(:,:), lat(:,:) !!
    !
!! MODIFIED VARIABLES
    INTEGER(i_std), INTENT(inout) :: trip(:,:) !!
    !
!! OUTPUT VARIABLES
    INTEGER(i_std), INTENT(out) :: new_nb !! Number of sub-basins (unitless)
    INTEGER(i_std), INTENT(out) :: oic
    INTEGER(i_std), INTENT(out) :: new_bname(nbvmax) !!
    INTEGER(i_std), INTENT(out) :: new_outdir(nbvmax) !!
    REAL(r_std), INTENT(out)    :: new_head(nbvmax) !!
    INTEGER(i_std), INTENT(out) :: new_outbas(nbvmax) !!
    INTEGER(i_std), INTENT(out) :: new_outloc(nbvmax,2) !!
    REAL(r_std), INTENT(out) :: new_lon(nbvmax) !!
    REAL(r_std), INTENT(out) :: new_lat(nbvmax) !!
    INTEGER(i_std), INTENT(out) :: new_sz(nbvmax) !!
    INTEGER(i_std), INTENT(out) :: new_pts(nbvmax, nbvmax, 2) !!
    !
!! LOCAL VARIABLES
    REAL(r_std), PARAMETER :: flag=-9999. !!
    LOGICAL, PARAMETER :: debug=.FALSE.
    LOGICAL, PARAMETER :: checkgrid=.FALSE.
    CHARACTER(LEN=7) :: fmt !!
    CHARACTER(LEN=9) :: fmtr !!
    CHARACTER(LEN=11) :: afmt !!
    CHARACTER(LEN=13) :: afmtr !!
    !
    !
    REAL(r_std), DIMENSION(nbi,nbj) :: factmp !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: triptmp !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: triptemp !!
    INTEGER(i_std), DIMENSION(nbi,nbj) :: basintmp !!
    REAL(r_std), DIMENSION(nbi,nbj) :: lontmp, lattmp !!
    !
    INTEGER(i_std) :: il, jl, ill, jll !!
    INTEGER(i_std) :: ie, je !!
    INTEGER(i_std) :: p, cnt, k, l, ic, ik !!
    INTEGER(i_std) :: ip, isz, checksz !!
    INTEGER(i_std) :: ff(1) !!
    !
    LOGICAL :: okpoint=.TRUE.
    !
    ! Number of neighbours on the HydroShed grid (regular Lat/Lon)
    !
    INTEGER(i_std), PARAMETER :: nbne=8
    INTEGER(i_std), DIMENSION(nbne,2) :: inc !!
    !
    ! Explanation for dimension of below arrays:
    !
    ! + Firstly, I suggest that you should read about the Pfafstetter Coding
    ! System, here for example:
    ! http://ponce.sdsu.edu/pfafstetter_system_revised_presentation.html
    !
    !    * Note: It will be easier if you keep in mind that the original
    !    information given in grid box of nbi*nbj. But here, to deal with main
    !    stem and tributaries, I need to store them to cnt*nbne (exactly,
    !    cnt*[nbne-2]). Where, cnt is the length of main stem and nbne is number
    !    of neighbour points, and usually 2 neighbour points will belongs to
    !    main stem.
    !
    ! + You will see steps for coding the sub-basin are:
    !
    !    - From the sub-basin outlet, trace upstream along the main stem of the
    !    river, and get the tributaries. To store location and flow accumulation
    !    of points belongs to main stream and tributaries:
    !
    INTEGER(i_std) :: main_loc(nbvmax,2), tri_loc(nbne,nbvmax,2)
    REAL(r_std) :: main_fac(nbvmax), tri_fac(nbne,nbvmax)
    REAL(r_std) :: tmptri_fac(nbne)  ! Flow accumulation of all neighbour points 
    INTEGER(i_std) :: sortedtrifac(nbne) ! And sort of tmptri_fac(nbne)
    REAL(r_std) :: alltri_fac(nbvmax) ! Sort flow accumulation of all tributaries
    INTEGER(i_std) :: alltri_loc1(nbvmax), alltri_loc2(nbvmax) ! And their location
    INTEGER(i_std) :: sortedallfac(nbvmax) ! Sort alltri_fac(nbvmax) 
    ! 
    !     *  Note: again, there are few dimensions should be exactly [nbne-1]
    !     or [nbne-2]. Because when you follow upstream the mainstream, there are
    !     always at least ONE neighbour points will not belong to TRIBUTARY.
    !     But to make your life easier, I put all "nbne" here.
    !
    !    - Identify the 4 greatest tributaries:
    ! 
    REAL(r_std) :: tmpmain_fac(4) ! Flow accumulations of 4 greatest tributaries
    INTEGER(i_std) :: tmpmain_loc(4,2), sortedmainfac(4) ! And their locations and sorted values
    INTEGER(i_std) :: numtri(4), usetri_loc(4,4,2) ! Counting and store location when processing these 4 points
    !
    !    - Inter-basins are the watersheds that contribute flow to the main
    !    stem: there can be 5 inter-basins. So we need 9 dividing points:
    !
    INTEGER(i_std) :: divloc(9,2) ! Location of dividing points (maximum is 9)
    ! 

!_ ================================================================================================================================

    !
    ! The routing code (i=1, j=2)
    !
    inc(1,1) = 0
    inc(1,2) = -1
    inc(2,1) = 1
    inc(2,2) = -1
    inc(3,1) = 1
    inc(3,2) = 0
    inc(4,1) = 1
    inc(4,2) = 1
    inc(5,1) = 0
    inc(5,2) = 1
    inc(6,1) = -1
    inc(6,2) = 1
    inc(7,1) = -1
    inc(7,2) = 0
    inc(8,1) = -1
    inc(8,2) = -1
    !
    ! 0.0 Get the information of all the points belongs to the subbasin
    ! which need to divide. Flag for flow accumulation is -9999 (the value of
    ! flow accumulation should be always non negative).
    !
    factmp(:,:) = flag
    basintmp(:,:) = 0
    lontmp(:,:) = 0
    lattmp(:,:) = 0
    triptmp(:,:) = -1
    triptemp(:,:) = -1
    !
    DO isz = 1, tsz
       il = tpts(ibas, isz, 1)
       jl = tpts(ibas, isz, 2)
       !
       factmp(il,jl) = fac(il,jl)
       triptmp(il,jl) = trip(il,jl)
       triptemp(il,jl) = trip(il,jl)
       basintmp(il,jl) = basin(il,jl)
       lontmp(il,jl) = lon(il,jl)
       lattmp(il,jl) = lat(il,jl)
    ENDDO
    !
    ! Print out information of grid box
    !
    IF ( checkgrid ) THEN
       ! 
       WRITE(numout,*) " Routing_reg_divbas: Grid before dividing "
       WRITE(numout,*) " Size: ", nbi, nbj
       WRITE(fmt,"('(',I3,'I6)')") nbi
       WRITE(fmtr,"('(',I3,'F8.1)')") nbi
       !
       WRITE(numout,*) '+++++++++++++++++++ TRIP IN DIVBAS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) triptmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN DIVBAS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmt) basintmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN DIVBAS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmtr) lontmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN DIVBAS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmtr) lattmp(1:nbi,je)
       ENDDO
       !
       WRITE(numout,*) '+++++++++++++++++++ FAC IN DIVBAS ++++++++++++++++++++'
       DO je=1,nbj
          WRITE(numout,fmtr) factmp(1:nbi,je)
       ENDDO
       CALL FLUSH(numout)
    ENDIF
    !
    ! 1.0 If the first version of this subroutine doesn't work well,
    ! we need to write the validation step of input arrays here (for
    ! example, the input sub-basin should only has 1 outlet).
    ! (October 2016: it still works well :))
    !
    IF ( triptmp(iloc,jloc) .LT. -4 .OR. triptmp(iloc,jloc) .GE. 109 ) THEN
       CALL ipslerr_p(3,'routing_reg_divbas','The TRIP of outlet is wrong','','')
    ENDIF
    IF ( debug ) THEN
       WRITE(numout,*) 'Basin number: ', ibas
       WRITE(numout,*) 'Basin size: ', tsz
       WRITE(numout,*) 'Basin out: ', tout, toutd
    ENDIF
    !
    ! 2.0 From the outlet of the subbasin, trace back to find the main stream 
    ! and identify the 4 greatest tributaries. If there are less than 4
    ! tributraries, take them all.
    !
    ! Trace back upstream from the outlet of the sub-basin
    ! and define the mainstream and all tributaries
    !
    main_loc(:,:) = 0
    main_fac(:) = flag
    tri_loc(:,:,:) = 0
    tri_fac(:,:) = flag
    !
    ! Start!
    !
    cnt = 0
    okpoint = .TRUE.
    il = iloc ; jl = jloc
    DO WHILE ( il .GT. 0 .AND. il .LE. nbi .AND. jl .GT. 0 .AND. jl .LE. nbj &
             & .AND. cnt .LT. nbi*nbj .AND. okpoint )
       !
       ! Count the length of the mainstream
       !
       cnt = cnt + 1
       main_loc(cnt,1) = il
       main_loc(cnt,2) = jl
       main_fac(cnt) = factmp(il,jl)
       !
       ! Look for [nbne] neighbour points to find the tributaries
       ! October 2016: so far, nbne = 8 (for 8 directions of TRIP)
       !
       l = 0
       DO k = 1, nbne
          ill = il + inc(k,1)
          jll = jl + inc(k,2)
          ! If this point is still in the grid box
          IF ( ill .GT. 0 .AND. ill .LE. nbi .AND. jll .GT. 0 .AND. jll .LE. nbj ) THEN
             ! If this point still belongs to the current sub-basin
             IF ( triptmp(ill,jll) .GT. 0 .AND. triptmp(ill,jll) .LE. nbne ) THEN
                ie = ill + inc(INT(triptmp(ill,jll)),1)
                je = jll + inc(INT(triptmp(ill,jll)),2)
                ! If this neighbour point contributes water for current point
                IF ( ie .EQ. il .AND. je .EQ. jl ) THEN
                   ! Store all points here
                   l = l + 1
                   tri_fac(l,cnt) = factmp(ill,jll) 
                   tri_loc(l,cnt,1) = ill
                   tri_loc(l,cnt,2) = jll
                   ! Mark the processed points here
                   triptmp(ill,jll) = -2
                ENDIF
             ENDIF
          ENDIF
       ENDDO
       !
       ! Only go further if we have found tributaries (there is still neighbour
       ! point flows into the current point)
       !
       IF ( l > 0 ) THEN
          !
          ! Sort the FAC of all neighbour points
          tmptri_fac(:) = flag
          sortedtrifac(:) = 0
          !
          tmptri_fac(:) = tri_fac(:,cnt)
          DO k = 1, l
             ff = MAXLOC(tmptri_fac)
             sortedtrifac(k) = ff(1)
             tmptri_fac(ff(1)) = flag
          ENDDO
          ! Continue trace upstream: the neighbour point with highest flow
          ! accumulation will belongs to main stream. We move to this point
          ! (change value of il, jl).
          IF ( tri_fac(sortedtrifac(1),cnt) .NE. flag ) THEN
             il = tri_loc(sortedtrifac(1),cnt,1)       
             jl = tri_loc(sortedtrifac(1),cnt,2)
             !
             IF ( checkgrid ) THEN
                WRITE(numout,*) "cnt = ", cnt, " fac = ", tri_fac(sortedtrifac(1),cnt)
             ENDIF
             !
             tri_fac(sortedtrifac(1),cnt) = flag
          ELSE
             okpoint = .FALSE.
          ENDIF
       ELSE
          okpoint = .FALSE.
       ENDIF
       !
       IF ( cnt .EQ. nbi*nbj) THEN
          IF ( debug ) THEN
             WRITE(numout,*) "Error: cnt .EQ. nbi*nbj "
             WRITE(numout,*) "Point: ", il, jl
             WRITE(numout,*) "Per: ", nbi, nbj
             WRITE(fmt,"('(',I3,'I6)')") nbi
             WRITE(fmtr,"('(',I3,'F8.1)')") nbi
             !
             WRITE(numout,*) '+++++++++++++++++++ TRIP IN DIVBAS ++++++++++++++++++++'
             DO je=1,nbj
                WRITE(numout,fmt) triptemp(1:nbi,je)
             ENDDO
             !
             WRITE(numout,*) '+++++++++++++++++++ BASIN IDs IN DIVBAS ++++++++++++++++++++'
             DO je=1,nbj
                WRITE(numout,fmt) basintmp(1:nbi,je)
             ENDDO
             !
             WRITE(numout,*) '+++++++++++++++++++ LONGITUDE IN DIVBAS ++++++++++++++++++++'
             DO je=1,nbj
                WRITE(numout,fmtr) lontmp(1:nbi,je)
             ENDDO
             !
             WRITE(numout,*) '+++++++++++++++++++ LATITUDE IN DIVBAS ++++++++++++++++++++'
             DO je=1,nbj
                WRITE(numout,fmtr) lattmp(1:nbi,je)
             ENDDO
             !
             WRITE(numout,*) '+++++++++++++++++++ FAC IN DIVBAS ++++++++++++++++++++'
             DO je=1,nbj
                WRITE(numout,fmtr) factmp(1:nbi,je)
             ENDDO
             CALL FLUSH(numout)
          ENDIF
          CALL ipslerr_p(3,'routing_reg_divbas','We could not route point','','')
       ENDIF
       !
    ENDDO
    IF ( debug ) WRITE (numout,*) 'Length of mainstream: ', cnt
    !
    ! 3.0 Sort the flow accumulation of the tributaries and find the 
    ! divided location.
    !
    alltri_fac(:) = flag
    alltri_loc1(:) = 0
    alltri_loc2(:) = 0
    divloc(:,:) = 0
    !
    ip = 0
    DO k = 1, cnt
       ! Actually, we should only DO l = 1, nbne-2
       ! Because, there are usually 2 neighbour points belong to main stream
       ! and maximum (nbne-2) neighbour points can be tributaries.
       ! DO l = 1, nbne-2 
       DO l = 1, nbne
          IF ( tri_fac(l,k) .NE. flag ) THEN
             ip = ip + 1
             alltri_fac(ip) = tri_fac(l,k)
             ! Attention: here we store location of each tributary in main stream
             ! ( k <= cnt ) and its direction compared with main stream ( l <= nbne )
             alltri_loc1(ip) = k
             alltri_loc2(ip) = l
          ENDIF
       ENDDO
    ENDDO
    IF ( debug ) WRITE (numout,*) 'Number of tributaries: ', ip
    ! If we have at least one tributary
    IF ( ip .GT. 0 ) THEN
       ! Original output
       oic = 0
       ! 
       sortedallfac(:) = 0
       DO k = 1, ip
          ff = MAXLOC(alltri_fac)
          sortedallfac(k) = ff(1)
          alltri_fac(ff(1)) = flag
       ENDDO
       ! Get the points in the mainstream
       tmpmain_fac(:) = flag
       tmpmain_loc(:,:) = 0
       numtri(:) = 0
       usetri_loc(:,:,:) = 0
       ! Using l to count the actual number of points in main stream need to use
       ! for dividing (not always equal 4 as ideal case).
       l = 0
       ! According to Pfafstetter coding, we only look for 4 greatest
       ! tributaries:
       DO k = 1, 4
          !
          IF ( sortedallfac(k) .NE. 0 ) THEN
             !
             ik = alltri_loc1(sortedallfac(k))
             il = alltri_loc2(sortedallfac(k))
             ! Starting store location and flow accumulation of points in main stream:
             IF ( COUNT ( tmpmain_fac(:) .EQ. main_fac(ik) ) .EQ. 0 ) THEN
                l = l + 1
                tmpmain_loc(l,1) = main_loc(ik,1)
                tmpmain_loc(l,2) = main_loc(ik,2)
                tmpmain_fac(l) = main_fac(ik)
                !
                numtri(l) = 1
                usetri_loc(numtri(l),l,1) = tri_loc(il,ik,1) 
                usetri_loc(numtri(l),l,2) = tri_loc(il,ik,2)
                !
             ELSE
                ! If this point in main stream have more than 1 tributary
                ! belongs to top 4 greatest tributaries
                numtri(l) = numtri(l) + 1
                usetri_loc(numtri(l),l,1) = tri_loc(il,ik,1) 
                usetri_loc(numtri(l),l,2) = tri_loc(il,ik,2)
                !
             ENDIF
          ENDIF
       ENDDO
       ! Sort the mainstream points
       sortedmainfac(:) = 0
       DO k = 1, l
          ff = MAXLOC(tmpmain_fac)
          sortedmainfac(k) = ff(1)
          tmpmain_fac(ff(1)) = flag
       ENDDO
       !
       ic = 0
       DO k = l, 1, -1
          IF ( tmpmain_loc(sortedmainfac(k),1) .NE. 0 ) THEN
             ic = ic + 1
             divloc(ic,1) = tmpmain_loc(sortedmainfac(k),1)
             divloc(ic,2) = tmpmain_loc(sortedmainfac(k),2)
             !
             new_outbas(ic) = ic + 1
             !
          ENDIF
       ENDDO
       ! If the last divide point is not the original outlet
       IF ( divloc(ic,1) .NE. iloc .OR. divloc(ic,2) .NE. jloc ) THEN
          ic = ic + 1
          divloc(ic,1) = iloc
          divloc(ic,2) = jloc
       ENDIF
       !
       new_outbas(ic) = tout
       ! Number of mainstream sub-basin
       oic = ic 
       !
       DO k = l, 1, -1
          !
          !DO il = 1, nbne-2
          ! Maximum 4 tributaries: 
          DO il = 1, 4
             IF ( usetri_loc(il,sortedmainfac(k),1) .NE. 0 ) THEN
                ic = ic + 1
                divloc(ic,1) = usetri_loc(il,sortedmainfac(k),1)
                divloc(ic,2) = usetri_loc(il,sortedmainfac(k),2)
                !
                !new_outbas(ic) = new_outbas(l-k+1)
                new_outbas(ic) = l-k+1
                !
             ENDIF
          ENDDO
       ENDDO
       ! Save number of dividing points
       l = ic
       !       
    ! If we don't have any tributary
    ELSE
       oic = 2
       l = 2
       cnt = cnt/2 + 1
       divloc(1,1) = main_loc(cnt,1)
       divloc(1,2) = main_loc(cnt,2)
       divloc(2,1) = iloc
       divloc(2,2) = jloc
       !
       new_outbas(1) = 2
       new_outbas(2) = tout
       !
    ENDIF
    IF ( debug ) WRITE (numout,*) 'Number of new sub-basin: ', l, oic
    !
    ! Now, cut it ! Cut the sub-basin ! Release The Kraken !
    !
    new_nb = l
    !
    DO ik = 1, l
       ! A small trick here
       IF ( oic .EQ. 2 .AND. l .EQ. 2 ) THEN
          k = ik
       ELSE
          IF ( ik .LE. (l - oic) ) THEN
             k = ik + oic 
          ELSE
             k = ik - (l - oic)
          ENDIF
       ENDIF
       ! I'm so stupid careful here with this IF
       IF ( divloc(k,1) .NE. 0 .AND. divloc(k,2) .NE. 0 ) THEN
          !
          new_sz(k) = 1 
          new_pts(k,new_sz(k),1) = divloc(k,1) 
          new_pts(k,new_sz(k),2) = divloc(k,2)
          !
          new_bname(k) = basin(divloc(k,1),divloc(k,2))
          new_outloc(k,1) = divloc(k,1)
          new_outloc(k,2) = divloc(k,2)
          new_lon(k) = lon(divloc(k,1),divloc(k,2))
          new_lat(k) = lat(divloc(k,1),divloc(k,2))
          !
          ! Change the TRIP here for routing_reg_globalize (don't change the
          ! original outlet before dividing). Change new_outdir for
          ! routing_reg_linkup.
          !
          IF ( k .NE. oic ) THEN
             trip(divloc(k,1), divloc(k,2)) = -4
             new_outdir(k) = -4
             new_head(k) = undef_sechiba
          ELSE
             new_outdir(k) = toutd
             new_head(k) = headd
          ENDIF
          !
          !
          triptemp(divloc(k,1), divloc(k,2)) = -1
          !   
          DO isz = 1, tsz
             il = tpts(ibas, isz, 1)
             jl = tpts(ibas, isz, 2)
             IF ( triptemp(il,jl) .GT. 0 .AND. triptemp(il,jl) .LT. 9 ) THEN
                p = triptemp(il,jl)
                cnt = 0
                ie = il ; je = jl
                okpoint = .TRUE.
                DO WHILE ( p .GT. 0 .AND. p .LT. 9 .AND. cnt .LT. nbi*nbj .AND. okpoint )
                   cnt = cnt + 1
                   ill = ie + inc(p,1)
                   jll = je + inc(p,2)
                   ie = ill ; je = jll
                   p = trip(ie,je)
                   IF ( ie .EQ. divloc(k,1) .AND. je .EQ. divloc(k,2) ) THEN
                      okpoint = .FALSE.
                      new_sz(k) = new_sz(k) + 1 
                      new_pts(k,new_sz(k),1) = il 
                      new_pts(k,new_sz(k),2) = jl
                      triptemp(tpts(ibas, isz, 1), tpts(ibas, isz, 2)) = -1
                   ENDIF
                ENDDO
             ENDIF
          ENDDO   
       ENDIF
    ENDDO 
    !
    ! 4.0 Make simple verification
    !
    IF ( new_nb .GE. 0 ) THEN
       checksz = 0
       DO ip=1,new_nb
          checksz = checksz + new_sz(ip)
       ENDDO
       !  
       IF ( checksz .NE. tsz) THEN
          WRITE(numout,*) ' Water got lost while I tried to divide basins'
          WRITE(numout,*) ' Number of new sub-basin : ', new_nb
          ip = COUNT(divloc(:,1) .NE. 0)
          WRITE(numout,*) ' Number of mainstrem sub-basin : ', oic
          WRITE(numout,*) ' Number of tributaries : ', ip - oic
          WRITE(numout,*) checksz, ' /= ', tsz
          !
          WRITE(afmt,"('(A10,', I3,'I6)')") ip
          WRITE(afmtr,"('(A10,', I3,'F8.1)')") ip
          !
          WRITE(numout,afmt) 'new_sz = ', new_sz(1:ip)
          WRITE(numout,*) 'new_sz(oic) = ', new_sz(oic)
          WRITE(numout,afmt) 'new_bname', new_bname(1:ip)
          WRITE(numout,afmt) 'new_outdir', new_outdir(1:ip)
          WRITE(numout,afmt) 'new_outbas', new_outbas(1:ip)
          WRITE(numout,afmt) 'new_outloc1', new_outloc(1:ip,1)
          WRITE(numout,afmt) 'new_outloc2', new_outloc(1:ip,2)
          WRITE(numout,afmtr) 'new_lon', new_lon(1:ip)
          WRITE(numout,afmtr) 'new_lat', new_lat(1:ip)
          !
          ip = COUNT(triptemp(1:nbi,1:nbj) .EQ. -1)
          WRITE(numout,*) 'Unprocessed points :', nbi*nbj-ip
          !
          WRITE(fmt,"('(',I3,'I6)')") nbi
          WRITE(fmtr,"('(',I3,'F8.1)')") nbi
          !
          WRITE(numout,*) '+++++++++++++++++++ TRIP IN DIVBAS ++++++++++++++++++++'
          DO je=1,nbj
             WRITE(numout,fmt) triptemp(1:nbi,je)
          ENDDO
          !
          CALL ipslerr_p(3,'routing_reg_divbas','Water got lost while I tried to divide sub-basins','','')
       ENDIF
    ENDIF
    !
    ip = COUNT(triptemp(1:nbi,1:nbj) .EQ. -1)
    IF ( ip .NE. nbi*nbj ) THEN
       WRITE(*,*) 'Unprocessed points :', nbi*nbj-ip
    ENDIF
    !
  END SUBROUTINE routing_reg_divbas
  !
!
!! ================================================================================================================================
!! SUBROUTINE : routing_reg_globalize
!!
!>\BRIEF This subroutine puts the basins found for grid box in the global map.
!! Connection can only be made later when all information is together.
!!
!! DESCRIPTION (definitions, functional, design, flags) : None
!!
!! RECENT CHANGE(S): None
!!
!! MAIN OUTPUT VARIABLE(S):
!! One of the outputs is basin_flowdir. Its convention is 1-8 for the directions from North to North
!! West going through South. The negative values will be -3 for return flow, -2 for coastal flow
!!
!! REFERENCES : None
!!
!! FLOWCHART : None 
!! \n
!_ ================================================================================================================================

1637
SUBROUTINE routing_reg_globalize(nbpt, ib, neighbours, area_bx, lon_bx, lat_bx, trip_bx, hierarchy_bx, fac_bx, topoind_bx, &
1638
       & min_topoind, nb_basin, basin_inbxid, basin_outlet, basin_outtp, basin_sz, basin_pts, basin_bxout, &
1639
       & basin_bbout, lshead, coast_pts, nwbas, basin_count, basin_notrun, basin_area, basin_cg, basin_hierarchy, &
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
       & basin_fac, basin_topoind, basin_id, basin_coor, basin_type, basin_flowdir, basin_lshead, &
       & outflow_grid, outflow_basin, nbcoastal, coastal_basin)
    !
    IMPLICIT NONE
    !
!! INPUT VARIABLES
    INTEGER(i_std), INTENT (in) :: nbpt !! Domain size (unitless)
    INTEGER(i_std), INTENT (in) :: ib !! Current basin (unitless)
    INTEGER(i_std), INTENT(in)  :: neighbours(nbpt,NbNeighb)!! Vector of neighbours for each grid point
                                                                         !! (1=North and then clockwise)
!! LOCAL VARIABLES
    REAL(r_std), DIMENSION(nbxmax,nbxmax)    :: area_bx      !! Area of each small box in the grid box (m^2)
1652 1653
    REAL(r_std), DIMENSION(nbxmax,nbxmax)    :: lon_bx       !! Longitude of each small box in the grid box
    REAL(r_std), DIMENSION(nbxmax,nbxmax)    :: lat_bx       !! Latitude of each small box in the grid box
1654 1655 1656 1657 1658 1659 1660
    INTEGER(i_std), DIMENSION(nbxmax,nbxmax) :: trip_bx      !! The trip field for each of the smaller boxes (unitless)
    REAL(r_std), DIMENSION(nbxmax,nbxmax)    :: hierarchy_bx !! Level in the basin of the point
    REAL(r_std), DIMENSION(nbxmax,nbxmax)    :: fac_bx !! Level in the basin of the point
    REAL(r_std), DIMENSION(nbxmax,nbxmax)    :: topoind_bx   !! Topographic index of the residence time for each of the smaller boxes (m)
    REAL(r_std)                              :: min_topoind  !! The current minimum of topographic index (m)
    INTEGER(i_std)                           :: nb_basin     !! Number of sub-basins (unitless)
    INTEGER(i_std), DIMENSION(nbvmax)