<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def rewrite_schema(r, df, doc=None):
 """Rebuild the schema for a resource based on a dataframe and re-write the doc"""


    from metapack.cli.core import write_doc

    if doc is None:
        doc = open_source_package()

    rebuild_schema(doc, r, df)

    write_doc(doc, doc.ref)