def filereplacer(filepath):
    """
    This context manager yields two file pointers:

    origlines:
        a generator that yields lines from the original file
    tmp:
        a file descriptor as if you had used open(tempfile.mkstemp(), 'w')
    NL:
        one of "\n", "\r\n" or "\r" depending on what is encountered first in
        orig. If orig is empty or doesn't exist, then "\n" is used.

    Note that upon successful exiting of the context manager, the file
    nominated by filepath will be replaced by the temp file. This will be done
    using file renames, so it is as close to atomic as we can get it.

    If the context block raises an exception, the original file is not changed,
    and the temp file is deleted.

    If the context block raises a NoChangesNeeded exception, then any changes
    to tmpfile are discarded.
    """
    # create the tmp dir if it doesn't exist yet
    tmpdir = join(ROOT, 'tmp')
    if not os.path.exists(tmpdir):
        os.makedirs(tmpdir, mode=0o700)
    tmpname = join(tmpdir, os.path.basename(filepath))
    try:
        if exists(filepath):
            shutil.copy2(filepath, tmpname)
        with opentext(tmpname, 'w') as tmp:
            if os.path.exists(filepath):
                with opentext(filepath, 'r') as orig:
                    NL = "\n"
                    origlines = []
                    firstline = None
                    for firstline in orig:
                        break
                    if firstline is not None:
                        stripped = firstline.rstrip('\r\n')
                        NL = firstline[len(stripped):]
                        assert NL in ("\r", "\n", "\r\n"), "Bad NL %r" % NL
                        origlines = chain([stripped],
                                          (l.rstrip('\r\n') for l in orig))
                    yield tmp, origlines, NL
            else:
                yield tmp, None, "\n"
    except NoChangesNeeded:
        if os.path.exists(tmpname):
            os.unlink(tmpname)
    except:
        if os.path.exists(tmpname):
            os.unlink(tmpname)
        raise
    if os.path.exists(filepath):
        os.unlink(filepath)
    os.rename(tmpname, filepath)