def gmt_overlay_grid(region, center, coords, legendloc, outfile):
    """Overlay the grid for a given region"""
    try:
        retcode = check_call( "psbasemap -X0 -Y0 -R%s -JE%s -V -Bg%swesn -Lf%sk+l -O -K >> %s"
                % (region, center, coords, legendloc, outfile), shell=True)
    except OSError, e:
       elog.elog_complain ("psbasemap execution failed:", e)
       raise
def gmt_plot_wet_and_coast(region, center, wet_rgb, outfile):
    """plot wet areas and coastline"""
    try:
        # Plot wet areas (not coast)
        retcode = check_call("pscoast"+" -V -R%s -JE%s -W0.5p,%s -S%s -A0/2/4 -Df -O -K >> %s" % (region, center, wet_rgb, wet_rgb, outfile), shell=True)
        # Plot coastline in black
        retcode = check_call("pscoast"+" -V -R%s -JE%s -W0.5p,0/0/0 -Df -O -K >> %s" % (region, center, outfile), shell=True)
        # Plot major rivers
        retcode = check_call("pscoast"+" -V -R%s -JE%s -Ir/0.5p,0/0/255 -Df -O -K >> %s" % (region, center, outfile), shell=True)
        # Plot national (N1) and state (N2) boundaries
        retcode = check_call("pscoast"+" -V -R%s -JE%s -N1/5/0/0/0 -N2/1/0/0/0 -Df -O -K >> %s" % (region, center, outfile), shell=True)
    except OSError, e:
        elog.elog_complain("A pscoast call failed: %s" % e)
        raise
def gmt_add_stations(station_loc_files, symsize, rgbs, outfile):
    """Overlay the station icons"""
    for key in sorted(station_loc_files.iterkeys()):
        if key == 'IU' or key == 'US': 
            # Plots diamond symbols for US backbone stations
            symtype='d'
        else:
            symtype='t'

        try:
            retcode = check_call(
                    "psxy %s -R -JE -V -S%s%s -G%s -W -L -O -K -: >> %s"
                    % (station_loc_files[key], symtype, symsize, rgbs[key],
                        outfile), shell=True)
        except OSError, e:
            elog.elog_complain("psxy execution failed: %s" % e)
            raise
def main(argv=None):
    """Main processing script for all maps """

    elog.elog_init(sys.argv)
    elog.elog_notify("Start of script")

    verbose, debug, year, month, maptype, deploytype, size = process_command_line(argv)
        
    if debug:
        elog.elog_notify("*** DEBUGGING ON ***")
        elog.elog_notify("*** No grd or grad files - just single color for speed ***")

    common_pf = 'common.pf'
    stations_pf = 'stations.pf'

    elog.elog_notify(" - Creating **%s** maps" % deploytype)
    if verbose:
        elog.elog_notify(" - Parse configuration parameter file (%s)" % common_pf)
        elog.elog_notify(" - Parse stations parameter file (%s)" % stations_pf)

    wet_rgb = '202/255/255'

    pfupdate(common_pf)
    pfupdate(stations_pf)

    dbmaster = pfget(common_pf, 'USARRAY_DBMASTER')
    networks = pfget_arr(stations_pf, 'network')
    infrasound = pfget_arr(stations_pf, 'infrasound')
    colors = pfget_arr(stations_pf, 'colors')
    # Force the tmp dir environmental variable
    tmp = pfget(common_pf, 'TMP')
    os.environ['TMPDIR'] = os.environ['TEMP'] = os.environ['TMP'] = tmp
    gmtbindir = pfget(common_pf, 'GMT_BIN')
    usa_coords = pfget_arr(common_pf, 'USACOORDS')
    ak_coords = pfget_arr(common_pf, 'AKCOORDS')
    web_output_dir = pfget(common_pf, 'CACHE_MONTHLY_DEPLOYMENT')
    web_output_dir_infra = pfget(common_pf, 'CACHE_MONTHLY_DEPLOYMENT_INFRA')
    infrasound_mapping = pfget(common_pf, 'INFRASOUND_MAPPING')
    output_dir = '/var/tmp' # FOR TESTING
    sys.path.append(gmtbindir)
    if size == 'wario':
        paper_orientation = 'landscape'
        paper_media = 'b0'
        symsize = '0.3'
    else:
        paper_orientation = 'portrait'
        paper_media = 'a1'
        symsize = '0.15'

    # Make sure execution occurs in the right directory
    cwd = os.getcwd()
    path_parts = cwd.split('/')
    if path_parts[-1] == 'deployment_history' and path_parts[-2] == 'bin':
        if verbose or debug:
            elog.elog_notify(' - Already in the correct current working directory %s' % cwd)
    else:
        cwd = os.getcwd() + '/bin/deployment_history'
        if verbose or debug:
            elog.elog_notify (' - Changed current working directory to %s' % cwd)
        os.chdir(cwd)
    # Make sure we set some GMT parameters for just this script
    # GMTSET
    try:
        set_gmt_params(paper_orientation, paper_media)
    except Exception, e:
        elog.elog_complain("An error occurred setting GMT params %s")
        raise
        # Add stations from local text files
        gmt_add_stations(station_loc_files, symsize, rgbs, ps[1])

        # }}} Contiguous United States

        if verbose or debug:
            elog.elog_notify (' - Working on Alaska inset')

        # {{{ Alaska

        if debug == True:
            try:
                retcode = check_call("pscoast -R%s -JE%s -Df -A5000 -S%s -G40/200/40 -V -X0.1i -Y0.1i -O -K >> %s" % (ak_region, ak_center, wet_rgb, ps[1]), shell=True)
            except OSError, e:
                elog.elog_complain("pscoast for Alaska execution failed: %s" % e)
                raise
        else:
            try:
                retcode = check_call("grdimage data/alaska.grd -R%s -JE%s -Cdata/land_ocean.cpt -Idata/alaska.grad -V -E100 -X0.1i -Y0.1i -O -K >> %s" % (ak_region, ak_center, ps[1]), shell=True)
            except OSError, e:
                elog.elog_complain("grdimage for alaska.grd execution failed: %s" % e)
                raise

        # Plot wet areas and coastline
        gmt_plot_wet_and_coast(ak_region, ak_center, wet_rgb, ps[1])

        # Overlay the grid
        gmt_overlay_grid(ak_region, ak_center, ak_coords['GRIDLINES'],
                '-145/57/60/500', ps[1])