Index: trunk/tools/generic_tools.py
===================================================================
--- trunk/tools/generic_tools.py	(revision 824)
+++ trunk/tools/generic_tools.py	(revision 825)
@@ -19,4 +19,6 @@
 
 ####### Content
+# chainSnum_levnext: Function to provide the next value for a given level from a chainStrnum hirerarchy of numbers
+# chainSnum_num: Function to pass a `ChainStrNum' string to a number
 # contflow: Function to bring back the increment in j,i grid points according to a trip: (inflow directions)
 # dictionary_key: Function to provide the first key in a dictionay with a given value
@@ -24,4 +26,6 @@
 # ijlonlat: Function to provide the imin,jmin imax,jmax of a lon,lat box
 # incomming_flow: Function to determine if a fgrid-flow inflows to the central grid point
+# num_chainSnum: Function to pass a value to a `ChainStrNum' number
+# num_split: Function to split a string at each numeric value keeping the number as the last character of each cut
 # PolyArea: Function to compute the area of the polygon following 'Shoelace formula'
 # significant_decomposition: Function to decompose a given number by its signifcant potencies
@@ -6393,10 +6397,17 @@
     diff = anum*1.
     iipot = 1
-    while diff > 0.:
-        pot = np.floor(np.log10(diff))
-        if pot < minpot: break
-        potv = np.int(diff/(10.**pot))
-#        print 'Lluis:',np.log10(diff), pot,':',10.**pot,':',diff/(10.**pot),'.',potv,'.',potv*10.**pot,diff
+    pot = np.floor(np.log10(anum))
+    while pot > minpot:
+        if diff >= 10.**(pot-1):
+            pot = np.floor(np.log10(diff))
+            potv = np.int(diff/(10.**pot))
+#            print 'Lluis:',np.log10(diff), pot,':',10.**pot,':',diff/(10.**pot),'.',potv,'.',potv*10.**pot,diff
+        else:
+            potv = 0
+            pot = pot - 1
+#            print 'Lluis:','*****', pot,':',10.**pot,':',diff/(10.**pot),'.',potv,'.',potv*10.**pot,diff
+
         diff = diff - potv*10.**pot
+#        print '  real diff', diff
         potencies.append(pot)
         potval.append(potv)
@@ -6605,4 +6616,168 @@
     return keyval
 
+def num_chainSnum(val):
+    """ Function to pass a value to a `ChainStrNum' number
+        `ChainStrNum:' hirerarchy classification where each levels is a significant number within a string:
+            1 lev.: [n]
+            2 lev.: [n][m]
+            3 lev.: [n][m][l]
+            ...
+          NOTE: when a given level has more than 9 values in a given potency of 10, then 'a' is attached in the front: 'a'[i]
+          NOTE: when a given level has more than 19 values in a given potency of 10, then 'b' is attached in the front: 'b'[i]
+          NOTE: when a given level has more than 29 values in a given potency of 10, then 'c' is attached in the front: 'c'[i]
+          (...)
+          NOTE: when a given level has more than 89 values in a given potency of 10, then 'i' is attached in the front: 'i'[i]
+          NOTE: 'o' is for that potencies of 10 without value
+      val = value to transform
+    >>> num_chainSnum(3)
+    3
+    >>> num_chainSnum(1976)
+    aig6
+    >>> num_chainSnum(12010)
+    aboa0
+    """
+    fname = 'num_chainSnum'
+
+    npot = np.int(np.log10(val))
+
+    chainSnum=''
+    if npot > 0:
+        Nvals, pots, vals = significant_decomposition(val,0)
+        rest = 0
+        for ipot in range(npot):
+            rest = rest + int(vals[ipot]*10**pots[ipot])
+            if vals[ipot] > 0:
+                chainSnum = chainSnum + chr(96+vals[ipot])
+            else:
+                chainSnum = chainSnum + 'o'
+
+        num = val - rest
+    else:
+        num = val
+    chainSnum = chainSnum + str(num)
+
+    return chainSnum
+
+def chainSnum_num(cSnum):
+    """ Function to pass a `ChainStrNum' string to number
+        `ChainStrNum:' hirerarchy classification where each levels is a significant number within a string:
+            1 lev.: [n]
+            2 lev.: [n][m]
+            3 lev.: [n][m][l]
+            ...
+          NOTE: when a given level has more than 9 values in a given potency of 10, then 'a' is attached in the front: 'a'[i]
+          NOTE: when a given level has more than 19 values in a given potency of 10, then 'b' is attached in the front: 'b'[i]
+          NOTE: when a given level has more than 29 values in a given potency of 10, then 'c' is attached in the front: 'c'[i]
+          (...)
+          NOTE: when a given level has more than 89 values in a given potency of 10, then 'i' is attached in the front: 'i'[i]
+          NOTE: 'o' is for that potencies of 10 without value
+      cSnum = value to transform
+    >>> num_chainSnum('3')
+    3
+    >>> num_chainSnum('aig6')
+    1976
+    >>> num_chainSnum('aboa0')
+    12010
+    """
+    fname = 'chainSnum_num'
+
+    num = 0
+    LcSnum = len(cSnum)
+    if LcSnum > 1:
+        for ic in range(LcSnum-1):
+            ipot = ord(cSnum[ic:ic+1]) - 96
+            if ipot < 0 or ipot > 9 and ipot != ord('o') - 96:
+                print errormsg
+                print '  ' + fname + ": wrong character '" + cSnum[ic:ic+1] + "' !!", ipot
+                print "    'ChainStrNum' codification only allows 'a' to 'i' and 'o'"
+                quit(-1)
+            else:
+                if ipot == ord('o') - 96: ipot = 0
+
+            num = num + int(ipot*10**(LcSnum-ic-1))
+
+    num = num + int(cSnum[LcSnum-1:LcSnum])
+
+    return num
+
+def num_split(string):
+    """ Function to split a string at each numeric value keeping the number as the last character of each cut
+      string= string to cut
+    >>> num_split('asd123asdsa1')
+    ['asd1', '2', '3', 'asdsa1']
+    """
+    fname = 'num_split'
+
+    Lstring = len(string)
+    cuts = []
+    newcut = ''
+    for ic in range(Lstring):
+        sc = string[ic:ic+1]
+        newcut = newcut + sc
+        if ord(sc) >= 48 and ord(sc) <= 57:
+            cuts.append(newcut)
+            newcut = ''
+
+    return cuts
+
+def chainSnum_levnext(parentlev, ChainStrNums):
+    """ Function to provide the next value for a given level from a chainStrnum hirerarchy of numbers
+      prevlev: parent level of the desired level
+      ChainStrNums: list of strings as `ChainStrNum'
+        `ChainStrNum:' hyerarchic classification where each levels is a significant number within a string:
+            1 lev.: [n]
+            2 lev.: [n][m]
+            3 lev.: [n][m][l]
+            ...
+          NOTE: when a given level has more than 9 values in a given potency of 10, then 'a' is attached in the front: 'a'[i]
+          NOTE: when a given level has more than 19 values in a given potency of 10, then 'b' is attached in the front: 'b'[i]
+          NOTE: when a given level has more than 29 values in a given potency of 10, then 'c' is attached in the front: 'c'[i]
+          (...)
+          NOTE: when a given level has more than 89 values in a given potency of 10, then 'i' is attached in the front: 'i'[i]
+          NOTE: 'o' is for that potencies of 10 without value
+    >>> ChainStrNums = ['1', '2', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a0', '111', '112', '113', '121', '122' ]
+    >>> chainSnum_levnext('',ChainStrNums)
+    3
+    >>> chainSnum_levnext('1',ChainStrNums)
+    1a1
+    >>> chainSnum_levnext('12',ChainStrNums)
+    123
+    >>> chainSnum_levnextt('111',ChainStrNums)
+    1111
+    """
+    fname = 'chainSnum_levnext'
+
+# Number of levels of the parent level
+    if len(parentlev) > 0:
+        parentlevs = num_split(parentlev)
+        Nparentlevs = len(parentlevs)
+    else:
+        parentlevs = ['']
+        Nparentlevs = 0
+
+#    print '  ' + fname + ' parentlev:', parentlev,'Nlevs:', Nparentlevs,'parentlevs:',parentlevs
+
+# Level to increment
+    lev = Nparentlevs + 1
+
+    rightvals = []
+    for istr in ChainStrNums:
+        levs = num_split(istr)
+        if len(levs) == lev:
+            parent = ''
+            for ilev in range(len(levs)-1):
+                parent = parent + levs[ilev]
+
+            if parent == parentlev:
+                rightvals.append(chainSnum_num(levs[lev-1]))
+
+    if len(rightvals) > 0:
+        newnum = np.max(rightvals)
+        newchainSnum = num_chainSnum(newnum + 1)
+    else:
+        newchainSnum = '1'
+
+    return parentlev + newchainSnum
+
 def subbasin_point(trips, pt):
     """ Function to provide sub-basins given a grid point following a matrix of trips
@@ -6656,15 +6831,6 @@
             ijfound[Nij] = True
             jipt = ijsubbasin[Nij]
-            Njipt = dictionary_key_list(ijsubflow, Nij)
-            if subfinished.has_key(Njipt + '1'): 
-                if subfinished.has_key(Njipt + '01'): 
-                    if subfinished.has_key(Njipt + '001'): 
-                        Njipt = Njipt + '0001'
-                    else:
-                        Njipt = Njipt + '001'
-                else:
-                    Njipt = Njipt + '01'
-            else:
-                Njipt = Njipt + '1'
+            parentNjipt = dictionary_key_list(ijsubflow, Nij)
+            Njipt = chainSnum_levnext(parentNjipt, ijsubflow.keys())
 #            print '  ' + fname + "new sub-flow '" + Njipt + "' !!"
             subfinished[Njipt] = False
@@ -6692,4 +6858,5 @@
             followvals = np.zeros((3,3), dtype=bool)
             followvals = arrive
+            parentNjipt = Njipt
 
             for ifollow in range(Narrive):
@@ -6707,9 +6874,11 @@
                         if ifollow != 0: 
 # Avoiding repetition of sub-flow name
-                            if subfinished.has_key(Njipt + str(ifollow)): 
-                                Njipt = Njipt + '0' + str(ifollow)
+                            if len(ijsubflow.keys()) > 1:
+                                Njipt = chainSnum_levnext(parentNjipt, ijsubflow.keys())
                             else:
-                                Njipt = Njipt + str(ifollow)
-#                            print '  ' + fname + "new sub-flow '" + Njipt + "' !!"
+                                Njipt = '11'
+                        else:
+                            Njipt = parentNjipt
+#                        print '  ' + fname + "new sub-flow '" + Njipt + "' !!"
                         subfinished[Njipt] = False
                         subbasin[jipt[0]+jiequiv[0], jipt[1]+jiequiv[1]] = True
@@ -6780,6 +6949,4 @@
 #  for isub in subflows[subflow]:
 #      print '  ' , isub , ':', subflowspt[isub]
-
+#
 #print 'Total sub-basin:', np.sum(masksubbasin)
-
-#quit()
