def swap_pairs(line, starttag=position_tag):
    """Swap coordinate pairs

    Inputs
        line: gml line assumed to contain pairs of coordinates ordered as
              latitude, longitude
        starttag: tag marking the start of the coordinate pairs.
    """

    endtag = starttag.replace('<', '</')

    index = line.find(starttag)
    if index < 0:
        msg = 'Expected line starting with <gml:posList>, got %s' % line
        raise Exception(msg)

    # Reuse indentation and tag
    k = index + len(starttag)
    new_line = line[:k]
    remaining_line = line[k:]

    # Swap coordinates for the rest of the line
    got_lat = False
    got_lon = False
    for field in remaining_line.split():

        # Clean end-tag from last field if present
        index = field.find(endtag)
        if index > -1:
            # We got e.g. 136.28396002600005</gml:posList>
            x = float(field[:index])
        else:
            x = float(field)

        # Assign latitude or longitude
        if got_lat:
            lon = x
            got_lon = True
        else:
            lat = x
            got_lat = True

        # Swap and write back every time a pair has been found
        # Ensure there are enough decimals for the required precision
        if got_lat and got_lon:
            new_line += ' %.9f %.9f' % (lon, lat)
            got_lat = got_lon = False

    # Close position list and return
    new_line += endtag + '\n'
    return new_line
Swap coordinate pairs

    Inputs
        line: gml line assumed to contain pairs of coordinates ordered as
              latitude, longitude
        starttag: tag marking the start of the coordinate pairs.