def copyfragment(fragment0,newobj):
  """Copy the data in a fragment to another object.

  The data in the source fragment 'fragment0' is copied to the
  target object 'newobj', and 'newobj' is returned. 'newobj'
  should be a fragment object or some subclass of fragment (such
  as a 'program' object).

  copyfragment can be used to 'mutate' a fragment into (for
  example) a program object."""

  # Copy attribute data
  for item in fragment0.attributes():
    newobj[item] = fragment0.get_attribute(item)
  # Copy tables
  for tbl in fragment0.tables():
    newobj.addtable(tbl)
  # Copy keytexts
  for i in range(0,fragment0.nkeytexts()):
    keytext = fragment0.keytext(i)
    newobj.addkeytext(keytext.name(),
                      keytext.junk_text(),
                      keytext.message())
  # Try to copy other attributes that fragment subclasses
  # have (such as keywords)
  try:
    for line in fragment0.keywords():
      newobj.addkeyword(line)
  except AttributeError:
    # Either the source or target doesn't support
    # keyword storage
    pass
  # Return the populated object
  return newobj