<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="CDA.xsl"?>
<!--

    Title: US_Realm_Header_Template
    Original Filename: US_Realm_Header_Template.xml
    Version: 1.0

    Generated via BlueButton.js

-->
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="urn:hl7-org:v3 ../../C-CDA%20rules/infrastructure/cda/CDA_SDTC.xsd"
 xmlns="urn:hl7-org:v3" xmlns:voc="urn:hl7-org:v3/voc">

<!--
********************************************************

  CDA Header

********************************************************
-->

    <realmCode code="US"/>
    <typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040"/>
    <!-- US General Header Template -->
    <templateId root="2.16.840.1.113883.10.20.22.1.1"/>
    <!-- *** Note:  The next templateId, code and title will differ depending on what type of document is being sent. *** -->
    <!-- conforms to the document specific requirements  -->
    <templateId root="2.16.840.1.113883.10.20.22.1.2"/>
    <id extension="999021" root="2.16.840.1.113883.19"/>
    <code codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" code="34133-9" displayName="Summarization of Episode Note"/>
    <title>
        <% if ("document" in bb && bb.document.title) { %>
            <%= bb.document.title %>
        <% } else if ("demographics" in bb) { %>
            <% if (bb.demographics.name.family) {%>
                <%= bb.demographics.name.family %> Health Summary
            <%} %>
        <%} else { %>
            Patient Health Summary
        <%} %>
    </title>
    <% if ("document" in bb && bb.document.date) { %>
        <effectiveTime <%-: bb.document.date | hl7Date %> />
    <% } else { %>
        <effectiveTime <%-: now | hl7Date %> />
    <% } %>
    <confidentialityCode code="N" displayName="Normal" codeSystem="2.16.840.1.113883.5.25"/>
    <languageCode code="en-US"/>
    <setId extension="111199021" root="2.16.840.1.113883.19"/>
    <versionNumber value="1"/>
    <recordTarget>
        <% if ("demographics" in bb) { %>

            <patientRole>
                <id extension="12345" root="2.16.840.1.113883.19"/>
                <!-- Fake ID using HL7 example OID. -->
                <id extension="111-00-1234" root="2.16.840.1.113883.4.1"/>
                <!-- Fake Social Security Number using the actual SSN OID. -->
                <addr use="HP">
                    <!-- HP is "primary home" from codeSystem 2.16.840.1.113883.5.1119 -->
                    <%-: tagHelpers.addressTags(bb.demographics.address) %>
                </addr>
                <% if (bb.demographics.phone.home) { -%>
                    <telecom use="HP" value="<%= bb.demographics.phone.home %>"/>
                <% } -%>
                <% if (bb.demographics.phone.work) { -%>
                    <telecom use="WP" value="<%= bb.demographics.phone.work %>"/>
                <% } -%>
                <% if (bb.demographics.phone.mobile) { -%>
                    <telecom use="MC" value="<%= bb.demographics.phone.mobile %>"/>
                <% } -%>
                <% if (!bb.demographics.phone.home && !bb.demographics.phone.work && !bb.demographics.phone.mobile) { -%>
                    <telecom nullFlavor="NI" />
                <% } -%>
                <patient>
                    <name use="L">
                        <!-- L is "Legal" from HL7 EntityNameUse 2.16.840.1.113883.5.45 -->
                        <%-: tagHelpers.nameTags(bb.demographics.name) %>
                    </name>
                    <administrativeGenderCode code="<%=: codes.reverseGender(bb.demographics.gender) %>" codeSystem="2.16.840.1.113883.5.1" displayName="<%= bb.demographics.gender %>"/>
                    <birthTime <%-: bb.demographics.dob | hl7Date %> />
                    <% if (bb.demographics.marital_status) { %>
                        <maritalStatusCode code="<%=: codes.reverseMaritalStatus(bb.demographics.marital_status) %>" displayName="<%= bb.demographics.marital_status %>" codeSystem="2.16.840.1.113883.5.2" codeSystemName="MaritalStatusCode"/>
                    <%} %>
                    <% if (bb.demographics.religion) { %>
                        <religiousAffiliationCode code="<%=: codes.reverseReligion(bb.demographics.religion) %>" displayName="<%= bb.demographics.religion %>" codeSystemName="HL7 Religious Affiliation " codeSystem="2.16.840.1.113883.5.1076"/>
                    <%} %>
                    <% if (bb.demographics.race) { %>
                        <raceCode code="<%=: codes.reverseRaceEthnicity(bb.demographics.race) %>" displayName="<%= bb.demographics.race %>" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp; Ethnicity - CDC"/>
                    <%} else { %>
                        <raceCode nullFlavor="NI" />
                    <%} %>
                    <% if (bb.demographics.ethnicity) { %>
                        <ethnicGroupCode code="<%=: codes.reverseRaceEthnicity(bb.demographics.ethnicity) %>" displayName="<%= bb.demographics.ethnicity %>" codeSystem="2.16.840.1.113883.6.238" codeSystemName="Race &amp; Ethnicity - CDC"/>
                    <%} else { %>
                        <ethnicGroupCode nullFlavor="NI" />
                    <%} %>
                    <% if (bb.demographics.guardian.name.family) { %>
                        <guardian>
                            <% if (codes.role(bb.demographics.guardian.relationship_code)) { -%>
                                <code code="<%=: bb.demographics.guardian.relationship_code %>" displayName="<%= bb.demographics.guardian.relationship %>" codeSystem="2.16.840.1.113883.5.111" codeSystemName="HL7 Role code"/>
                            <% } else if (codes.reverseRole(bb.demographics.guardian.relationship)) { -%>
                                <code code="<%=: codes.reverseRole(bb.demographics.guardian.relationship) %>" displayName="<%= bb.demographics.guardian.relationship %>" codeSystem="2.16.840.1.113883.5.111" codeSystemName="HL7 Role code"/>
                            <% } -%>
                            <addr use="HP">
                                <!-- HP is "primary home" from codeSystem 2.16.840.1.113883.5.1119 -->
                                <%-: tagHelpers.addressTags(bb.demographics.guardian.address) %>
                            </addr>
                            <telecom value="<%= bb.demographics.guardian.phone.home %>" use="HP"/>
                            <guardianPerson>
                                <name>
                                    <%-: tagHelpers.nameTags(bb.demographics.guardian.name) %>
                                </name>
                            </guardianPerson>
                        </guardian>
                    <%} %>
                    <% if (bb.demographics.birthplace.state || bb.demographics.birthplace.zip) { %>
                        <birthplace>
                            <place>
                                <addr>
                                    <state><%= bb.demographics.birthplace.state %></state>
                                    <postalCode><%= bb.demographics.birthplace.zip %></postalCode>
                                    <%-: tagHelpers.simpleTag('country', bb.demographics.birthplace.country) %>
                                    <%-: tagHelpers.simpleTag('country', bb.demographics.birthplace.country) %>
                                </addr>
                            </place>
                        </birthplace>
                    <%} %>
                    <% if (bb.demographics.language) { %>
                        <languageCommunication>
                            <languageCode code="<%= bb.demographics.language %>"/>
                            <modeCode code="RWR" displayName="Recieve Written" codeSystem="2.16.840.1.113883.5.60" codeSystemName="LanguageAbilityMode"/>
                            <preferenceInd value="true"/>
                        </languageCommunication>
                    <%} else { %>
                        <languageCommunication>
                          <languageCode nullFlavor="NI" />
                          <preferenceInd value="true" />
                        </languageCommunication>
                    <%} %>
                </patient>
                <providerOrganization>
                    <id root="2.16.840.1.113883.19"/>
                    <name><%= bb.demographics.provider.organization %></name>
                    <telecom use="WP" value="<%= bb.demographics.provider.phone %>"/>
                    <addr>
                        <%-: tagHelpers.addressTags(bb.demographics.provider.address) %>
                    </addr>
                </providerOrganization>
            </patientRole>

        <%} else { %>

            <patientRole>
              <id extension="CS - Patient - 1" root="CSP123456" />
              <addr use="HP">
                <%-: tagHelpers.addressTags(null) %>
              </addr>
              <telecom nullFlavor="NI" />
              <patient>
                <name use="L">
                  <given>Name</given>
                  <family>Withheld</family>
                </name>
                <administrativeGenderCode nullFlavor="NI" />
                <birthTime nullFlavor="NI" />
                <maritalStatusCode nullFlavor="NI" />
                <raceCode nullFlavor="NI" />
                <ethnicGroupCode nullFlavor="NI" />
                <languageCommunication>
                  <languageCode nullFlavor="NI" />
                  <preferenceInd value="true" />
                </languageCommunication>
              </patient>
              <providerOrganization>
                <id extension="1234567893" root="2.16.840.1.113883.4.6" />
                <name />
                <telecom use="WP" value="" />
                <addr use="WP">
                  <%-: tagHelpers.addressTags(null) %>
                </addr>
              </providerOrganization>
            </patientRole>

        <%} %>

    </recordTarget>
    
    <% if ("document" in bb) { %>
        <author>
            <time <%-: now | hl7Date %> />
            <assignedAuthor>
                <!-- TODO support real NPI -->
                <id extension="99999999" root="2.16.840.1.113883.4.6"/>
                <addr>
                    <%-: tagHelpers.addressTags(bb.document.author.address) %>
                </addr>
                <telecom use="WP" value="<%= bb.document.author.phone.work %>"/>
                <assignedPerson>
                    <name>
                        <%-: tagHelpers.nameTags(bb.document.author.name) %>
                    </name>
                </assignedPerson>
            </assignedAuthor>
        </author>
        <custodian>
            <assignedCustodian>
                <representedCustodianOrganization>
                    <id extension="99999999" root="2.16.840.1.113883.4.6"/>
                    <name><%= bb.document.author.name.family %></name>
                    <telecom use="WP" value="<%= bb.document.author.phone.work %>"/>
                    <addr>
                        <%-: tagHelpers.addressTags(bb.document.author.address) %>
                    </addr>
                </representedCustodianOrganization>
            </assignedCustodian>
        </custodian>
        <documentationOf>
            <serviceEvent classCode="PCPR">
                <effectiveTime>
                    <% if (bb.document.date) { %>
                        <low <%-: bb.document.date | hl7Date %> />
                    <% } else { %>
                        <low <%-: now | hl7Date %> />
                    <% } %>
                    <high nullFlavor="UNK" />
                </effectiveTime>
                <% for (var i=0; i<bb.document.documentation_of.length; i++) { var performer = bb.document.documentation_of[i]; %>
                    <performer typeCode="PRF">
                        <assignedEntity>
                            <id extension="99999999" root="2.16.840.1.113883.4.6"/>
                            <code code="261QP2300X" displayName="Primary Care [Ambulatory Health Care Facilities\Clinic/Center]"
                                codeSystemName="NUCC Provider Codes" codeSystem="2.16.840.1.113883.6.101"/>
                            <% if (performer.address) { -%>
                                <addr use="WP">
                                    <%-: tagHelpers.addressTags(performer.address) %>
                                </addr>
                            <% } else { -%>
                                <addr />
                            <% } -%>
                            <% if (performer.phone.work) { -%>
                                <telecom use="WP" value="<%= performer.phone.work %>"/>
                            <% } else { -%>
                                <telecom nullFlavor="UNK" />
                            <% } -%>
                            <assignedPerson>
                                <name>
                                    <%-: tagHelpers.nameTags(performer.name) %>
                                </name>
                            </assignedPerson>
                        </assignedEntity>
                    </performer>
                <% } %>
            </serviceEvent>
        </documentationOf>
        <% if (bb.document.location && bb.document.location.name) { %>
            <componentOf>
                <encompassingEncounter>
                    <id extension = "6745876" root = "2.16.840.1.113883.19"/>
                    <effectiveTime>
                        <% if (bb.document.location.encounter_date) { %>
                            <low <%-: bb.document.location.encounter_date | hl7Date %> />
                        <% } else if (bb.document.date) { %>
                            <low <%-: bb.document.date | hl7Date %> />
                        <% } else { %>
                            <low <%-: now | hl7Date %> />
                        <% } %>
                        <high nullFlavor="UNK" />
                    </effectiveTime>
                    <location>
                        <healthCareFacility>
                            <id extension = "9985647" root = "2.16.840.1.113883.19"/>
                            <code code="261QP2300X" displayName="Primary Care [Ambulatory Health Care Facilities\Clinic/Center]"
                                  codeSystemName="NUCC Provider Codes" codeSystem="2.16.840.1.113883.6.101"/>
                            <location>
                                <name><%= bb.document.location.name %></name>
                                <addr>
                                    <%-: tagHelpers.addressTags(bb.document.location.address) %>
                                </addr>
                            </location>
                        </healthCareFacility>
                    </location>
                </encompassingEncounter>
            </componentOf>
        <% } %>
    <%} %>

    <!-- ********************************************************

     CDA Body

     ******************************************************** -->
    <component>
        <structuredBody>
            <!-- *********************** -->

            <!--
            ********************************************************

            Allergies, Adverse Reactions, Alerts

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.6.1"/>
                        <!-- Alerts section template -->
                        <code code="48765-2" codeSystem="2.16.840.1.113883.6.1"/>
                        <title>Allergies, Adverse Reactions, Alerts</title>
                        <text>
                            <% if ("allergies" in bb && bb.allergies.length) { %>
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Substance</th>
                                            <th>Code</th>
                                            <th>Reaction</th>
                                            <th>Severity</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.allergies.length; i++) { %>
                                            <tr>
                                                <td><%=: bb.allergies[i].allergen.name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.allergies[i].allergen.code | emptyStringIfFalsy %></td>
                                                <td><%=: bb.allergies[i].reaction.name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.allergies[i].severity | emptyStringIfFalsy %></td>
                                                <td><%=: bb.allergies[i].status %></td>
                                            </tr>
                                        <% } %>
                                    </tbody>
                                </table>
                            <% } else { %>
                                No allergy data provided.
                            <% } %>
                        </text>

                        <% if ("allergies" in bb && bb.allergies.length) { %>
                            <% for (var i=0; i<bb.allergies.length; i++) { %>

                                <entry typeCode="DRIV">
                                    <act classCode="ACT" moodCode="EVN">
                                        <templateId root="2.16.840.1.113883.10.20.22.4.30"/>
                                        <!-- ** Allergy problem act ** -->
                                        <id root="36e3e930-7b14-11db-9fe1-0800200c9a66"/>
                                        <code code="48765-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Allergies, adverse reactions, alerts"/>
                                        <statusCode code="active"/>
                                        <effectiveTime <%-: bb.allergies[i].date_range.start | hl7Date %>  >
                                            <low <%-: bb.allergies[i].date_range.start | hl7Date %> />
                                            <high <%-: bb.allergies[i].date_range.end | hl7Date %> />
                                        </effectiveTime>
                                        <entryRelationship typeCode="SUBJ">
                                            <observation classCode="OBS" moodCode="EVN">
                                                <!-- allergy observation template -->
                                                <templateId root="2.16.840.1.113883.10.20.22.4.7"/>
                                                <id root="4adc1020-7b14-11db-9fe1-0800200c9a66"/>
                                                <code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4" />
                                                <statusCode code="completed"/>
                                                <effectiveTime>
                                                    <low <%-: bb.allergies[i].date_range.start | hl7Date %> />
                                                </effectiveTime>
                                                <value xsi:type="CD" <%-: bb.allergies[i].reaction_type | hl7Code %> >
                                                </value>
                                                <participant typeCode="CSM">
                                                    <participantRole classCode="MANU">
                                                        <playingEntity classCode="MMAT">
                                                            <code <%-: bb.allergies[i].allergen | hl7Code %> >
                                                            </code>
                                                        </playingEntity>
                                                    </participantRole>
                                                </participant>
                                                <% if (bb.allergies[i].status) { -%>
                                                    <entryRelationship typeCode="SUBJ" inversionInd="true">
                                                        <observation classCode="OBS" moodCode="EVN">
                                                            <templateId root="2.16.840.1.113883.10.20.22.4.28"/>
                                                            <!-- Alert status observation template -->
                                                            <code code="33999-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Status"/>
                                                            <statusCode code="completed"/>
                                                            <value xsi:type="CE" code="55561003" codeSystem="2.16.840.1.113883.6.96" displayName="<%= bb.allergies[i].status %>"/>
                                                        </observation>
                                                    </entryRelationship>
                                                <%} -%>
                                                <entryRelationship typeCode="MFST" inversionInd="true">
                                                    <observation classCode="OBS" moodCode="EVN">
                                                        <templateId root="2.16.840.1.113883.10.20.22.4.9"/>
                                                        <!-- Reaction observation template -->
                                                        <id root="4adc1020-7b14-11db-9fe1-0800200c9a64"/>
                                                        <code nullFlavor="NA"/>
                                                        <statusCode code="completed"/>
                                                        <effectiveTime>
                                                            <low <%-: bb.allergies[i].date_range.start | hl7Date %> />
                                                        </effectiveTime>
                                                        <value xsi:type="CD" <%-: bb.allergies[i].reaction | hl7Code %> />
                                                    </observation>
                                                </entryRelationship>
                                                <% if (bb.allergies[i].severity) {%>
                                                    <entryRelationship typeCode="SUBJ" inversionInd="true">
                                                        <observation classCode="OBS" moodCode="EVN">
                                                            <templateId root="2.16.840.1.113883.10.20.22.4.8"/>
                                                            <!-- ** Severity observation template ** -->
                                                            <code code="SEV" displayName="Severity Observation" codeSystem="2.16.840.1.113883.5.4" codeSystemName="ActCode"/>
                                                            <statusCode code="completed"/>
                                                            <value xsi:type="CD" displayName="<%= bb.allergies[i].severity %>" nullFlavor="UNK" />
                                                        </observation>
                                                    </entryRelationship>
                                                <%} %>
                                            </observation>
                                        </entryRelationship>
                                    </act>
                                </entry>

                            <% } %>
                        <% } else { %>

                            <entry typeCode="DRIV">
                              <act classCode="ACT" moodCode="EVN">
                                <!-- ** Allergy problem act ** -->
                                <templateId root="2.16.840.1.113883.10.20.22.4.30" />
                                <id root="6208ef0f-7750-1115-8cf9-b6ea1d0d0a66" />
                                <code code="48765-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Allergies, adverse reactions, alerts" />
                                <statusCode code="completed" />
                                <effectiveTime>
                                  <low nullFlavor="NA" />
                                  <high nullFlavor="NA" />
                                </effectiveTime>
                                <entryRelationship typeCode="SUBJ" inversionInd="true">
                                  <observation classCode="OBS" moodCode="EVN" negationInd="true">
                                    <!-- ** Allergy observation ** -->
                                    <templateId root="2.16.840.1.113883.10.20.22.4.7" />
                                    <id root="434c9b5a-e514-46bb-91b5-032ca579efec" />
                                    <code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4" />
                                    <statusCode code="completed" />
                                    <effectiveTime>
                                      <low nullFlavor="NA" />
                                      <high nullFlavor="NA" />
                                    </effectiveTime>
                                    <value xsi:type="CD" code="419511003" displayName="Propensity to adverse reactions to drug" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"></value>
                                    <participant typeCode="CSM">
                                      <participantRole classCode="MANU">
                                        <playingEntity classCode="MMAT">
                                          <code nullFlavor="NI" />
                                        </playingEntity>
                                      </participantRole>
                                    </participant>
                                  </observation>
                                </entryRelationship>
                              </act>
                            </entry>

                        <% } %>

                    </section>
                </component>

            <!--
            ********************************************************

            PLAN OF CARE
            (This section is optimized for its unstructured data, not its structured data)

            ********************************************************
            -->
            <component>
                <section>
                    <templateId root = "2.16.840.1.113883.10.20.22.2.10"/>
                    <code code = "18776-5" codeSystem = "2.16.840.1.113883.6.1" codeSystemName = "LOINC" displayName = "Treatment plan"/>
                    <title>Plan of Care</title>
                    <text>
                        <% if ("care_plan" in bb && bb.care_plan.length) { %>
                            <table>
                                <thead>
                                    <tr>
                                        <th>Details</th>
                                        <th>Name</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <% for (var i=0; i<bb.care_plan.length; i++) { %>
                                        <tr>
                                            <td><%=: bb.care_plan[i].text | emptyStringIfFalsy %></td>
                                            <td><%=: bb.care_plan[i].name | emptyStringIfFalsy %></td>
                                        </tr>
                                    <% } %>
                                </tbody>
                            </table>
                        <% } %>

                    </text>

                    <% if ("care_plan" in bb && bb.care_plan.length) { %>
                        <% for (var i=0; i<bb.care_plan.length; i++) { %>
                            
                            <% if (bb.care_plan[i].name.toLowerCase() == 'future appointment') { %>
                                <entry>
                                    <encounter moodCode = "INT" classCode = "ENC">
                                        <templateId root = "2.16.840.1.113883.10.20.22.4.40"/>
                                        <id root = "d9a4ab89-3fdc-48ed-8f35-43ec0a053a7b"/>
                                        <% if (bb.care_plan[i].text) { %>
                                            <text><%= bb.care_plan[i].text %></text>
                                        <% } else { %>
                                            <text></text>
                                        <% } %>
                                    </encounter>
                                </entry>
                            <% } else { %>
                                <entry>
                                    <act classCode = "ACT" moodCode = "INT">
                                        <templateId root = "2.16.840.1.113883.10.20.22.4.20"/>
                                        <code <%-: bb.care_plan[i] | hl7Code %> />
                                        <% if (bb.care_plan[i].text) { %>
                                            <text><%= bb.care_plan[i].text %></text>
                                        <% } else { %>
                                            <text></text>
                                        <% } %>
                                        <statusCode code = "completed"/>
                                    </act>
                                </entry>
                            <% } %>

                        <% } %>
                    <% } %>

                </section>
            </component>

            <!--
            ********************************************************

            INSTRUCTIONS
            (This section is optimized for its unstructured data, not its structured data)

            ********************************************************
            -->
            <component>
                <section>
                    <templateId root = "2.16.840.1.113883.10.20.22.2.45"/>
                    <code code = "69730-0" codeSystem = "2.16.840.1.113883.6.1" codeSystemName = "LOINC" displayName = "INSTRUCTIONS"/>
                    <title>Instructions</title>
                    <text>
                        <% if ("instructions" in bb && bb.instructions.length) { %>
                            <table>
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Text</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <% for (var i=0; i<bb.instructions.length; i++) { %>
                                        <tr>
                                            <td><%=: bb.instructions[i].name | emptyStringIfFalsy %></td>
                                            <td><%=: bb.instructions[i].text | emptyStringIfFalsy %></td>
                                        </tr>
                                    <% } %>
                                </tbody>
                            </table>
                        <% } %>

                    </text>

                    <% if ("instructions" in bb && bb.instructions.length) { %>
                        <% for (var i=0; i<bb.instructions.length; i++) { %>
                            
                            <entry>
                                <act classCode = "ACT" moodCode = "INT">
                                    <templateId root = "2.16.840.1.113883.10.20.22.4.20"/>
                                    <code <%-: bb.instructions[i] | hl7Code %> />
                                    <% if (bb.instructions[i].text) { %>
                                        <text><%= bb.instructions[i].text %></text>
                                    <% } else { %>
                                        <text></text>
                                    <% } %>
                                    <statusCode code = "completed"/>
                                </act>
                            </entry>

                        <% } %>
                    <% } %>
                </section>
            </component>

            <!--
            ********************************************************

            FUNCTIONAL STATUS

            ********************************************************
            -->
            <component>
                <section>
                    <templateId
                      root="2.16.840.1.113883.10.20.22.2.14"/>
                    <!--  ******** Functional status section template   ******** -->
                    <code
                      code="47420-5"
                      codeSystem="2.16.840.1.113883.6.1"/>
                    <title>Functional Status</title>
                    <text>
                        <% if ("functional_statuses" in bb && bb.functional_statuses.length) { -%>
                            <table>
                                <thead>
                                    <tr>
                                        <th>Condition</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <% for (var i=0; i<bb.functional_statuses.length; i++) { -%>
                                        <tr>
                                            <td><%=: bb.functional_statuses[i].name | emptyStringIfFalsy %></td>
                                            <td><%=: bb.functional_statuses[i].date | emptyStringIfFalsy %></td>
                                        </tr>
                                    <% } -%>
                                </tbody>
                            </table>
                        <% } -%>
                    </text>
                    <% if ("functional_statuses" in bb) { -%>
                        <% for (var i=0; i<bb.functional_statuses.length; i++) { -%>
                       
                            <entry typeCode = "DRIV">
                                <observation classCode = "OBS" moodCode = "EVN">
                                    <templateId root="2.16.840.1.113883.10.20.22.4.68"/>
                                    <id root="ab1791b0-5c71-11db-b0de-0800200c9a66"/>
                                    <code nullFlavor="UNK" />
                                    <statusCode code = "completed"/>
                                    <effectiveTime>
                                        <low <%-: bb.functional_statuses[i].date | hl7Date %> />
                                    </effectiveTime>
                                    <value xsi:type="CD" <%-: bb.functional_statuses[i] | hl7Code %> />
                                </observation>
                            </entry>

                       <% } -%>
                   <% } -%>
                </section>
            </component>

            <!--
            ********************************************************
            
            REASON FOR REFERRAL
            
            ********************************************************
            -->
            <component>
                <section>
                   <templateId
                      root="1.3.6.1.4.1.19376.1.5.3.1.3.1"/>
                   <!-- ** Reason for Referral Section Template ** -->
                   <code
                      codeSystem="2.16.840.1.113883.6.1"
                      codeSystemName="LOINC"
                      code="42349-1"
                      displayName="REASON FOR REFERRAL"/>
                   <title>Reason for Referral</title>
                   <!-- Unstructured text field -->
                   <text></text>
                </section>
            </component>

            <!-- 
            ************************************
            
            HOSPITAL DISCHARGE INSTRUCTIONS
            
            ************************************ 
            -->
                <component>
                    <section>
                       <templateId
                          root="2.16.840.1.113883.10.20.22.2.41"/>
                       <code
                          code="8653-8"
                          codeSystem="2.16.840.1.113883.6.1"
                          codeSystemName="LOINC"
                          displayName="HOSPITAL DISCHARGE INSTRUCTIONS"/>
                       <title>Hospital Discharge Instructions</title>
                       <!-- Unstructured text field -->
                       <text></text>
                    </section>
                </component>


            <!-- 
            ************************************
            
            CHIEF COMPLAINT / REASON
            
            ************************************ 
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.13"/>
                        <code code="46239-0"
                              codeSystem="2.16.840.1.113883.6.1"
                              codeSystemName="LOINC"
                              displayName="CHIEF COMPLAINT AND REASON FOR VISIT"/>
                        <title>Chief Complaint</title>
                        <% if (bb.chief_complaint && bb.chief_complaint.text) { %>
                            <text><%=: bb.chief_complaint.text %></text>
                        <% } else { %>
                            <text></text>
                        <% } %>
                      </section>
                </component>


            <% /* Note this key is not yet part of our Parsers... it didn't seem very useful */
               if ("visit_medications" in bb && bb.visit_medications.length) { -%>
                <!--
                ********************************************************

                MEDICATIONS ADMINISTERED DURING VISIT

                ********************************************************
                -->
                    
                    <component>
                        <section>
                            <templateId root = "2.16.840.1.113883.10.20.22.2.38"/>
                            <code code = "29549-3" codeSystem = "2.16.840.1.113883.6.1" codeSystemName = "LOINC" displayName = "Medications Administered"/>
                            <title>Medications Administered During Visit</title>
                            <text>
                                
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Medication</th>
                                            <th>Administration Date</th>
                                            <th>Notes</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.visit_medications.length; i++) { %>
                                            <tr>
                                                <td><%=: bb.visit_medications[i].product.name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.visit_medications[i].date_range.start | emptyStringIfFalsy %></td>
                                                <td><%=: bb.visit_medications[i].text | emptyStringIfFalsy %></td>
                                            </tr>
                                        <% } %>
                                    </tbody>
                                </table>
                            </text>

                            <% for (var i=0; i<bb.visit_medications.length; i++) { %>

                                <entry typeCode="DRIV">
                                    <substanceAdministration classCode="SBADM" moodCode="EVN">
                                        <templateId root="2.16.840.1.113883.10.20.22.4.16"/>
                                        <!-- ** MEDICATION ACTIVITY -->
                                        <id root="cdbd33f0-6cde-11db-9fe1-0800200c9a66"/>
                                        <% if (bb.visit_medications[i].text) { %>
                                            <text><%=: bb.visit_medications[i].text %></text>
                                        <% } else { %>
                                            <text></text>
                                        <% } %>
                                        <statusCode code="completed"/>
                                        <effectiveTime xsi:type="IVL_TS">
                                            <low <%-: bb.visit_medications[i].date_range.start | hl7Date %> />
                                            <high nullFlavor="NI" />
                                        </effectiveTime>
                                        <routeCode <%-: bb.visit_medications[i].route | hl7Code %> />
                                        <% if (bb.visit_medications[i].dose_quantity.value) { %>
                                            <doseQuantity value="<%= bb.visit_medications[i].dose_quantity.value %>" <% if (bb.visit_medications[i].dose_quantity.unit) { %> unit="<%= bb.visit_medications[i].dose_quantity.unit %>" <% } %> />
                                        <%} %>
                                        <% if (bb.visit_medications[i].rate_quantity.value) { %>
                                            <rateQuantity value="<%= bb.visit_medications[i].rate_quantity.value %>" unit="<%= bb.visit_medications[i].rate_quantity.unit %>"/>
                                        <%} %>
                                        <maxDoseQuantity nullFlavor="UNK">
                                            <numerator nullFlavor="UNK"/>
                                            <denominator nullFlavor="UNK"/>
                                        </maxDoseQuantity>
                                        <administrationUnitCode <%-: bb.visit_medications[i].administration | hl7Code %> />
                                        <consumable>
                                            <manufacturedProduct classCode="MANU">
                                                <templateId root="2.16.840.1.113883.10.20.22.4.23"/>
                                                <id nullFlavor="UNK" />
                                                <manufacturedMaterial>
                                                    <code <%-: bb.visit_medications[i].product | hl7Code %> >
                                                        <translation <%-: bb.visit_medications[i].product.translation | hl7Code %>/>
                                                    </code>
                                                </manufacturedMaterial>
                                                <manufacturerOrganization/>
                                            </manufacturedProduct>
                                        </consumable>
                                    </substanceAdministration>
                                </entry>

                            <% } %>

                        </section>
                    </component>
            <% } %>

            <!--
            ********************************************************

            MEDICATIONS

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.1.1"/>
                        <code code="10160-0" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="HISTORY OF MEDICATION USE"/>
                        <title>Medications</title>
                        <text>
                            <% if ("medications" in bb && bb.medications.length) { %>
                                <table>
                                    <thead>
                                        <tr>
                                           <th>Medication</th>
                                           <th>Notes</th>
                                           <th>Start Date</th>
                                           <th>End Date</th>
                                           <th>Reason</th>
                                           <th>Prescriber</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.medications.length; i++) { %>
                                            <tr>
                                                <td><%=: bb.medications[i].product.name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.medications[i].text | emptyStringIfFalsy %></td>
                                                <td><%=: bb.medications[i].date_range.start | emptyStringIfFalsy %></td>
                                                <td><%=: bb.medications[i].date_range.end | emptyStringIfFalsy %></td>
                                                <td><%=: bb.medications[i].reason.name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.medications[i].prescriber.person ? bb.medications[i].prescriber.person.name : '' %></td>
                                            </tr>
                                        <% } %>
                                    </tbody>
                                </table>
                            <% } else { %>
                                No medications data provided.
                            <% } %>
                        </text>

                        <% if ("medications" in bb && bb.medications.length) { %>
                            <% for (var i=0; i<bb.medications.length; i++) { %>

                                <entry typeCode="DRIV">
                                    <substanceAdministration classCode="SBADM" moodCode="EVN">
                                        <templateId root="2.16.840.1.113883.10.20.22.4.16"/>
                                        <!-- ** MEDICATION ACTIVITY -->
                                        <id root="cdbd33f0-6cde-11db-9fe1-0800200c9a66"/>
                                        <% if (bb.medications[i].text) { %>
                                            <text><%=: bb.medications[i].text %></text>
                                        <% } else { %>
                                            <text></text>
                                        <% } %>
                                        <statusCode code="completed"/>
                                        <effectiveTime xsi:type="IVL_TS">
                                            <low <%-: bb.medications[i].date_range.start | hl7Date %> />
                                            <high <%-: bb.medications[i].date_range.end | hl7Date %> />
                                        </effectiveTime>
                                        <% if (bb.medications[i].schedule && bb.medications[i].schedule.period_value && bb.medications[i].schedule.period_unit) { %>
                                            <effectiveTime xsi:type="PIVL_TS" institutionSpecified="true" operator="A">
                                                <period value="<%= bb.medications[i].schedule.period_value %>" unit="<%= bb.medications[i].schedule.period_unit %>"/>
                                            </effectiveTime>
                                        <% } %>
                                        <routeCode <%-: bb.medications[i].route | hl7Code %> />
                                        <% if (bb.medications[i].dose_quantity.value) { %>
                                            <doseQuantity value="<%= bb.medications[i].dose_quantity.value %>" <% if (bb.medications[i].dose_quantity.unit) { %> unit="<%= bb.medications[i].dose_quantity.unit %>" <% } %> />
                                        <%} %>
                                        <% if (bb.medications[i].rate_quantity.value) { %>
                                            <rateQuantity value="<%= bb.medications[i].rate_quantity.value %>" unit="<%= bb.medications[i].rate_quantity.unit %>"/>
                                        <%} %>
                                        <maxDoseQuantity nullFlavor="UNK">
                                            <numerator nullFlavor="UNK"/>
                                            <denominator nullFlavor="UNK"/>
                                        </maxDoseQuantity>
                                        <administrationUnitCode <%-: bb.medications[i].administration | hl7Code %> />
                                        <consumable>
                                            <manufacturedProduct classCode="MANU">
                                                <templateId root="2.16.840.1.113883.10.20.22.4.23"/>
                                                <id nullFlavor="UNK" />
                                                <manufacturedMaterial>
                                                    <code <%-: bb.medications[i].product | hl7Code %> >
                                                        <translation <%-: bb.medications[i].product.translation | hl7Code %>/>
                                                        <% if (bb.medications[i].product.text) { %>
                                                            <originalText><%= bb.medications[i].product.text %></originalText>
                                                        <% } %>
                                                    </code>
                                                </manufacturedMaterial>
                                                <manufacturerOrganization/>
                                            </manufacturedProduct>
                                        </consumable>
                                        <% if (bb.medications[i].vehicle.name) { -%>
                                            <participant typeCode="CSM">
                                               <participantRole classCode="MANU">
                                                  <templateId root="2.16.840.1.113883.10.20.22.4.24"/>
                                                  <code code="412307009" displayName="drug vehicle" codeSystem="2.16.840.1.113883.6.96"/>
                                                  <playingEntity classCode="MMAT">
                                                     <code <%-: bb.medications[i].vehicle | hl7Code %> />
                                                     <name><%= bb.medications[i].vehicle.name %></name>
                                                  </playingEntity>
                                               </participantRole>
                                            </participant>
                                        <% } %>
                                        <entryRelationship typeCode="RSON">
                                            <observation classCode="OBS" moodCode="EVN">
                                                <templateId root="2.16.840.1.113883.10.20.22.4.19"/>
                                                <id root="db734647-fc99-424c-a864-7e3cda82e703" extension="45665"/>
                                                <code code="404684003" displayName="Finding" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>
                                                <statusCode code="completed"/>
                                                <value xsi:type="CE" <%-: bb.medications[i].reason | hl7Code %>/>
                                            </observation>
                                        </entryRelationship>
                                        <precondition typeCode="PRCN">
                                            <templateId root="2.16.840.1.113883.10.20.22.4.25"/>
                                            <criterion>
                                                <code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4"/>
                                                <value xsi:type="CE" <%-: bb.medications[i].precondition | hl7Code %>/>
                                            </criterion>
                                        </precondition>
                                    </substanceAdministration>
                                </entry>

                            <% } %>

                        <% } else { %>
                            <entry>
                              <substanceAdministration moodCode="EVN" classCode="SBADM" negationInd="true">
                                <!-- ** Medication activity ** -->
                                <templateId root="2.16.840.1.113883.10.20.22.4.16" />
                                <id root="37c20f19-f327-b5cc-3a5d-0587eb9deb3f" />
                                <statusCode code="completed" />
                                <effectiveTime xsi:type="IVL_TS">
                                  <low nullFlavor="NA" />
                                  <high nullFlavor="NA" />
                                </effectiveTime>
                                <consumable>
                                  <manufacturedProduct classCode="MANU">
                                    <!-- ** Medication information ** -->
                                    <templateId root="2.16.840.1.113883.10.20.22.4.23" />
                                    <id root="70260742-c295-154c-4e2e-9f68b1a7397f" />
                                    <manufacturedMaterial>
                                      <code nullFlavor="NI" />
                                    </manufacturedMaterial>
                                  </manufacturedProduct>
                                </consumable>
                              </substanceAdministration>
                            </entry>
                        <% } %>

                    </section>
                </component>
            

            <!--
            ********************************************************

            PROBLEM LIST

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.5.1"/>
                        <code code="11450-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="PROBLEM LIST"/>
                        <title>Problems</title>
                        <text>
                            <% if ("problems" in bb && bb.problems.length) { %>
                                <table>
                                    <thead>
                                        <tr>
                                           <th>Problem</th>
                                           <th>Code</th>
                                           <th>Code System</th>
                                           <th>Start Date</th>
                                           <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.problems.length; i++) { %>
                                            <tr>
                                                <td><%=: bb.problems[i].name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.problems[i].code | emptyStringIfFalsy %></td>
                                                <td><%=: bb.problems[i].code_system_name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.problems[i].date_range.start | emptyStringIfFalsy %></td>
                                                <td><%=: bb.problems[i].status | emptyStringIfFalsy %></td>
                                            </tr>
                                        <% } %>
                                    </tbody>
                                </table>
                            <% } else { %>
                                No problems data provided.
                            <% } %>
                        </text>

                        <% if ("problems" in bb && bb.problems.length) { %>
                            <% for (var i=0; i<bb.problems.length; i++) { %>

                                <entry typeCode="DRIV">
                                    <act classCode="ACT" moodCode="EVN">
                                        <!-- Problem act template -->
                                        <templateId root="2.16.840.1.113883.10.20.22.4.3"/>
                                        <id root="ec8a6ff8-ed4b-4f7e-82c3-e98e58b45de7"/>
                                        <code nullFlavor="NA"/>
                                        <statusCode code="completed"/>
                                        <effectiveTime>
                                            <low <%-: bb.problems[i].date_range.start | hl7Date %> />
                                            <high <%-: bb.problems[i].date_range.end | hl7Date %> />
                                        </effectiveTime>
                                        <entryRelationship typeCode="SUBJ">
                                            <observation classCode="OBS" moodCode="EVN">
                                                <!-- Problem observation template -->
                                                <templateId root="2.16.840.1.113883.10.20.22.4.4"/>
                                                <id root="ab1791b0-5c71-11db-b0de-0800200c9a66"/>
                                                <code code="409586006" codeSystem="2.16.840.1.113883.6.96" displayName="Complaint"/>
                                                <statusCode code="completed"/>
                                                <effectiveTime>
                                                    <low <%-: bb.problems[i].date_range.start | hl7Date %> />
                                                </effectiveTime>
                                                <value xsi:type="CD" <%-: bb.problems[i] | hl7Code %> >
                                                    <% if (bb.problems[i].translation && bb.problems[i].translation.code) { -%>
                                                        <translation <%-: bb.problems[i].translation | hl7Code %> />
                                                    <% } -%>
                                                </value>
                                                <entryRelationship typeCode="REFR">
                                                    <observation classCode="OBS" moodCode="EVN">
                                                        <!-- Problem status observation template -->
                                                        <templateId root="2.16.840.1.113883.10.20.22.4.6"/>
                                                        <code code="33999-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="Status"/>
                                                        <statusCode code="completed"/>
                                                        <value xsi:type="CD" code="<%=: codes.reverseProblemStatus(bb.problems[i].status) %>" codeSystem="2.16.840.1.113883.6.96" displayName="<%= bb.problems[i].status %>" codeSystemName="SNOMED CT"/>
                                                    </observation>
                                                </entryRelationship>
                                                <% if (bb.problems[i].age) { -%>
                                                    <entryRelationship typeCode="SUBJ" inversionInd="true">
                                                       <observation classCode="OBS" moodCode="EVN">
                                                          <templateId root="2.16.840.1.113883.10.20.22.4.31"/>
                                                          <!-- Age observation template   -->
                                                          <code code="445518008" codeSystem="2.16.840.1.113883.6.96" displayName="Age At Onset"/>
                                                          <statusCode code="completed"/>
                                                          <value xsi:type="PQ" value="<%= bb.problems[i].age %>" unit="a"/>
                                                       </observation>
                                                    </entryRelationship>
                                                <% } %>
                                            </observation>
                                        </entryRelationship>
                                    </act>
                                </entry>

                            <% } %>
                        <% } else { %>

                            <entry typeCode="DRIV">
                              <act classCode="ACT" moodCode="EVN">
                                <!-- ** Problem concern act ** -->
                                <templateId root="2.16.840.1.113883.10.20.22.4.3" />
                                <id root="6b51d431-df5d-f141-bece-cf79edf3dd86" />
                                <code code="CONC" codeSystem="2.16.840.1.113883.5.6" displayName="Concern" />
                                <statusCode code="completed" />
                                <effectiveTime>
                                  <low nullFlavor="NA" />
                                  <high nullFlavor="NA" />
                                </effectiveTime>
                                <entryRelationship typeCode="SUBJ">
                                  <observation classCode="OBS" moodCode="EVN" negationInd="true">
                                    <!-- Problem Observation template -->
                                    <templateId root="2.16.840.1.113883.10.20.22.4.4" />
                                    <id root="73475cb4-0a56-e8da-a045-ed110137e159" />
                                    <code code="ASSERTION" codeSystem="2.16.840.1.113883.5.4" codeSystemName="HL7ActCode" />
                                    <statusCode code="completed" />
                                    <value xsi:type="CD" code="55607006" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Problem" />
                                  </observation>
                                </entryRelationship>
                              </act>
                            </entry>

                        <% } %>

                    </section>
                </component>
            

            <!--
            ********************************************************

            PROCEDURES

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.7.1"/>
                        <!-- Procedures section template -->
                        <code code="47519-4" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="PROCEDURES"/>
                        <title>Procedures</title>
                        <text>
                            <% if ("procedures" in bb && bb.procedures.length) { %>
                                <table>
                                    <thead>
                                        <tr>
                                           <th>Procedure</th>
                                           <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.procedures.length; i++) { %>
                                            <tr>
                                                <td><%=: bb.procedures[i].name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.procedures[i].date | emptyStringIfFalsy %></td>
                                            </tr>
                                        <% } %>
                                    </tbody>
                                </table>
                            <% } else { %>
                                No procedures data provided.
                            <% } %>
                        </text>

                        <% if ("procedures" in bb && bb.procedures.length) { %>
                            <% for (var i=0; i<bb.procedures.length; i++) { %>

                                <entry>
                                    <observation classCode="OBS" moodCode="EVN">
                                        <templateId root="2.16.840.1.113883.10.20.22.4.13"/>
                                        <!-- ***** Procedure  Activity Procedure Template ***** -->
                                        <id root="d68b7e32-7810-4f5b-9cc2-acd54b0fd85d"/>
                                        <code <%-: bb.procedures[i] | hl7Code %> />
                                        <statusCode code="completed"/>
                                        <effectiveTime <%-: bb.procedures[i].date | hl7Date %> />
                                        <value xsi:type = "CD"/>
                                        <methodCode nullFlavor="UNK"/>
                                    </observation>
                                </entry>

                            <% } %>
                        
                        <% } else { %>

                            <entry>
                              <act classCode="ACT" moodCode="INT">
                                <!-- Procedure activity act -->
                                <templateId root="2.16.840.1.113883.10.20.22.4.12" />
                                <id root="d6061bbe-e6cf-3bd7-765f-aea7cdd0af13" />
                                <code nullFlavor="NI" />
                                <statusCode code="completed" />
                                <effectiveTime nullFlavor="NA" />
                              </act>
                            </entry>

                        <% } %>

                    </section>
                </component>
            

            <!--
            ********************************************************

            RESULTS / LABS

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.3.1"/>
                        <code code="30954-2" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="RESULTS"/>
                        <title>Results</title>
                        <text>
                            <% if ("results" in bb && bb.results.length) { %>
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Panel Name</th>
                                            <th>Test Name</th>
                                            <th>Value</th>
                                            <th>Unit</th>
                                            <th>Reference Range</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.results.length; i++) { %>
                                            <% for (var j=0; j<bb.results[i].tests.length; j++) { %>
                                                <tr>
                                                    <td><%=bb.results[i].name %></td>
                                                    <td><%=bb.results[i].tests[j].name %></td>
                                                    <td><% if (bb.results[i].tests[j].value) { %><%=bb.results[i].tests[j].value %><% } else { %>unknown<% } %></td>
                                                    <td><%=bb.results[i].tests[j].unit %></td>
                                                    <% if ( bb.results[i].tests[j].reference_range.low_value &&
                                                            bb.results[i].tests[j].reference_range.high_value ) { -%>
                                                        <td><%=bb.results[i].tests[j].reference_range.low_value %> to <%=bb.results[i].tests[j].reference_range.high_value %></td>
                                                    <% } else { -%>
                                                        <td></td>
                                                    <% } %>
                                                    <td><%=bb.results[i].tests[j].date %></td>
                                                </tr>
                                            <% } %>
                                        <% } %>
                                    </tbody>
                                </table>
                            <% } else { %>
                                No lab results data provided.
                            <% } %>
                        </text>

                        <% if ("results" in bb && bb.results.length) { %>
                            <% for (var i=0; i<bb.results.length; i++) { %>


                            <entry typeCode="DRIV">
                                <organizer classCode="BATTERY" moodCode="EVN">
                                    <!-- Result organizer template -->
                                    <templateId root="2.16.840.1.113883.10.20.22.4.1"/>
                                    <id root="7d5a02b0-67a4-11db-bd13-0800200c9a66"/>
                                    <code <%-: bb.results[i] | hl7Code %> />
                                    <statusCode code="completed"/>

                                    <% for (var j=0; j<bb.results[i].tests.length; j++) { %>


                                    <component>
                                        <observation classCode="OBS" moodCode="EVN">
                                            <!-- Result observation template -->
                                            <templateId root="2.16.840.1.113883.10.20.22.4.2"/>
                                            <id root="107c2dc0-67a5-11db-bd13-0800200c9a66"/>
                                            <code <%-: bb.results[i].tests[j] | hl7Code %> >
                                                <% if (bb.results[i].tests[j].translation && bb.results[i].tests[j].translation.code) { -%>
                                                    <translation <%-: bb.results[i].tests[j].translation | hl7Code %> />
                                                <% } -%>
                                            </code>
                                            <statusCode code="completed"/>
                                            <effectiveTime <%-: bb.results[i].tests[j].date | hl7Date %> />
                                            <% if (bb.results[i].tests[j].value) { %>
                                                <value
                                                    <% if (bb.results[i].tests[j].unit) { %>
                                                        xsi:type="PQ"
                                                        value="<%=bb.results[i].tests[j].value%>"
                                                        <% if (bb.results[i].tests[j].unit) { %> unit="<%=bb.results[i].tests[j].unit%>" <% } %>
                                                    <%} else { %>
                                                        xsi:type="ST"
                                                        value="<%=bb.results[i].tests[j].value%>"
                                                    <% } %>
                                                />
                                            <%} else { %>
                                                <value xsi:type="PQ" nullFlavor="UNK" />
                                            <%} %>
                                            <interpretationCode code="N" codeSystem="2.16.840.1.113883.5.83"/>
                                            <methodCode/>
                                            <targetSiteCode/>
                                            <referenceRange>
                                                <observationRange>
                                                    <% if (bb.results[i].tests[j].reference_range.text) { -%>
                                                        <text><%= bb.results[i].tests[j].reference_range.text %></text>
                                                    <% } else if (bb.results[i].tests[j].reference_range.low_value &&
                                                                bb.results[i].tests[j].reference_range.high_value) { -%>
                                                        <value xsi:type="IVL_PQ">
                                                           <low value="<%= bb.results[i].tests[j].reference_range.low_value %>"
                                                                unit="<%= bb.results[i].tests[j].reference_range.low_unit %>"/>
                                                           <high value="<%= bb.results[i].tests[j].reference_range.high_value %>"
                                                                unit="<%= bb.results[i].tests[j].reference_range.high_unit %>"/>
                                                        </value>
                                                    <% } -%>
                                                </observationRange>
                                            </referenceRange>
                                        </observation>
                                    </component>


                                    <% } %>

                                </organizer>
                            </entry>

                            <% } %>
                        <% } else { %>

                            <entry>
                               <organizer classCode="BATTERY" moodCode="EVN">
                                  <templateId root="2.16.840.1.113883.10.20.22.4.1"/>
                                  <id nullFlavor="NI"/>
                                  <code code="CONC" codeSystem="2.16.840.1.113883.5.6"/>
                                  <statusCode code="completed"/>
                                  <effectiveTime>
                                     <low nullFlavor="UNK"/>
                                  </effectiveTime>
                                  <component>
                                     <observation classCode="OBS" moodCode="EVN">
                                        <templateId root="2.16.840.1.113883.10.20.22.4.2"/>
                                        <id nullFlavor="NI"/>
                                        <code nullFlavor="NI"/>
                                        <statusCode code="completed"/>
                                        <effectiveTime>
                                           <low nullFlavor="UNK"/>
                                        </effectiveTime>
                                        <value nullFlavor="NI" xsi:type="ST"/>
                                     </observation>
                                  </component>
                               </organizer>
                            </entry>

                        <% } %>

                    </section>
                </component>


            <!--
            ********************************************************

            ENCOUNTERS

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.22"/>
                        <!-- Encounters Section - optional entries -->
                        <code code="46240-8" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="History of encounters"/>
                        <title>Encounters</title>
                        <text>
                            <% if ("encounters" in bb && bb.encounters.length) { -%>
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Encounter Diagnosis</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.encounters.length; i++) { -%>
                                            <% if (bb.encounters[i].findings.length) { -%>
                                                <% for (var j=0; j<bb.encounters[i].findings.length; j++) { -%>
                                                    <tr>
                                                        <td><%=: bb.encounters[i].findings[j].name | emptyStringIfFalsy %></td>
                                                        <td><%=: bb.encounters[i].date | emptyStringIfFalsy %></td>
                                                    </tr>
                                                <% } -%>
                                            <% } else { -%>
                                                <tr>
                                                    <td>None</td>
                                                    <td><%=: bb.encounters[i].date | emptyStringIfFalsy %></td>
                                                </tr>
                                            <% } -%>
                                        <% } -%>
                                    </tbody>
                                </table>
                            <% } else { -%>
                                No encounters data provided.
                            <% } -%>
                        </text>

                        <% if ("encounters" in bb) { %>
                            <% for (var i=0; i<bb.encounters.length; i++) { %>

                                <entry typeCode="DRIV">
                                    <encounter classCode="ENC" moodCode="EVN">
                                        <templateId root="2.16.840.1.113883.10.20.22.4.49"/>
                                        <!-- Encounter Activities -->
                                        <!--  ********  Encounter activity template   ******** -->
                                        <id root="2a620155-9d11-439e-92b3-5d9815ff4de8"/>
                                        <code <%-: bb.encounters[i] | hl7Code %> <% if (bb.encounters[i].code_system_version) { %>codeSystemVersion="<%= bb.encounters[i].code_system_version %>"<% } %> >
                                            <% if (bb.encounters[i].translation && bb.encounters[i].translation.code) { -%>
                                                <translation <%-: bb.encounters[i].translation | hl7Code %> />
                                            <% } -%>
                                        </code>
                                        <effectiveTime <%-: bb.encounters[i].date | hl7Date %> />
                                        <performer>
                                            <assignedEntity>
                                                <id nullFlavor="UNK" />
                                                <code <%-: bb.encounters[i].performer | hl7Code %> />
                                            </assignedEntity>
                                        </performer>
                                        <% for (var j=0; j<bb.encounters[i].findings.length; j++) { -%>
                                            <entryRelationship typeCode="RSON">
                                                <observation classCode="OBS" moodCode="EVN">
                                                    <templateId root="2.16.840.1.113883.10.20.22.4.19"/>
                                                    <id root="db734647-fc99-424c-a864-7e3cda82e703" extension="45665"/>
                                                    <code code="404684003" displayName="Finding" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>
                                                    <statusCode code="completed"/>
                                                    <value xsi:type="CD" <%-: bb.encounters[i].findings[j] | hl7Code %> />
                                                </observation>
                                            </entryRelationship>
                                        <% } -%>
                                    </encounter>
                                </entry>

                            <% } %>
                        <% } %>
                    </section>
                </component>
            

            <!--
            ********************************************************

            IMMUNIZATIONS

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.2.1"/>
                        <!--  ********  Immunizations section template   ******** -->
                        <code code="11369-6" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="History of immunizations"/>
                        <title>Immunizations</title>
                        <text>
                            <% if ("immunizations" in bb && bb.immunizations.length) { %>
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Vaccine</th>
                                            <th>Code System</th>
                                            <th>Code</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.immunizations.length; i++) { %>
                                            <tr>
                                                <td><%=: bb.immunizations[i].product.name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.immunizations[i].product.code_system_name | emptyStringIfFalsy %></td>
                                                <td><%=: bb.immunizations[i].product.code | emptyStringIfFalsy %></td>
                                                <td><%=: bb.immunizations[i].date | emptyStringIfFalsy %></td>
                                            </tr>
                                        <% } %>
                                    </tbody>
                                </table>
                            <% } else { %>
                                No immunizations data provided.
                            <% } %>
                        </text>

                        <% if ("immunizations" in bb && bb.immunizations.length) { %>
                            <% for (var i=0; i<bb.immunizations.length; i++) { %>

                                <entry typeCode="DRIV">
                                    <substanceAdministration classCode="SBADM" moodCode="EVN" negationInd="false">
                                        <templateId root="2.16.840.1.113883.10.20.22.4.52"/>
                                        <!--  ********   Immunization activity template    ******** -->
                                        <id root="e6f1ba43-c0ed-4b9b-9f12-f435d8ad8f92"/>
                                        <statusCode code="completed"/>
                                        <effectiveTime xsi:type="IVL_TS" <%-: bb.immunizations[i].date | hl7Date %> />
                                        <routeCode <%-: bb.immunizations[i].route | hl7Code %> />
                                        <% if (bb.immunizations[i].dose_quantity.value) { -%>
                                            <doseQuantity value="<%= bb.immunizations[i].dose_quantity.value %>" unit="<%= bb.immunizations[i].dose_quantity.unit %>"/>
                                        <%} else { -%>
                                            <doseQuantity nullFlavor="UNK"/>
                                        <%} -%>
                                        <consumable>
                                            <manufacturedProduct classCode="MANU">
                                                <templateId root="2.16.840.1.113883.10.20.22.4.54"/>
                                                <!--  ********   Immunization Medication Information    ******** -->
                                                <manufacturedMaterial>
                                                    <code <%-: bb.immunizations[i].product | hl7Code %> >
                                                        <originalText>Influenza virus vaccine</originalText>
                                                        <translation <%-: bb.immunizations[i].product.translation | hl7Code %> />
                                                    </code>
                                                    <% if (bb.immunizations[i].product.lot_number) { -%>
                                                        <lotNumberText><%= bb.immunizations[i].product.lot_number %></lotNumberText>
                                                    <% } -%>
                                                </manufacturedMaterial>
                                                <% if (bb.immunizations[i].product.manufacturer_name) { -%>
                                                    <manufacturerOrganization>
                                                        <name><%= bb.immunizations[i].product.manufacturer_name %></name>
                                                    </manufacturerOrganization>
                                                <% } -%>
                                            </manufacturedProduct>
                                        </consumable>
                                        <entryRelationship typeCode="SUBJ" inversionInd="true">
                                            <act classCode="ACT" moodCode="INT">
                                                <templateId root="2.16.840.1.113883.10.20.22.4.20"/>
                                                <!-- ** Instructions Template ** -->
                                                <code <%-: bb.immunizations[i].education_type | hl7Code %> />
                                                <% if (bb.immunizations[i].instructions) { -%>
                                                    <text><%= bb.immunizations[i].instructions%></text>
                                                <% } -%>
                                                <statusCode code="completed"/>
                                            </act>
                                        </entryRelationship>
                                    </substanceAdministration>
                                </entry>

                            <% } %>
                        
                        <% } else { %>

                            <entry typeCode="DRIV">
                              <substanceAdministration moodCode="EVN" classCode="SBADM" negationInd="true">
                                <!-- ** Immunization activity ** -->
                                <templateId root="2.16.840.1.113883.10.20.22.4.52" />
                                <id root="d6a40317-3361-bb08-d0bf-794fcc9dbdcf" />
                                <statusCode code="completed" />
                                <effectiveTime nullFlavor="NA" />
                                <consumable>
                                  <manufacturedProduct classCode="MANU">
                                    <!-- ** Immunization medication information ** -->
                                    <templateId root="2.16.840.1.113883.10.20.22.4.54" />
                                    <manufacturedMaterial>
                                      <code nullFlavor="NI" />
                                    </manufacturedMaterial>
                                  </manufacturedProduct>
                                </consumable>
                              </substanceAdministration>
                            </entry>

                        <% } %>

                    </section>
                </component>
            

            <!--
            ********************************************************

            VITAL SIGNS

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root="2.16.840.1.113883.10.20.22.2.4"/>
                        <code code="8716-3" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC" displayName="VITAL SIGNS"/>
                        <title>Vital Signs</title>
                        <text>
                            <% if ("vitals" in bb && bb.vitals.length) { %>
                                <table>
                                    <thead>
                                        <tr>
                                           <th>Date</th>
                                           <th>Name</th>
                                           <th>Value</th>
                                           <th>Unit</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <% for (var i=0; i<bb.vitals.length; i++) { %>
                                            <% for (var j=0; j<bb.vitals[i].results.length;j++) {%>
                                                <tr>
                                                    <td><%=: bb.vitals[i].date | emptyStringIfFalsy %></td>
                                                    <td><%=: bb.vitals[i].results[j].name | emptyStringIfFalsy %></td>
                                                    <td><%=: bb.vitals[i].results[j].value | emptyStringIfFalsy %></td>
                                                    <td><%=: bb.vitals[i].results[j].unit | emptyStringIfFalsy %></td>
                                                </tr>
                                            <% } %>
                                        <% } %>
                                    </tbody>
                                </table>
                            <% } else { %>
                                No vital signs data provided.
                            <% } %>
                        </text>

                        <% if ("vitals" in bb && bb.vitals.length) { %>
                            <% for (var i=0; i<bb.vitals.length; i++) { %>
                                <% if (bb.vitals[i].results.length) { %>

                                    <entry typeCode="DRIV">
                                        <organizer classCode="CLUSTER" moodCode="EVN">
                                            <templateId root="2.16.840.1.113883.10.20.22.4.26"/>
                                            <!-- Vital signs organizer template -->
                                            <id root="c6f88320-67ad-11db-bd13-0800200c9a66"/>
                                            <code code="46680005" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Vital signs"/>
                                            <statusCode code="completed"/>
                                            <effectiveTime <%-: bb.vitals[i].date | hl7Date %> />

                                            <% for (var j=0; j<bb.vitals[i].results.length;j++) {%>
                                            <component>
                                                <observation classCode="OBS" moodCode="EVN">
                                                    <templateId root="2.16.840.1.113883.10.20.22.4.27"/>
                                                    <!-- Vital Sign Observation template -->
                                                    <id root="c6f88321-67ad-11db-bd13-0800200c9a66"/>
                                                    <code <%-: bb.vitals[i].results[j] | hl7Code %> />
                                                    <statusCode code="completed"/>
                                                    <effectiveTime <%-: bb.vitals[i].date | hl7Date %> />
                                                    <value xsi:type="PQ" value="<%=bb.vitals[i].results[j].value%>" unit="<%=bb.vitals[i].results[j].unit%>"/>
                                                    <interpretationCode code="N" codeSystem="2.16.840.1.113883.5.83"/>
                                                </observation>
                                            </component>
                                            <% } %>
                                            
                                        </organizer>
                                    </entry>

                                <% } %>
                            <% } %>
                        <% } %>
                    </section>
                </component>

            <!--
            ********************************************************

            SOCIAL HISTORY

            ********************************************************
            -->
                <component>
                    <section>
                        <templateId root = "2.16.840.1.113883.10.20.22.2.17"/>
                        <code code = "29762-2" codeSystem = "2.16.840.1.113883.6.1" displayName = "Social History"/>
                        <title>Social History</title>
                        <text>
                            <% if ("smoking_status" in bb && bb.smoking_status) { -%>
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Social History Element</th>
                                            <th>Description</th>
                                            <th>Code</th>
                                            <th>Effective Dates</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>Smoking Status</td>
                                            <td><%=: bb.smoking_status.name | emptyStringIfFalsy %></td>
                                            <td><%=: bb.smoking_status.code |emptyStringIfFalsy %></td>
                                            <td><%=: bb.smoking_status.date | emptyStringIfFalsy %></td>
                                        </tr>
                                    </tbody>
                                </table>
                            <% } else { -%>
                                No social history data provided.
                            <% } -%>
                        </text>
                        <entry typeCode = "DRIV">
                            <observation classCode = "OBS" moodCode = "EVN">
                                <templateId root = "2.16.840.1.113883.10.20.22.4.78"/>
                                <id root = "bb4029d5-cd10-437e-8985-6db6db5beb12"/>
                                <code code = "ASSERTION" codeSystem = "2.16.840.1.113883.5.4"/>
                                <statusCode code = "completed"/>
                                <effectiveTime>
                                    <low nullFlavor="UNK" />
                                </effectiveTime>
                                
                                <% if ("smoking_status" in bb && bb.smoking_status) { %>
                                    <value xsi:type="CD" <%-: bb.smoking_status | hl7Code %> />
                                <% } else { %>
                                    <value xsi:type="CD" nullFlavor="NASK" />
                                <% } %>
                            </observation>
                        </entry>
                    </section>
                </component>

            </structuredBody>
        </component>

</ClinicalDocument>