def gml_to_polygon(footprint):
    """Converts a GML footprint into a WKT polygon string.

    Can handle the formats used by Sentinel-1, 2, and 3

    Parameters
    ----------
    footprint : str
        A GML footprint as retrieved from SciHub.

    Returns
    -------
    str
        The converted WKT polygon string.
    """
    footprint = footprint.replace('\n', '').strip()
    coords_poly = []
    #
    # Sentinel-1
    # (http://www.opengis.net/gml/srs/epsg.xml#4326)
    #
    if ',' in footprint:
        coords_gml = footprint.split()
        for coord_pair in coords_gml:
            lat, lon = [float(_) for _ in coord_pair.split(',')]
            if lon < -180.0:
                lon = -180.0
            if lon > 180.0:
                lon = 180.0
            if lat < -90.0:
                lat = -90.0
            if lat > 90.0:
                lat = 90.0
            coords_poly.append('{lon:.4f} {lat:.4f}'.format(lon=lon, lat=lat))

    #
    # Sentinel-3 and Sentinel-2
    # (http://www.opengis.net/def/crs/EPSG/0/4326)
    #
    else:
        coords_gml = footprint.split()
        for i in range(len(coords_gml)//2):
            lat = float(coords_gml[2*i])
            lon = float(coords_gml[2*i+1])
            if lon < -180.0:
                lon = -180.0
            if lon > 180.0:
                lon = 180.0
            if lat < -90.0:
                lat = -90.0
            if lat > 90.0:
                lat = 90.0
            coords_poly.append('{lon:.4f} {lat:.4f}'.format(lon=lon, lat=lat))

    #
    # Make sure the polygon is a closed line string.
    #
    if coords_poly[0] != coords_poly[-1]:
        coords_poly.append(coords_poly[0])

    wkt = 'POLYGON (({}))'.format(','.join(coords_poly))
    return wkt