def remove_hetatm(filename_in, file_out, remove_all):
    """Remove HETATM and related lines.
    If remove_all is False, remove only element X which happens in many PDB
    entries but is not accepted by pointless, refmac, phaser, etc
    """
    # we could instead zero occupancy of the atoms and replace X with Y
    file_in = open(filename_in)
    removed = set()

    def is_removed(serial):
        return serial and not serial.isspace() and int(serial) in removed

    for line in file_in:
        record = line[:6]
        if record == 'HETATM':
            if remove_all or line[76:78] == ' X':
                atom_serial_num = int(line[6:11])
                removed.add(atom_serial_num)
                continue
        elif record in ('HET   ', 'HETNAM', 'HETSYN', 'FORMUL'):
            continue
        elif line.startswith('ANISOU'):
            if is_removed(line[6:11]):
                continue
        elif line.startswith('CONECT'):
            if any(is_removed(line[p:p+5]) for p in (6, 11, 16, 21, 26)):
                continue
        file_out.write(line)
    return len(removed)