def rename_residues(fhandle, name_from, name_to):
    """Changes the residue name of residues matching a pattern to another.
    """
    records = 'ATOM', 'HETATM', 'TER', 'ANISOU'
    for line in fhandle:
        if line.startswith(records):
            line_resname = line[17:20].strip()
            if line_resname == name_from:
                yield line[:17] + name_to.rjust(3) + line[20:]
                continue
        yield line
