Index: python/plot_retrieved.py
===================================================================
--- python/plot_retrieved.py	(revision 991df6ad0a703d97e1e192a0a6106e1d9ba47e8e)
+++ python/plot_retrieved.py	(revision ccab8091e3f70844b2b6e73b9aa5e6b41aaf5ff5)
@@ -19,4 +19,6 @@
 #        - created function main and moved the two function calls for
 #          arguments and plotting into it
+#        - added function getBasics to extract the boundary conditions
+#          of the data fields from the first grib file it gets.
 #
 # @License:
@@ -30,8 +32,10 @@
 #
 # @Program Content:
-#    - plot_retrieved
-#    - plottimeseries
-#    - plotmap
-#    - interpret_plotargs
+#    - main
+#    - getBasics
+#    - plotRetrieved
+#    - plotTS
+#    - plotMap
+#    - getPlotArgs
 #
 #*******************************************************************************
@@ -40,6 +44,6 @@
 # MODULES
 # ------------------------------------------------------------------------------
+import time
 import datetime
-import time
 import os
 import inspect
@@ -57,5 +61,12 @@
 import matplotlib.colors as colors
 #from rasotools.utils import stats
-from gribapi import *
+
+font = {'family': 'monospace', 'size': 12}
+matplotlib.rcParams['xtick.major.pad'] = '20'
+
+matplotlib.rc('font', **font)
+
+from eccodes import *
+import numpy as np
 
 # add path to pythonpath so that python finds its buddies
@@ -66,7 +77,8 @@
 
 # software specific classes and modules from flex_extract
-from Tools import silentremove, product
+from Tools import silentremove
 from ControlFile import ControlFile
-from GribTools import GribTools
+#from GribTools import GribTools
+from UIOFiles import UIOFiles
 
 # ------------------------------------------------------------------------------
@@ -76,7 +88,7 @@
     '''
     @Description:
-        If plot_retrieved is called from command line, this function controls
+        If plotRetrieved is called from command line, this function controls
         the program flow and calls the argumentparser function and
-        the plot_retrieved function for plotting the retrieved GRIB data.
+        the plotRetrieved function for plotting the retrieved GRIB data.
 
     @Input:
@@ -86,10 +98,100 @@
         <nothing>
     '''
-    args, c = interpret_plotargs()
-    plot_retrieved(args, c)
+    args, c = getPlotArgs()
+    plotRetrieved(args, c)
 
     return
 
-def plot_retrieved(args, c):
+def getBasics(ifile, verb=False):
+    """
+    @Description:
+        An example grib file will be opened and basic information will
+        be extracted. These information are important for later use and the
+        initialization of numpy arrays for data storing.
+
+    @Input:
+        ifile: string
+            Contains the full absolute path to the ECMWF grib file.
+        verb (opt): bool
+            Is True if there should be extra output in verbose mode.
+            Default value is False.
+
+    @Return:
+        data: dict
+            Contains basic informations of the ECMWF grib files, e.g.
+            'Ni', 'Nj', 'latitudeOfFirstGridPointInDegrees',
+            'longitudeOfFirstGridPointInDegrees',
+            'latitudeOfLastGridPointInDegrees',
+            'longitudeOfLastGridPointInDegrees',
+            'jDirectionIncrementInDegrees',
+            'iDirectionIncrementInDegrees'
+    """
+    from eccodes import *
+
+    data = {}
+
+    # --- open file ---
+    print("Opening file for getting information data --- %s" %
+          os.path.basename(ifile))
+
+    with open(ifile) as f:
+
+        # load first message from file
+        gid = codes_grib_new_from_file(f)
+
+        # information needed from grib message
+        keys = [
+                'Ni',
+                'Nj',
+                'latitudeOfFirstGridPointInDegrees',
+                'longitudeOfFirstGridPointInDegrees',
+                'latitudeOfLastGridPointInDegrees',
+                'longitudeOfLastGridPointInDegrees',
+                'jDirectionIncrementInDegrees',
+                'iDirectionIncrementInDegrees'
+               ]
+
+        if verb: print('\nInformations are: ')
+        for key in keys:
+            # Get the value of the key in a grib message.
+            data[key] = codes_get(gid,key)
+            if verb: print "%s = %s" % (key,data[key])
+        if verb: print '\n'
+
+        # Free the memory for the message referred as gribid.
+        codes_release(gid)
+
+    return data
+
+def getFilesPerDate(files, datelist):
+    '''
+    @Description:
+        The filenames contain dates which are used to select a list
+        of files for a specific time period specified in datelist.
+
+    @Input:
+        files: instance of UIOFiles
+            For description see class documentation.
+            It contains the attribute "files" which is a list of pathes
+            to filenames.
+
+        datelist: list of datetimes
+            Contains the list of dates which should be processed for plotting.
+
+    @Return:
+        filelist: list of strings
+            Contains the selected files for the time period.
+    '''
+
+    filelist = []
+    for file in files:
+        fdate = file[-8:]
+        ddate = datetime.datetime.strptime(fdate, '%y%m%d%H')
+        if ddate in datelist:
+            filelist.append(file)
+
+    return filelist
+
+def plotRetrieved(args, c):
     '''
     @Description:
@@ -118,32 +220,47 @@
     end = datetime.datetime.strptime(c.end_date, '%Y%m%d%H')
 
+    # create datelist between start and end date
+    datelist = [start] # initialise datelist with first date
+    run_date = start
+    while run_date < end:
+        run_date += datetime.timedelta(hours=int(c.dtime))
+        datelist.append(run_date)
+
+    print 'datelist: ', datelist
+
     c.paramIds = asarray(c.paramIds, dtype='int')
     c.levels = asarray(c.levels, dtype='int')
     c.area = asarray(c.area)
 
-    index_keys = ["date", "time", "step"]
-    indexfile = c.inputdir + "/date_time_stepRange.idx"
-    silentremove(indexfile)
-    files = glob.glob(c.inputdir + '/' + c.prefix + '*')
-    grib = GribTools(files)
-    iid = grib.index(index_keys=index_keys, index_file = indexfile)
-
-    gdict = dict(Ni = 360, Nj = 181,
-                iScansNegatively = 0,  jScansPositively = 0,
-                jPointsAreConsecutive = 0,  alternativeRowScanning = 0,
-                latitudeOfFirstGridPointInDegrees = 90,
-                longitudeOfFirstGridPointInDegrees = 181,
-                latitudeOfLastGridPointInDegrees = -90,
-                longitudeOfLastGridPointInDegrees = 180,
-                iDirectionIncrementInDegrees = 1,
-                jDirectionIncrementInDegrees = 1
-                )
-
-    index_vals = []
-    for key in index_keys:
-        key_vals = grib_index_get(iid, key)
-        print key_vals
-
-        index_vals.append(key_vals)
+    # index_keys = ["date", "time", "step"]
+    # indexfile = c.inputdir + "/date_time_stepRange.idx"
+    # silentremove(indexfile)
+    # grib = GribTools(inputfiles.files)
+    # # creates new index file
+    # iid = grib.index(index_keys=index_keys, index_file=indexfile)
+
+    # # read values of index keys
+    # index_vals = []
+    # for key in index_keys:
+        # index_vals.append(grib_index_get(iid, key))
+        # print(index_vals[-1])
+        # # index_vals looks for example like:
+        # # index_vals[0]: ('20171106', '20171107', '20171108') ; date
+        # # index_vals[1]: ('0', '1200', '1800', '600') ; time
+        # # index_vals[2]: ('0', '12', '3', '6', '9') ; stepRange
+
+
+
+
+    #index_keys = ["date", "time", "step", "paramId"]
+    #indexfile = c.inputdir + "/date_time_stepRange.idx"
+    #silentremove(indexfile)
+
+    files = UIOFiles(c.prefix+'*')
+    files.listFiles(c.inputdir)
+    ifiles = getFilesPerDate(files.files, datelist)
+    ifiles.sort()
+
+    gdict = getBasics(ifiles[0], verb=False)
 
     fdict = dict()
@@ -156,67 +273,80 @@
             fmeta[key] = []
             fstamp[key] = []
-    for prod in product(*index_vals):
-        for i in range(len(index_keys)):
-            grib_index_select(iid, index_keys[i], prod[i])
-
-        gid = grib_new_from_index(iid)
-
+
+    for file in ifiles:
+        f = open(file)
+        print( "Opening file for reading data --- %s" % file)
+        fdate = datetime.datetime.strptime(file[-8:], "%y%m%d%H")
+
+        # Load in memory a grib message from a file.
+        gid = codes_grib_new_from_file(f)
         while(gid is not None):
-            date = grib_get(gid, 'date')
-            fdate = datetime.datetime(date/10000, mod(date,10000)/100,
-                                      mod(date,100))
-            gtime = grib_get(gid, 'time')
-            step = grib_get(gid, 'step')
-            fdatetime = fdate + datetime.timedelta(hours=gtime/100)
-            gtype = grib_get(gid, 'type')
-            paramId = grib_get(gid, 'paramId')
-            parameterName = grib_get(gid, 'parameterName')
-            level = grib_get(gid, 'level')
-            if step >= c.start_step and step <= c.end_step and \
-               fdatetime >= start and fdatetime <= end and \
-               paramId in c.paramIds and level in c.levels:
+            gtype = codes_get(gid, 'type')
+            paramId = codes_get(gid, 'paramId')
+            parameterName = codes_get(gid, 'parameterName')
+            level = codes_get(gid, 'level')
+
+            if paramId in c.paramIds and level in c.levels:
                 key = '{:0>3}_{:0>3}'.format(paramId, level)
-                print key
-                fdatetimestep = fdatetime + datetime.timedelta(hours=step)
-                if len(fstamp) == 0:
-                    fstamp[key].append(fdatetimestamp)
+                print 'key: ', key
+                if len(fstamp[key]) != 0 :
+                    for i in range(len(fstamp[key])):
+                        if fdate < fstamp[key][i]:
+                            fstamp[key].insert(i, fdate)
+                            fmeta[key].insert(i, [paramId, parameterName, gtype,
+                                                fdate, level])
+                            fdict[key].insert(i, flipud(reshape(
+                                            codes_get_values(gid),
+                                            [gdict['Nj'], gdict['Ni']])))
+                            break
+                        elif fdate > fstamp[key][i] and i == len(fstamp[key])-1:
+                            fstamp[key].append(fdate)
+                            fmeta[key].append([paramId, parameterName, gtype,
+                                                fdate, level])
+                            fdict[key].append(flipud(reshape(
+                                            codes_get_values(gid),
+                                            [gdict['Nj'], gdict['Ni']])))
+                            break
+                        elif fdate > fstamp[key][i] and i != len(fstamp[key])-1 \
+                             and fdate < fstamp[key][i+1]:
+                            fstamp[key].insert(i, fdate)
+                            fmeta[key].insert(i, [paramId, parameterName, gtype,
+                                                    fdate, level])
+                            fdict[key].insert(i, flipud(reshape(
+                                            codes_get_values(gid),
+                                            [gdict['Nj'], gdict['Ni']])))
+                            break
+                        else:
+                            pass
+                else:
+                    fstamp[key].append(fdate)
                     fmeta[key].append((paramId, parameterName, gtype,
-                                       fdatetime, gtime, step, level))
+                                       fdate, level))
                     fdict[key].append(flipud(reshape(
-                            grib_get_values(gid), [gdict['Nj'], gdict['Ni']])))
-                else:
-                    i = 0
-                    inserted = False
-                    for i in range(len(fstamp[key])):
-                        if fdatetimestep < fstamp[key][i]:
-                            fstamp[key][i:i] = [fdatetimestep]
-                            fmeta[key][i:i] = [(paramId, parameterName, gtype,
-                                                fdatetime, gtime, step, level)]
-                            fdict[key][i:i] = [flipud(reshape(
-                                                grib_get_values(gid),
-                                                [gdict['Nj'], gdict['Ni']]))]
-                            inserted = True
-                            break
-                    if not inserted:
-                        fstamp[key].append(fdatetimestep)
-                        fmeta[key].append((paramId, parameterName, gtype,
-                                           fdatetime, gtime, step, level))
-                        fdict[key].append(flipud(reshape(
-                            grib_get_values(gid), [gdict['Nj'], gdict['Ni']])))
-
-            grib_release(gid)
-            gid = grib_new_from_index(iid)
+                        codes_get_values(gid), [gdict['Nj'], gdict['Ni']])))
+
+            codes_release(gid)
+
+            # Load in memory a grib message from a file.
+            gid = codes_grib_new_from_file(f)
+
+        f.close()
+    #print 'fstamp: ', fstamp
+    #exit()
 
     for k in fdict.keys():
+        print 'fmeta: ', len(fmeta),fmeta
         fml = fmeta[k]
         fdl = fdict[k]
-
+        print 'fm1: ', len(fml), fml
+        #print 'fd1: ', fdl
+        #print zip(fdl, fml)
         for fd, fm in zip(fdl, fml):
+            print fm
             ftitle = fm[1] + ' {} '.format(fm[-1]) + \
                 datetime.datetime.strftime(fm[3], '%Y%m%d%H') #+ ' ' + stats(fd)
             pname = '_'.join(fm[1].split()) + '_{}_'.format(fm[-1]) + \
-                datetime.datetime.strftime(fm[3], '%Y%m%d%H') + \
-                '.{:0>3}'.format(fm[5])
-            plotmap(fd, fm, gdict, ftitle, pname + '.eps')
+                datetime.datetime.strftime(fm[3], '%Y%m%d%H')
+            plotMap(c, fd, fm, gdict, ftitle, pname, 'png')
 
     for k in fdict.keys():
@@ -230,19 +360,20 @@
                 datetime.datetime.strftime(fm[3], '%Y%m%d%H') #+ ' ' + stats(fd)
             pname = '_'.join(fm[1].split()) + '_{}_'.format(fm[-1]) + \
-                datetime.datetime.strftime(fm[3], '%Y%m%d%H') + \
-                '.{:0>3}'.format(fm[5])
+                datetime.datetime.strftime(fm[3], '%Y%m%d%H')
             lat = -20
             lon = 20
-            plottimeseries(fdl, fml, fsl, lat, lon,
-                           gdict, ftitle, pname + '.eps')
+            plotTS(c, fdl, fml, fsl, lat, lon,
+                           gdict, ftitle, pname, 'png')
 
     return
 
-def plottimeseries(flist, fmetalist, ftimestamps, lat, lon,
-                   gdict, ftitle, filename):
+def plotTS(c, flist, fmetalist, ftimestamps, lat, lon,
+                   gdict, ftitle, filename, fending, show=False):
     '''
     @Description:
 
     @Input:
+        c:
+
         flist:
             The actual data values to be plotted from the grib messages.
@@ -250,9 +381,8 @@
         fmetalist: list of strings
             Contains some meta date for the data field to be plotted:
-            parameter id, parameter Name, grid type, date and time,
-            time, forecast step, level
+            parameter id, parameter Name, grid type, datetime, level
 
         ftimestamps: list of datetime
-            Contains the time stamps in a datetime format, e.g.
+            Contains the time stamps.
 
         lat:
@@ -268,86 +398,63 @@
             The time series is stored in a file with this name.
 
+        fending: string
+            Contains the type of plot, e.g. pdf or png
+
+        show: boolean
+            Decides if the plot is shown after plotting or hidden.
+
     @Return:
         <nothing>
     '''
+    print 'plotting timeseries'
+
     t1 = time.time()
-    latindex = (lat + 90) * 180 / (gdict['Nj'] - 1)
-    lonindex = (lon + 179) * 360 / gdict['Ni']
+
+    llx = gdict['longitudeOfFirstGridPointInDegrees']
+    if llx > 180. :
+        llx -= 360.
+    lly = gdict['latitudeOfLastGridPointInDegrees']
+    dxout = gdict['iDirectionIncrementInDegrees']
+    dyout = gdict['jDirectionIncrementInDegrees']
+    urx = gdict['longitudeOfLastGridPointInDegrees']
+    ury = gdict['latitudeOfFirstGridPointInDegrees']
+    numxgrid = gdict['Ni']
+    numygrid = gdict['Nj']
+
     farr = asarray(flist)
-    ts = farr[:, latindex, lonindex]
-    f = plt.figure(figsize=(12,6.7))
+    #(time, lat, lon)
+
+    lonindex = linspace(llx, urx, numxgrid)
+    latindex = linspace(lly, ury, numygrid)
+    #print len(lonindex), len(latindex), farr.shape
+
+    #latindex = (lat + 90) * 180 / (gdict['Nj'] - 1)
+    #lonindex = (lon + 179) * 360 / gdict['Ni']
+    #print latindex, lonindex
+
+
+    ts = farr[:, 0, 0]#latindex[0], lonindex[0]]
+
+    fig = plt.figure(figsize=(12, 6.7))
+
     plt.plot(ftimestamps, ts)
     plt.title(ftitle)
-    savefig(c.outputdir + '/' + filename)
+
+    plt.savefig(c.outputdir+'/'+filename+'_TS.'+fending, facecolor=fig.get_facecolor(), edgecolor='none',format=fending)
     print 'created ', c.outputdir + '/' + filename
-    plt.close(f)
+    if show == True:
+        plt.show()
+    fig.clf()
+    plt.close(fig)
+
     print time.time() - t1, 's'
 
     return
 
-def plotmap(flist, fmetalist, gdict, ftitle, filename):
+def plotMap(c, flist, fmetalist, gdict, ftitle, filename, fending, show=False):
     '''
     @Description:
 
     @Input:
-        flist
-        fmetalist
-        gdict
-        ftitle
-        filename
-
-    @Return:
-        <nothing>
-    '''
-    t1 = time.time()
-    f = plt.figure(figsize=(12, 6.7))
-    mbaxes = f.add_axes([0.05, 0.15, 0.8, 0.7])
-    m = Basemap(llcrnrlon=-180., llcrnrlat=-90., urcrnrlon=180, urcrnrlat=90.)
-    #if bw==0 :
-        #fill_color=rgb(0.6,0.8,1)
-    #else:
-        #fill_color=rgb(0.85,0.85,0.85)
-
-    lw = 0.3
-    m.drawmapboundary()
-    parallels = arange(-90., 91, 90.)
-    # labels = [left, right, top, bottom]
-    m.drawparallels(parallels, labels=[True, True, True, True], linewidth=lw)
-    meridians = arange(-180., 181., 60.)
-    m.drawmeridians(meridians, labels=[True, True, True, True], linewidth=lw)
-    m.drawcoastlines(linewidth=lw)
-    xleft = gdict['longitudeOfFirstGridPointInDegrees']
-    if xleft > 180.0:
-        xleft -= 360.
-    x = linspace(xleft, gdict['longitudeOfLastGridPointInDegrees'], gdict['Ni'])
-    y = linspace(gdict['latitudeOfLastGridPointInDegrees'],
-                 gdict['latitudeOfFirstGridPointInDegrees'], gdict['Nj'])
-    xx, yy = m(*meshgrid(x, y))
-
-    s = m.contourf(xx, yy, flist)
-    title(ftitle, y=1.1)
-    cbaxes = f.add_axes([0.9, 0.2, 0.04, 0.6])
-    cb = colorbar(cax=cbaxes)
-
-    savefig(c.outputdir + '/' + filename)
-    print 'created ', c.outputdir + '/' + filename
-    plt.close(f)
-    print time.time() - t1, 's'
-
-    return
-
-def interpret_plotargs():
-    '''
-    @Description:
-        Assigns the command line arguments and reads CONTROL file
-        content. Apply default values for non mentioned arguments.
-
-    @Input:
-        <nothing>
-
-    @Return:
-        args: instance of ArgumentParser
-            Contains the commandline arguments from script/program call.
-
         c: instance of class ControlFile
             Contains all necessary information of a CONTROL file. The parameters
@@ -360,6 +467,128 @@
             For more information about format and content of the parameter see
             documentation.
-    '''
-    parser = ArgumentParser(description='Retrieve FLEXPART input from ' + \
+
+        flist
+
+        fmetalist
+
+        gdict: dict
+            Contains basic informations of the ECMWF grib files, e.g.
+            'Ni', 'Nj', 'latitudeOfFirstGridPointInDegrees',
+            'longitudeOfFirstGridPointInDegrees',
+            'latitudeOfLastGridPointInDegrees',
+            'longitudeOfLastGridPointInDegrees',
+            'jDirectionIncrementInDegrees',
+            'iDirectionIncrementInDegrees'
+
+        ftitle: string
+            The titel of the plot.
+
+        filename: string
+            The plot is stored in a file with this name.
+
+        fending: string
+            Contains the type of plot, e.g. pdf or png
+
+        show: boolean
+            Decides if the plot is shown after plotting or hidden.
+
+    @Return:
+        <nothing>
+    '''
+    print 'plotting map'
+
+    t1 = time.time()
+
+    fig = plt.figure(figsize=(12, 6.7))
+    #mbaxes = fig.add_axes([0.05, 0.15, 0.8, 0.7])
+
+    llx = gdict['longitudeOfFirstGridPointInDegrees'] #- 360
+    if llx > 180. :
+        llx -= 360.
+    lly = gdict['latitudeOfLastGridPointInDegrees']
+    dxout = gdict['iDirectionIncrementInDegrees']
+    dyout = gdict['jDirectionIncrementInDegrees']
+    urx = gdict['longitudeOfLastGridPointInDegrees']
+    ury = gdict['latitudeOfFirstGridPointInDegrees']
+    numxgrid = gdict['Ni']
+    numygrid = gdict['Nj']
+
+    m = Basemap(projection='cyl', llcrnrlon=llx, llcrnrlat=lly,
+                urcrnrlon=urx, urcrnrlat=ury,resolution='i')
+
+    lw = 0.5
+    m.drawmapboundary()
+    x = linspace(llx, urx, numxgrid)
+    y = linspace(lly, ury, numygrid)
+
+    xx, yy = m(*meshgrid(x, y))
+
+    #s = m.contourf(xx, yy, flist)
+
+    s = plt.imshow(flist.T,
+                    extent=(llx, urx, lly, ury),
+                    alpha=1.0,
+                    interpolation='nearest'
+                    #vmin=vn,
+                    #vmax=vx,
+                    #cmap=my_cmap,
+                    #levels=levels,
+                    #cmap=my_cmap,
+                    #norm=LogNorm(vn,vx)
+                    )
+
+    title(ftitle, y=1.08)
+    cb = m.colorbar(s, location="right", pad="10%")
+    #cb.set_label('Contribution per cell (ng m$^{-3}$)',size=14)
+
+    thickline = np.arange(lly,ury+1,10.)
+    thinline  = np.arange(lly,ury+1,5.)
+    m.drawparallels(thickline,color='gray',dashes=[1,1],linewidth=0.5,labels=[1,1,1,1], xoffset=1.) # draw parallels
+    m.drawparallels(np.setdiff1d(thinline,thickline),color='lightgray',dashes=[1,1],linewidth=0.5,labels=[0,0,0,0]) # draw parallels
+
+    thickline = np.arange(llx,urx+1,10.)
+    thinline  = np.arange(llx,urx+1,5.)
+    m.drawmeridians(thickline,color='gray',dashes=[1,1],linewidth=0.5,labels=[1,1,1,1],yoffset=1.) # draw meridians
+    m.drawmeridians(np.setdiff1d(thinline,thickline),color='lightgray',dashes=[1,1],linewidth=0.5,labels=[0,0,0,0]) # draw meridians
+
+    m.drawcoastlines()
+    m.drawcountries()
+
+    plt.savefig(c.outputdir+'/'+filename+'_MAP.'+fending, facecolor=fig.get_facecolor(), edgecolor='none',format=fending)
+    print 'created ', c.outputdir + '/' + filename
+    if show == True:
+        plt.show()
+    fig.clf()
+    plt.close(fig)
+
+    print time.time() - t1, 's'
+
+    return
+
+def getPlotArgs():
+    '''
+    @Description:
+        Assigns the command line arguments and reads CONTROL file
+        content. Apply default values for non mentioned arguments.
+
+    @Input:
+        <nothing>
+
+    @Return:
+        args: instance of ArgumentParser
+            Contains the commandline arguments from script/program call.
+
+        c: instance of class ControlFile
+            Contains all necessary information of a CONTROL file. The parameters
+            are: DAY1, DAY2, DTIME, MAXSTEP, TYPE, TIME, STEP, CLASS, STREAM,
+            NUMBER, EXPVER, GRID, LEFT, LOWER, UPPER, RIGHT, LEVEL, LEVELIST,
+            RESOL, GAUSS, ACCURACY, OMEGA, OMEGADIFF, ETA, ETADIFF, DPDETA,
+            SMOOTH, FORMAT, ADDPAR, WRF, CWC, PREFIX, ECSTORAGE, ECTRANS,
+            ECFSDIR, MAILOPS, MAILFAIL, GRIB2FLEXPART, DEBUG, INPUTDIR,
+            OUTPUTDIR, FLEXPART_ROOT_SCRIPTS
+            For more information about format and content of the parameter see
+            documentation.
+    '''
+    parser = ArgumentParser(description='Plot retrieved GRIB data from ' + \
                             'ECMWF MARS archive',
                             formatter_class=ArgumentDefaultsHelpFormatter)
@@ -374,9 +603,9 @@
                         help="start step in hours")
     parser.add_argument( "--end_step", dest="end_step",
-                         help="end_step in hours")
+                         help="end step in hours")
 
 # some arguments that override the default in the CONTROL file
     parser.add_argument("--levelist", dest="levelist",
-                        help="Vertical levels to be retrieved, e.g. 30/to/60")
+                        help="vertical levels to be retrieved, e.g. 30/to/60")
     parser.add_argument("--area", dest="area",
                         help="area defined as north/west/south/east")
@@ -398,5 +627,6 @@
 
     parser.add_argument("--controlfile", dest="controlfile",
-                        default='CONTROL.temp', help="file with CONTROL parameters")
+                        default='CONTROL.temp',
+                        help="file with CONTROL parameters")
     args = parser.parse_args()
 
@@ -418,4 +648,5 @@
     else:
         c.levels = [0]
+
     if args.area:
         c.area = args.area.split('/')
@@ -424,8 +655,10 @@
 
     c.paramIds = args.paramIds.split('/')
+
     if args.start_step:
         c.start_step = int(args.start_step)
     else:
         c.start_step = 0
+
     if args.end_step:
         c.end_step = int(args.end_step)
@@ -435,6 +668,9 @@
     c.start_date = args.start_date
     c.end_date = args.end_date
+
     c.prefix = args.prefix
+
     c.inputdir = args.inputdir
+
     if args.outputdir:
         c.outputdir = args.outputdir
