def extract_ligand_residues(
    pdb_hierarchy,
    ligand_code,
    atom_selection=None,
    only_segid=None):
  """
  Extract the atom_group object(s) with given 3-character residue name.

  :param pdb_hierarchy: input model
  :param ligand_code: 3-letter residue ID
  :param atom_selection: optional flex.bool object specifying ligand selection
      to use
  :param only_segid: optional segid which ligand(s) must match
  :returns: list of atom_group objects
  """
  assert (len(pdb_hierarchy.models()) == 1)
  ligands = []
  for chain in pdb_hierarchy.models()[0].chains():
    for residue_group in chain.residue_groups():
      for atom_group in residue_group.atom_groups():
        if (atom_group.resname == ligand_code):
          use_ligand = True
          if (only_segid is not None):
            for atom in atom_group.atoms():
              if (atom.segid != only_segid):
                use_ligand = False
                break
          if (use_ligand) and (atom_selection is not None):
            for atom in atom_group.atoms():
              if (not atom_selection[atom.i_seq]):
                use_ligand = False
                break
          if (use_ligand):
            ligands.append(atom_group)
  return ligands