Index: trunk/tools/generic_tools.py
===================================================================
--- trunk/tools/generic_tools.py	(revision 2442)
+++ trunk/tools/generic_tools.py	(revision 2443)
@@ -377,4 +377,20 @@
     return newstring
 
+def remove_extraspaces(string, maxNspaces=30):
+    """ Function to remove from a string any chain of more or equal than 2 spaces
+      string: string to modify
+      maxNspaces: maximum number of consecutive spaces to look for (30 default value)
+    >>> remove_extraspaces('  87047 01011991    6  19.0 6 70 7   27    2  17.9   874.9  1471.0              1    2      4 5  1  0      ')
+    87047 01011991 6 19.0 6 70 7 27 2 17.9 874.9 1471.0 1 2 4 5 1 0
+    """
+    fname = 'remove_extraspaces'
+
+    newstring = string + ''
+    for i in range(maxNspaces,1,-1):
+        spaces = Ntchar(' ',i)
+        newstring = newstring.replace(spaces, ' ')
+       
+    return newstring
+
 def string_dicvals_char(dictionary, string, char):
     """ Function to provide a string taking values from a given [string] where each single character 
@@ -1072,4 +1088,101 @@
 
     return dateYmdHMS
+
+
+def impose_gregorian(timev, Tunits, cal):
+    """ Function to impose gregorian calendar to a series of times with a 
+        non-standard calendar
+      timev: list of values
+      Tunits: CF units of time [Tunits] since [DateRef]
+      cal: non standard calendar
+      >>> impose_gregorian(np.range(800,10000,100), 'days since 1949-12-01 00:00:00',
+        'noleap')
+      [ 800. 901.]
+    """
+    import datetime as dt
+    fname = 'impose_gregorian'
+
+    availTu = ['weeks', 'days', 'hours', 'minutes', 'seconds']
+    availcalendar = ['noleap', '365d']
+
+    lTunits = Tunits.split(' ')
+    NTunits = len(lTunits)
+    Tu = lTunits[0]
+    if NTunits < 4: 
+        print infmsg
+        print '  ' + fname + ": CF-time units without time, adding '00:00:00' !!"
+        Srefdate = lTunits[2] + ' 00:00:00'
+        refdate = dt.datetime.combine(dateStr_date(lTunits[2]),                      \
+          timeStr_time('00:00:00'))
+    else:
+        Srefdate = lTunits[2] + ' ' + lTunits[3]
+        refdate = dt.datetime.combine(dateStr_date(lTunits[2]),                      \
+          timeStr_time(lTunits[3]))
+
+    if type(timev) == type(range(2)):
+        dimt = len(timev)
+        timev = np.array(timev)
+    elif type(timev) == type(np.arange(2)):
+        dimt = timev.shape[0]
+    elif type(timev) == type(int(2)) or type(timev) == type(np.float(2.)) or         \
+      type(timev) == type(float(2.)) or type(timev) == type(np.float32(2.)) or       \
+      type(timev) == type(np.float64(2.)):
+        dimt = 1
+        timev = np.ones(dimt, dtype=type(timev))*timev
+    else:
+        print errormsg
+        print '  ' + fname + ": type of time values: '", type(timev), "' not ready !!"
+        print '    available ones:', type(range(2)), type(np.arange(2)),type(int(2)),\
+          type(np.float(2.)), type(float(2.)), type(np.float32(2.)),                 \
+          type(np.float64(2.))
+        quit(-1)
+
+    if Tu == 'weeks':
+        timevsecs = timev * 24. * 7 * 3600.
+    elif Tu == 'days':
+        timevsecs = timev * 24. * 3600.
+    elif Tu == 'hours':
+        timevsecs = timev * 3600.
+    elif Tu == 'minutes':
+        timevsecs = timev * 60.
+    elif Tu == 'seconds':
+        timevsecs = timev * 1.
+    else:
+        print errormsg
+        print '  ' + fname + ": CF time units '" + Tu + "' not ready !!"
+        print '    available ones:', availTu
+        quit(-1)
+
+    newtimes = np.zeros((dimt), dtype=np.float64)
+
+    yrref = refdate.year
+    if cal == 'noleap' or cal == '365d':
+        for it in range(dimt):
+            # Some issues in implementations/machines ...
+            # FROM: https://stackoverflow.com/questions/33566939/timedelta-error-with-numpy-longdouble-dtype
+            tv = int(timevsecs[it])
+            deltaT = dt.timedelta(seconds=tv)
+            datetime = refdate + deltaT
+            yr = datetime.year
+            Nleapd = leapdays(yrref, yr)
+            if datetime.month <= 2 and days_month(yr, 2) > 28: Nleapd = Nleapd - 1
+            newtimes[it] = timevsecs[it] + Nleapd*24*3600.
+    else:
+        print errormsg
+        print '  ' + fname + ": calendar '" + cal + "' not ready !!"
+        print '    available ones:', availcalendar
+        quit(-1)
+        
+    # Re-transforming to the original units
+    if Tu == 'weeks':
+        newtimes = newtimes/(24.*7*3600.)
+    elif Tu == 'days':
+        newtimes = newtimes/(24.*3600.)
+    elif Tu == 'hours':
+        newtimes = newtimes/(3600.)
+    elif Tu == 'minutes':
+        newtimes = newtimes/(60.)
+
+    return newtimes
 
 def period_information(idate, edate, totunits):
@@ -3043,15 +3156,31 @@
     return newdate
 
-def timeref_datetime(refd, timeval, tu):
+def timeref_datetime(refd, timeval, tu, cal='gregorian'):
     """ Function to transform from a [timeval] in [tu] units from the time referece [tref] to datetime object
-    refd: time of reference (as datetime object)
-    timeval: time value (as [tu] from [tref])
-    tu: time units
-    >>> timeref = date(1949,12,1,0,0,0)
-    >>> timeref_datetime(timeref, 229784.36, hours)
-    1976-02-17 08:21:36
+      refd: time of reference (as datetime object)
+      timeval: time value (as [tu] from [tref])
+      tu: time units
+      cal: calendar
+      >>> timeref_datetime(dt.datetime(1949,12,1,0,0,0), 229784.36, 'hours')
+        1976-02-17 08:21:36
+      >>> timeref_datetime(dt.datetime(1949,12,1,0,0,0), 230784.36, 'hours')
+        1976-03-30 00:21:36
+      >>> timeref_datetime(dt.datetime(1949,12,1,0,0,0), 230784.36, 'hours', 'noleap')
+        1976-04-06 00:21:36
     """
     import datetime as dt
     import numpy as np
+
+    availtu = ['weeks', 'days', 'hours', 'minutes', 'seconds', 'miliseconds']
+
+    daterefS = str(refd.year).zfill(4) + '-' + str(refd.month).zfill(2) + '-' +      \
+      str(refd.day).zfill(2) + ' ' + str(refd.hour).zfill(2) + ':'+                  \
+      str(refd.minute).zfill(2) + ':' + str(refd.second).zfill(2)
+
+    # For non-gregorian calendars, we impose gregorian (since, we are using python)
+    if cal == 'noleap' or cal == '365d':
+        timev = impose_gregorian(timeval, tu + ' since ' + daterefS, cal)
+    else:
+        timev = timeval + 0.
 
 ## Not in timedelta
@@ -3061,19 +3190,20 @@
 #        realdate = refdate + dt.timedelta(months=float(timeval))
     if tu == 'weeks':
-        realdate = refd + dt.timedelta(weeks=float(timeval))
+        realdate = refd + dt.timedelta(weeks=float(timev))
     elif tu == 'days':
-        realdate = refd + dt.timedelta(days=float(timeval))
+        realdate = refd + dt.timedelta(days=float(timev))
     elif tu == 'hours':
-        realdate = refd + dt.timedelta(hours=float(timeval))
+        realdate = refd + dt.timedelta(hours=float(timev))
     elif tu == 'minutes':
-        realdate = refd + dt.timedelta(minutes=float(timeval))
+        realdate = refd + dt.timedelta(minutes=float(timev))
     elif tu == 'seconds':
-        realdate = refd + dt.timedelta(seconds=float(timeval))
+        realdate = refd + dt.timedelta(seconds=float(timev))
     elif tu == 'milliseconds':
-        realdate = refd + dt.timedelta(milliseconds=float(timeval))
+        realdate = refd + dt.timedelta(milliseconds=float(timev))
     else:
-          print errormsg
-          print '    timeref_datetime: time units "' + tu + '" not ready!!!!'
-          quit(-1)
+        print errormsg
+        print '  ' + fname + ": time units '" + tu + "' not ready!!!!"
+        print '    available ones:', availtu
+        quit(-1)
 
     return realdate
@@ -15668,107 +15798,4 @@
 #        print '  ' , '(', inds[i,j,0], ',', inds[i,j,1], ')'
 
-def remove_extraspaces(string, maxNspaces=30):
-    """ Function to remove from a string any chain of more or equal than 2 spaces
-      string: string to modify
-      maxNspaces: maximum number of consecutive spaces to look for (30 default value)
-    >>> remove_extraspaces('  87047 01011991    6  19.0 6 70 7   27    2  17.9   874.9  1471.0              1    2      4 5  1  0      ')
-    87047 01011991 6 19.0 6 70 7 27 2 17.9 874.9 1471.0 1 2 4 5 1 0
-    """
-    fname = 'remove_extraspaces'
-
-    newstring = string + ''
-    for i in range(maxNspaces,1,-1):
-        spaces = Ntchar(' ',i)
-        newstring = newstring.replace(spaces, ' ')
-       
-    return newstring
-
-def impose_gregorian(timev, Tunits, cal):
-    """ Function to impose gregorian calendar to a series of times with a 
-        non-standard calendar
-      timev: list of values
-      Tunits: CF units of time [Tunits] since [DateRef]
-      cal: non standard calendar
-      >>> impose_gregorian(np.range(800,10000,100), 'days since 1949-12-01 00:00:00',
-        'noleap')
-      [ 800. 901.]
-    """
-    import datetime as dt
-    fname = 'impose_gregorian'
-
-    availTu = ['weeks', 'days', 'hours', 'minutes', 'seconds']
-    availcalendar = ['noleap', '365d']
-
-    lTunits = Tunits.split(' ')
-    NTunits = len(lTunits)
-    Tu = lTunits[0]
-    if NTunits < 4: 
-        print infmsg
-        print '  ' + fname + ": CF-time units without time, adding '00:00:00' !!"
-        Srefdate = lTunits[2] + ' 00:00:00'
-        refdate = dt.datetime.combine(dateStr_date(lTunits[2]),                      \
-          timeStr_time('00:00:00'))
-    else:
-        Srefdate = lTunits[2] + ' ' + lTunits[3]
-        refdate = dt.datetime.combine(dateStr_date(lTunits[2]),                      \
-          timeStr_time(lTunits[3]))
-
-    if type(timev) == type(range(2)):
-        dimt = len(timev)
-        timev = np.array(timev)
-    elif type(timev) == type(np.arange(2)):
-        dimt = timev.shape[0]
-    else:
-        print errormsg
-        print '  ' + fname + ": type of time values: '", type(timev), "' not ready !!"
-        print '    available ones:', type(range(2)), type(np.arange(2)) 
-
-    if Tu == 'weeks':
-        timevsecs = timev * 24. * 7 * 3600.
-    elif Tu == 'days':
-        timevsecs = timev * 24. * 3600.
-    elif Tu == 'hours':
-        timevsecs = timev * 3600.
-    elif Tu == 'minutes':
-        timevsecs = timev * 60.
-    elif Tu == 'seconds':
-        timevsecs = timev * 1.
-    else:
-        print errormsg
-        print '  ' + fname + ": CF time units '" + Tu + "' not ready !!"
-        print '    available ones:', availTu
-        quit(-1)
-
-    newtimes = np.zeros((dimt), dtype=np.float64)
-
-    yrref = refdate.year
-    if cal == 'noleap' or cal == '365d':
-        for it in range(dimt):
-            # Some issues in implementations/machines ...
-            # FROM: https://stackoverflow.com/questions/33566939/timedelta-error-with-numpy-longdouble-dtype
-            tv = int(timevsecs[it])
-            deltaT = dt.timedelta(seconds=tv)
-            datetime = refdate + deltaT
-            yr = datetime.year
-            Nleapd = leapdays(yrref, yr)
-            if datetime.month <= 2 and days_month(yr, 2) > 28: Nleapd = Nleapd - 1
-            newtimes[it] = timevsecs[it] + Nleapd*24*3600.
-    else:
-        print errormsg
-        print '  ' + fname + ": calendar '" + cal + "' not ready !!"
-        print '    available ones:', availcalendar
-        quit(-1)
-        
-    # Re-transforming to the original units
-    if Tu == 'weeks':
-        newtimes = newtimes/(24.*7*3600.)
-    elif Tu == 'days':
-        newtimes = newtimes/(24.*3600.)
-    elif Tu == 'hours':
-        newtimes = newtimes/(24.*3600.)
-    elif Tu == 'minutes':
-        newtimes = newtimes/(60.)
-
-    return newtimes
 
 #quit()
