import re


def parse_synctex_response(response, pos):
    """
    Take the stdout response of SyncTex and parse it
    into a dictionary.

    Parameters
    ----------
    response: string
        The response output to stdout from SyncTeX

    pos: dict
        The position that was input to SyncTeX

    returns:
        A dictionary with the parsed response.

    """
    fields = ["line", "column", "page", "x", "y"]
    match = re.search(r'SyncTeX result begin\r?\n(.*?)\nSyncTeX result end',
            response, flags=re.DOTALL)
    if match is None:
        raise Exception(f'Unable to parse SyncTeX response: {response}')
    lines = match.group(1).lower().replace(' ', '').split('\n')
    result = {}
    for l in lines:
        components = l.split(":")
        key, value = components[0], ":".join(components[1:])
        if key in fields:
            result[key] = value
            fields.remove(key)
    for f in fields:
        result[f] = pos[f]
    return result