def form_tree_definition(proj, formname):
    """Turn the form (instrument) definition in the project xml file into
    a python dictionary tree.

    In the XML structure items are defined in different places and the are
    various places where 'ref' items have to be looked up to find 'def'.

    Turn it into a nice neat:
    FormDef
        ItemGroup(s)
            Item(s)
    """

    """
    Form Def
    <FormDef OID="Form.ob_template" Name="Ob Template" Repeating="No" redcap:FormName="ob_template">
        <ItemGroupRef ItemGroupOID="ob_template.timestamp_template" Mandatory="No"/>
        ...
    </FormDef>


    <ItemGroupDef OID="ob_template.timestamp_template" Name="Ob Template" Repeating="No">
        <ItemRef ItemOID="timestamp_template" Mandatory="No" redcap:Variable="timestamp_template"/>
        <ItemRef ItemOID="title_measurements_template" Mandatory="No" redcap:Variable="title_measurements_template"/>
        ...
    </ItemGroupDef>
    <ItemGroupDef OID="ob_template.supqn_tired_template" Name="Confirm and Submit" Repeating="No">
        ...
    </ItemGroupDef>
    ...
    """

    tree = {}
    xpath = r"./Study/MetaDataVersion/FormDef/[@OID='%s']" % formname
    root = proj.find(xpath, proj.nsmap)

    tree = {**tree, **root.attrib}
    # tree['ItemGroupRef'] = []
    # tree['ItemGroupDef'] = []
    tree['ItemGroup'] = []

    for igr in root.getchildren():
        igr_oid = igr.attrib['ItemGroupOID']

        igd_xpath = r"./Study/MetaDataVersion/ItemGroupDef/[@OID='%s']" % igr_oid
        igd = proj.find(igd_xpath, proj.nsmap)

        itemgroup = {**igr.attrib, **igd.attrib}

        itemgroup['Item'] = []
        for itemref in igd.getchildren():
            item_oid = itemref.attrib['ItemOID']

            itmd_xpath = r"./Study/MetaDataVersion/ItemDef/[@OID='%s']" % item_oid
            itm = proj.find(itmd_xpath, proj.nsmap)

            item = {
                **itm.attrib
            }
            itemgroup['Item'].append(item)

        tree['ItemGroup'].append(itemgroup)

    return tree