import re
import io


def rectify_csv(filepath):
    """
    Input CSV contains newlines embedded in address fields
    Identify these newlines and replace them
    with `|` characters.

    The values of the first column have a known and expected format An integer primary key value,
    followed by a r'US-d.' Certificate Identifier regex; r'/-d.,US/'

    We use this information to identify offending newlines
    Regex below captures new lines which are NOT followed
    by the expected integer PK and Certificate identifier fields
    """
    pattern = re.compile(r'''
                        (\n)       # Capture new-line for replacement
                        (?!        # Negative look ahead
                            \d+     # One or more digit
                            ,       # CSV field separator
                            US|$    # 'US' portion of expected following field OR end of line
                        )
                        ''', re.VERBOSE)
    output = io.StringIO()
    with open(filepath) as infile:
        f = infile.read()
        result = pattern.sub('|', f)
        output.write(result)
    output.seek(0)
    return output