<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _masquerade(origin: str, orig: ServiceDefn, new: ServiceDefn, **map: str) -> str: """build an origin URL such that the orig has all of the mappings to new defined by map"""


    origin: ParseResult = urlparse(origin)

    prev_maps = {}

    if origin.query:
        prev_maps = {k: v for k, v in parse_qsl(origin.query)}

    r_args = {}

    for new_k, orig_k in map.items():

        assert new_k in new.rpcs, [new_k, new.rpcs]
        assert orig_k in orig.rpcs, [orig_k, orig.rpcs]

        # todo: check if the definitions are the same

        new_v = new.rpcs[new_k]
        orig_v = orig.rpcs[orig_k]

        if orig_k in prev_maps:
            orig_k = prev_maps[orig_k]

        assert new_v.res == orig_v.res, [new_v.res, orig_v.res]
        assert new_v.req == orig_v.req, [new_v.req, orig_v.req]

        r_args[new_k] = orig_k

    return urlunparse(origin._replace(query=urlencode(r_args)))