# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Group5to4'
/// name = 'Group5to4'
/// title = 'FML Conversion for Group: R5 to R4'
/// status = 'active'

conceptmap "GroupType" {
  prefix s = "http://hl7.org/fhir/group-type"
  prefix t = "http://hl7.org/fhir/4.0/group-type"

  s:person - t:person
  s:animal - t:animal
  s:practitioner - t:practitioner
  s:device - t:device
}

uses "http://hl7.org/fhir/StructureDefinition/Group" alias GroupR5 as source
uses "http://hl7.org/fhir/4.0/StructureDefinition/Group" alias GroupR4 as target

imports "http://hl7.org/fhir/StructureMap/*5to4"

group Group(source src : GroupR5, target tgt : GroupR4) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.active -> tgt.active;
  src.type as v -> tgt.type = translate(v, '#GroupType', 'code');
  src.code -> tgt.code; // src.membership as v -> tgt.membership = translate(v, '#group-membership-basis', 'code');
  src.name -> tgt.name;
  src.quantity -> tgt.quantity; // src.description -> tgt.description;
  src.managingEntity -> tgt.managingEntity;
  src.characteristic as s -> tgt.characteristic as t then GroupCharacteristic(s, t);
  src.member as s -> tgt.member as t then GroupMember(s, t);
}

group GroupCharacteristic(source src, target tgt) extends BackboneElement {
  src.code -> tgt.code;
  src.value : CodeableConcept -> tgt.value;
  src.value : boolean -> tgt.value;
  src.value : Quantity -> tgt.value;
  src.value : Range -> tgt.value;
  src.value : Reference -> tgt.value;
  src.exclude -> tgt.exclude;
  src.period -> tgt.period;
}

group GroupMember(source src, target tgt) extends BackboneElement {
  src.entity -> tgt.entity;
  src.period -> tgt.period;
  src.inactive -> tgt.inactive;
}

# entry[].resource.group[].rule[].documentation
src.membership as v -> tgt.membership = translate(v, '#group-membership-basis', 'code');

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Resource4to5'
/// name = 'Resource4to5'
/// title = 'FML Conversion for Resource: R4 to R5'
/// status = 'active'

uses "http://hl7.org/fhir/4.0/StructureDefinition/Resource" alias ResourceR4 as source
uses "http://hl7.org/fhir/StructureDefinition/Resource" alias ResourceR5 as target
uses "http://hl7.org/fhir/StructureDefinition/Base" alias BaseR5 as source

imports "http://hl7.org/fhir/StructureMap/*4to5"

group Resource(source src : ResourceR4, target tgt : ResourceR5) extends Base <<type+>> {
  src.id -> tgt.id;
  src.meta -> tgt.meta;
  src.implicitRules -> tgt.implicitRules;
  src.language -> tgt.language;
}

group Base(source src : BaseR5) {
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Communication4to5'
/// name = 'Communication4to5'
/// title = 'FML Conversion for Communication: R4 to R5'
/// status = 'active'

conceptmap "CommunicationPriority" {
  prefix s = "http://hl7.org/fhir/4.0/request-priority"
  prefix t = "http://hl7.org/fhir/request-priority"

  s:routine - t:routine
  s:urgent - t:urgent
  s:asap - t:asap
  s:stat - t:stat
}

conceptmap "CommunicationStatus" {
  prefix s = "http://hl7.org/fhir/4.0/event-status"
  prefix t = "http://hl7.org/fhir/event-status"

  s:preparation - t:preparation
  s:"in-progress" - t:"in-progress"
  s:"not-done" - t:"not-done"
  s:"on-hold" - t:"on-hold"
  s:stopped - t:stopped
  s:completed - t:completed
  s:"entered-in-error" - t:"entered-in-error"
  s:unknown - t:unknown
}

uses "http://hl7.org/fhir/4.0/StructureDefinition/Communication" alias CommunicationR4 as source
uses "http://hl7.org/fhir/StructureDefinition/Communication" alias CommunicationR5 as target

imports "http://hl7.org/fhir/StructureMap/*4to5"

group Communication(source src : CommunicationR4, target tgt : CommunicationR5) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.instantiatesCanonical -> tgt.instantiatesCanonical;
  src.instantiatesUri -> tgt.instantiatesUri;
  src.basedOn -> tgt.basedOn;
  src.partOf -> tgt.partOf;
  src.inResponseTo -> tgt.inResponseTo;
  src.status as v -> tgt.status = translate(v, '#CommunicationStatus', 'code');
  src.statusReason -> tgt.statusReason;
  src.category -> tgt.category;
  src.priority as v -> tgt.priority = translate(v, '#CommunicationPriority', 'code');
  src.medium -> tgt.medium;
  src.subject -> tgt.subject;
  src.topic -> tgt.topic;
  src.about -> tgt.about;
  src.encounter -> tgt.encounter;
  src.sent -> tgt.sent;
  src.received -> tgt.received;
  src.recipient -> tgt.recipient;
  src.sender -> tgt.sender;
  src.reasonCode -> tgt.reason;
  src.reasonReference -> tgt.reason;
  src.payload as s -> tgt.payload as t then CommunicationPayload(s, t);
  src.note -> tgt.note;
}

group CommunicationPayload(source src, target tgt) extends BackboneElement {
  src.content : Attachment -> tgt.content;
  src.content : Reference -> tgt.content;
  src.content : string -> tgt.content;
}

# entry[].resource.title
FML Conversion for Communication: R4 to R5

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Communication5to4'
/// name = 'Communication5to4'
/// title = 'FML Conversion for Communication: R5 to R4'
/// status = 'active'

conceptmap "CommunicationPriority" {
  prefix s = "http://hl7.org/fhir/request-priority"
  prefix t = "http://hl7.org/fhir/4.0/request-priority"

  s:routine - t:routine
  s:urgent - t:urgent
  s:asap - t:asap
  s:stat - t:stat
}

conceptmap "CommunicationStatus" {
  prefix s = "http://hl7.org/fhir/event-status"
  prefix t = "http://hl7.org/fhir/4.0/event-status"

  s:preparation - t:preparation
  s:"in-progress" - t:"in-progress"
  s:"not-done" - t:"not-done"
  s:"on-hold" - t:"on-hold"
  s:stopped - t:stopped
  s:completed - t:completed
  s:"entered-in-error" - t:"entered-in-error"
  s:unknown - t:unknown
}

uses "http://hl7.org/fhir/StructureDefinition/Communication" alias CommunicationR5 as source
uses "http://hl7.org/fhir/4.0/StructureDefinition/Communication" alias CommunicationR4 as target

imports "http://hl7.org/fhir/StructureMap/*5to4"

group Communication(source src : CommunicationR5, target tgt : CommunicationR4) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.instantiatesCanonical -> tgt.instantiatesCanonical;
  src.instantiatesUri -> tgt.instantiatesUri;
  src.basedOn -> tgt.basedOn;
  src.partOf -> tgt.partOf;
  src.inResponseTo -> tgt.inResponseTo;
  src.status as v -> tgt.status = translate(v, '#CommunicationStatus', 'code');
  src.statusReason -> tgt.statusReason;
  src.category -> tgt.category;
  src.priority as v -> tgt.priority = translate(v, '#CommunicationPriority', 'code');
  src.medium -> tgt.medium;
  src.subject -> tgt.subject;
  src.topic -> tgt.topic;
  src.about -> tgt.about;
  src.encounter -> tgt.encounter;
  src.sent -> tgt.sent;
  src.received -> tgt.received;
  src.recipient -> tgt.recipient;
  src.sender -> tgt.sender;
  src.reason -> tgt.reasonCode;
  src.reason -> tgt.reasonReference;
  src.payload as s -> tgt.payload as t then CommunicationPayload(s, t);
  src.note -> tgt.note;
}

group CommunicationPayload(source src, target tgt) extends BackboneElement {
  src.content : Attachment -> tgt.content;
  src.content : Reference -> tgt.content;
  src.content : CodeableConcept -> tgt.content;
}

# entry[].resource.title
FML Conversion for Communication: R5 to R4

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Encounter4to5'
/// name = 'Encounter4to5'
/// title = 'FML Conversion for Encounter: R4 to R5'
/// status = 'active'

conceptmap "EncounterLocationStatus" {
  prefix s = "http://hl7.org/fhir/4.0/encounter-location-status"
  prefix t = "http://hl7.org/fhir/encounter-location-status"

  s:planned - t:planned
  s:active - t:active
  s:reserved - t:reserved
  s:completed - t:completed
}

conceptmap "EncounterStatus" {
  prefix s = "http://hl7.org/fhir/4.0/encounter-status"
  prefix t = "http://hl7.org/fhir/encounter-status"

  s:planned - t:planned
  s:arrived - t:planned
  s:triaged - t:"in-progress"
  s:"in-progress" - t:"in-progress"
  s:onleave - t:"on-hold"
  s:finished - t:completed
  s:cancelled - t:cancelled
  s:"entered-in-error" - t:"entered-in-error"
  s:unknown - t:unknown
}

uses "http://hl7.org/fhir/4.0/StructureDefinition/Encounter" alias EncounterR4 as source
uses "http://hl7.org/fhir/StructureDefinition/Encounter" alias EncounterR5 as target

imports "http://hl7.org/fhir/StructureMap/*4to5"

group Encounter(source src : EncounterR4, target tgt : EncounterR5) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.status as v -> tgt.status = translate(v, '#EncounterStatus', 'code');
  src.class as s ->  tgt.class = create('CodeableConcept') as t,  t.coding as tc then Coding(s, tc); // src.class as s -> tgt.class = create('CodeableConcept') as t, t.coding = create('Coding') as tc, tc.system = (s.system), tc.code = (s.code), tc.display = s.display;
  src.priority -> tgt.priority;
  src.type -> tgt.type;
  src.serviceType -> tgt.serviceType;
  src.subject -> tgt.subject;
  src.episodeOfCare -> tgt.episodeOfCare; // src.subjectStatus -> tgt.subjectStatus;
  src.basedOn -> tgt.basedOn;
  src.partOf -> tgt.partOf; // src.careTeam -> tgt.careTeam;
  src.serviceProvider -> tgt.serviceProvider;
  src.participant as s -> tgt.participant as t then EncounterParticipant(s, t);
  src.appointment -> tgt.appointment;
  src.period -> tgt.actualPeriod; // src.virtualService -> tgt.virtualService;
  src.length -> tgt.length; // src.plannedStartDate -> tgt.plannedStartDate;
  src.diagnosis as s -> tgt.diagnosis as t then EncounterDiagnosis(s, t); // src.reason as s -> tgt.reason as t then EncounterReason(s,t);
  src.account -> tgt.account;
  src.hospitalization as s -> tgt.admission as t then EncounterAdmission(s, t); // src.dietPreference -> tgt.dietPreference;
  src.location as s -> tgt.location as t then EncounterLocation(s, t);
}

group EncounterParticipant(source src, target tgt) extends BackboneElement {
  src.type -> tgt.type;
  src.period -> tgt.period;
  src.individual -> tgt.actor;
}

// group EncounterReason(source src, target tgt) extends BackboneElement {
// src.use -> tgt.use;
// src.value -> tgt.value;
// }
group EncounterDiagnosis(source src, target tgt) extends BackboneElement {
  src.condition -> tgt.condition;
  src.use -> tgt.use;
}

group EncounterAdmission(source src, target tgt) extends BackboneElement {
  src.preAdmissionIdentifier -> tgt.preAdmissionIdentifier;
  src.origin -> tgt.origin;
  src.admitSource -> tgt.admitSource;
  src.reAdmission -> tgt.reAdmission;
  src.destination -> tgt.destination;
  src.dischargeDisposition -> tgt.dischargeDisposition;
}

group EncounterLocation(source src, target tgt) extends BackboneElement {
  src.location -> tgt.location;
  src.status as v -> tgt.status = translate(v, '#EncounterLocationStatus', 'code');
  src.physicalType -> tgt.form;
  src.period -> tgt.period;
}

# entry[].resource.group[].rule[].documentation
src.class as s -> tgt.class = create('CodeableConcept') as t, t.coding = create('Coding') as tc, tc.system = (s.system), tc.code = (s.code), tc.display = s.display;

# entry[].resource.group[].rule[].documentation
src.reason as s -> tgt.reason as t then EncounterReason(s,t);

# entry[].resource.group[].documentation
group EncounterReason(source src, target tgt) extends BackboneElement {
src.use -> tgt.use;
src.value -> tgt.value;
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Flag5to4B'
/// name = 'Flag5to4B'
/// title = 'FML Conversion for Flag: R5 to R4B'
/// status = 'draft'

conceptmap "FlagStatus" {
  prefix s = "http://hl7.org/fhir/flag-status"
  prefix t = "http://hl7.org/fhir/4.3/flag-status"

  s:active - t:active
  s:inactive - t:inactive
  s:"entered-in-error" - t:"entered-in-error"
}

uses "http://hl7.org/fhir/StructureDefinition/Flag" alias FlagR5 as source
uses "http://hl7.org/fhir/4.3/StructureDefinition/Flag" alias FlagR4B as target

imports "http://hl7.org/fhir/StructureMap/*5to4B"

group Flag(source src : FlagR5, target tgt : FlagR4B) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.status as v -> tgt.status = translate(v, '#FlagStatus', 'code');
  src.category -> tgt.category;
  src.code -> tgt.code;
  src.subject -> tgt.subject;
  src.period -> tgt.period;
  src.encounter -> tgt.encounter;
  src.author -> tgt.author;
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/TriggerDefinition4Bto5'
/// name = 'TriggerDefinition4Bto5'
/// title = 'FML Conversion for TriggerDefinition: R4B to R5'
/// status = 'active'

conceptmap "TriggerType" {
  prefix s = "http://hl7.org/fhir/4.3/trigger-type"
  prefix t = "http://hl7.org/fhir/trigger-type"

  s:"named-event" - t:"named-event"
  s:periodic - t:periodic
  s:"data-changed" - t:"data-changed"
  s:"data-added" - t:"data-added"
  s:"data-modified" - t:"data-modified"
  s:"data-removed" - t:"data-removed"
  s:"data-accessed" - t:"data-accessed"
  s:"data-access-ended" - t:"data-access-ended"
}

uses "http://hl7.org/fhir/4.3/StructureDefinition/TriggerDefinition" alias TriggerDefinitionR4B as source
uses "http://hl7.org/fhir/StructureDefinition/TriggerDefinition" alias TriggerDefinitionR5 as target

imports "http://hl7.org/fhir/StructureMap/*4Bto5"

group TriggerDefinition(source src : TriggerDefinitionR4B, target tgt : TriggerDefinitionR5) extends Element <<type+>> {
  src.type as v -> tgt.type = translate(v, '#TriggerType', 'code');
  src.name -> tgt.name;
  src.timing : Timing -> tgt.timing; // introduced in R5
  src.timing : Reference -> tgt.timing;
  src.timing : date -> tgt.timing;
  src.timing : dateTime -> tgt.timing;
  src.data -> tgt.data;
  src.condition -> tgt.condition;
}

# entry[].resource.title
FML Conversion for TriggerDefinition: R4B to R5

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Bundle4to5'
/// name = 'Bundle4to5'
/// title = 'FML Conversion for Bundle: R4 to R5'
/// status = 'active'

conceptmap "BundleType" {
  prefix s = "http://hl7.org/fhir/4.0/bundle-type"
  prefix t = "http://hl7.org/fhir/bundle-type"

  s:document - t:document
  s:message - t:message
  s:transaction - t:transaction
  s:"transaction-response" - t:"transaction-response"
  s:batch - t:batch
  s:"batch-response" - t:"batch-response"
  s:history - t:history
  s:searchset - t:searchset
  s:collection - t:collection
}

conceptmap "HTTPVerb" {
  prefix s = "http://hl7.org/fhir/4.0/http-verb"
  prefix t = "http://hl7.org/fhir/http-verb"

  s:GET - t:GET
  s:HEAD - t:HEAD
  s:POST - t:POST
  s:PUT - t:PUT
  s:DELETE - t:DELETE
  s:PATCH - t:PATCH
}

conceptmap "SearchEntryMode" {
  prefix s = "http://hl7.org/fhir/4.0/search-entry-mode"
  prefix t = "http://hl7.org/fhir/search-entry-mode"

  s:match - t:match
  s:include - t:include
  s:outcome - t:outcome
}

uses "http://hl7.org/fhir/4.0/StructureDefinition/Bundle" alias BundleR4 as source
uses "http://hl7.org/fhir/StructureDefinition/Bundle" alias BundleR5 as target

imports "http://hl7.org/fhir/StructureMap/*4to5"

group Bundle(source src : BundleR4, target tgt : BundleR5) extends Resource <<type+>> {
  src.identifier -> tgt.identifier;
  src.type as v -> tgt.type = translate(v, '#BundleType', 'code');
  src.timestamp -> tgt.timestamp;
  src.total -> tgt.total;
  src.link as s -> tgt.link as t then BundleLink(s, t);
  src.entry as s -> tgt.entry as t then BundleEntry(s, t);
  src.signature -> tgt.signature;
}

group BundleLink(source src, target tgt) extends BackboneElement {
  src.relation -> tgt.relation;
  src.url -> tgt.url;
}

group BundleEntry(source src, target tgt) extends BackboneElement {
  src.fullUrl -> tgt.fullUrl;
  src.resource : Resource -> tgt.resource;
  src.search as s -> tgt.search as t then BundleEntrySearch(s, t);
  src.request as s -> tgt.request as t then BundleEntryRequest(s, t);
  src.response as s -> tgt.response as t then BundleEntryResponse(s, t);
}

group BundleEntrySearch(source src, target tgt) extends BackboneElement {
  src.mode as v -> tgt.mode = translate(v, '#SearchEntryMode', 'code');
  src.score -> tgt.score;
}

group BundleEntryRequest(source src, target tgt) extends BackboneElement {
  src.method as v -> tgt.method = translate(v, '#HTTPVerb', 'code');
  src.url -> tgt.url;
  src.ifNoneMatch -> tgt.ifNoneMatch;
  src.ifModifiedSince -> tgt.ifModifiedSince;
  src.ifMatch -> tgt.ifMatch;
  src.ifNoneExist -> tgt.ifNoneExist;
}

group BundleEntryResponse(source src, target tgt) extends BackboneElement {
  src.status -> tgt.status;
  src.location -> tgt.location;
  src.etag -> tgt.etag;
  src.lastModified -> tgt.lastModified;
  src.outcome : Resource -> tgt.outcome;
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/AdverseEvent4Bto5'
/// name = 'AdverseEvent4Bto5'
/// title = 'FML Conversion for AdverseEvent: R4B to R5'
/// status = 'active'

conceptmap "AdverseEventActuality" {
  prefix s = "http://hl7.org/fhir/4.3/adverse-event-actuality"
  prefix t = "http://hl7.org/fhir/adverse-event-actuality"

  s:actual - t:actual
  s:potential - t:potential
}

uses "http://hl7.org/fhir/4.3/StructureDefinition/AdverseEvent" alias AdverseEventR4B as source
uses "http://hl7.org/fhir/StructureDefinition/AdverseEvent" alias AdverseEventR5 as target

imports "http://hl7.org/fhir/StructureMap/*4Bto5"

group AdverseEvent(source src : AdverseEventR4B, target tgt : AdverseEventR5) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.actuality as v -> tgt.actuality = translate(v, '#AdverseEventActuality', 'code'); // src.status -> tgt.status;
  src.category -> tgt.category;
  src.event -> tgt.code;
  src.subject -> tgt.subject;
  src.encounter -> tgt.encounter;
  src.date : dateTime -> tgt.occurrence;
  src.detected -> tgt.detected; // src.occurrence : Period -> tgt.occurrence;
  src.recordedDate -> tgt.recordedDate;
  src.resultingCondition -> tgt.resultingEffect;
  src.location -> tgt.location;
  src.seriousness -> tgt.seriousness;
  src.outcome -> tgt.outcome;
  src.recorder -> tgt.recorder;
  src.contributor as s -> tgt.participant as t then AdverseEventParticipant(s, t);
  src.study -> tgt.study;
  src.suspectEntity as s -> tgt.suspectEntity as t then AdverseEventSuspectEntity(s, t); // src.expectedInResearchStudy -> tgt.expectedInResearchStudy;
  src.subjectMedicalHistory as s -> tgt.contributingFactor as t then AdverseEventContributingFactor(s, t);
}

group AdverseEventParticipant(source src, target tgt) extends BackboneElement {
  src as v -> tgt.actor = v "reference"; // src.function -> tgt.function;
}

group AdverseEventSuspectEntity(source src, target tgt) extends BackboneElement {
  src.instance : Reference -> tgt.instance; // src.instance : CodeableConcept -> tgt.instance;
  src.causality as s -> tgt.causality as t then AdverseEventSuspectEntityCausality(s, t);
}

group AdverseEventSuspectEntityCausality(source src, target tgt) extends BackboneElement {
  src.assessment -> tgt.assessmentMethod;
  src.productRelatedness -> tgt.entityRelatedness;
  src.author -> tgt.author;
}

group AdverseEventContributingFactor(source src, target tgt) extends BackboneElement {
  src as v -> tgt.item = v "reference";
}

# entry[].resource.title
FML Conversion for AdverseEvent: R4B to R5

# entry[].resource.group[].rule[].documentation
src.occurrence : Period -> tgt.occurrence;

# entry[].resource.group[].rule[].documentation
src.instance : CodeableConcept -> tgt.instance;

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/AllergyIntolerance5to4'
/// name = 'AllergyIntolerance5to4'
/// title = 'FML Conversion for AllergyIntolerance: R5 to R4'
/// status = 'active'

conceptmap "AllergyIntoleranceCategory" {
  prefix s = "http://hl7.org/fhir/allergy-intolerance-category"
  prefix t = "http://hl7.org/fhir/4.0/allergy-intolerance-category"

  s:food - t:food
  s:medication - t:medication
  s:environment - t:environment
  s:biologic - t:biologic
}

conceptmap "AllergyIntoleranceCriticality" {
  prefix s = "http://hl7.org/fhir/allergy-intolerance-criticality"
  prefix t = "http://hl7.org/fhir/4.0/allergy-intolerance-criticality"

  s:low - t:low
  s:high - t:high
  s:"unable-to-assess" - t:"unable-to-assess"
}

conceptmap "AllergyIntoleranceSeverity" {
  prefix s = "http://hl7.org/fhir/reaction-event-severity"
  prefix t = "http://hl7.org/fhir/4.0/reaction-event-severity"

  s:mild - t:mild
  s:moderate - t:moderate
  s:severe - t:severe
}

uses "http://hl7.org/fhir/StructureDefinition/AllergyIntolerance" alias AllergyIntoleranceR5 as source
uses "http://hl7.org/fhir/4.0/StructureDefinition/AllergyIntolerance" alias AllergyIntoleranceR4 as target

imports "http://hl7.org/fhir/StructureMap/*5to4"

group AllergyIntolerance(source src : AllergyIntoleranceR5, target tgt : AllergyIntoleranceR4) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.clinicalStatus -> tgt.clinicalStatus;
  src.verificationStatus -> tgt.verificationStatus;
  src.type as s where code = 'allergy' ->  tgt.type = create('code') as t,  t.value = 'allergy';
  src.type as s where code = 'intolerance' ->  tgt.type = create('code') as t,  t.value = 'intolerance';
  src.category as v -> tgt.category = translate(v, '#AllergyIntoleranceCategory', 'code');
  src.criticality as v -> tgt.criticality = translate(v, '#AllergyIntoleranceCriticality', 'code');
  src.code -> tgt.code;
  src.patient -> tgt.patient;
  src.encounter -> tgt.encounter;
  src.onset : dateTime -> tgt.onset;
  src.onset : Age -> tgt.onset;
  src.onset : Period -> tgt.onset;
  src.onset : Range -> tgt.onset;
  src.onset : string -> tgt.onset;
  src.recordedDate -> tgt.recordedDate;
  src.participant as s where code = 'enterer' -> tgt then {
    s.actor -> tgt.recorder;
  };
  src.participant as s where code = 'author' -> tgt then {
    s.actor -> tgt.recorder;
  };
  src.lastOccurrence -> tgt.lastOccurrence;
  src.note -> tgt.note;
  src.reaction as s -> tgt.reaction as t then AllergyIntoleranceReaction(s, t);
}

// group AllergyIntoleranceParticipant(source src, target tgt) extends BackboneElement {
// src.function -> tgt.function;
// src.actor -> tgt.actor;
// }
group AllergyIntoleranceReaction(source src, target tgt) extends BackboneElement {
  src.substance -> tgt.substance;
  src.manifestation -> tgt.manifestation;
  src.description -> tgt.description;
  src.onset -> tgt.onset;
  src.severity as v -> tgt.severity = translate(v, '#AllergyIntoleranceSeverity', 'code');
  src.exposureRoute -> tgt.exposureRoute;
  src.note -> tgt.note;
}

# entry[].resource.title
FML Conversion for AllergyIntolerance: R5 to R4

# entry[].resource.group[].documentation
group AllergyIntoleranceParticipant(source src, target tgt) extends BackboneElement {
src.function -> tgt.function;
src.actor -> tgt.actor;
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Contract5to4'
/// name = 'Contract5to4'
/// title = 'FML Conversion for Contract: R5 to R4'
/// status = 'draft'

conceptmap "ContractPublicationStatus" {
  prefix s = "http://hl7.org/fhir/contract-publicationstatus"
  prefix t = "http://hl7.org/fhir/4.0/contract-publicationstatus"

  s:amended - t:amended
  s:appended - t:appended
  s:cancelled - t:cancelled
  s:disputed - t:disputed
  s:"entered-in-error" - t:"entered-in-error"
  s:executable - t:executable
  s:executed - t:executed
  s:negotiable - t:negotiable
  s:offered - t:offered
  s:policy - t:policy
  s:rejected - t:rejected
  s:renewed - t:renewed
  s:revoked - t:revoked
  s:resolved - t:resolved
  s:terminated - t:terminated
}

conceptmap "ContractStatus" {
  prefix s = "http://hl7.org/fhir/contract-status"
  prefix t = "http://hl7.org/fhir/4.0/contract-status"

  s:amended - t:amended
  s:appended - t:appended
  s:cancelled - t:cancelled
  s:disputed - t:disputed
  s:"entered-in-error" - t:"entered-in-error"
  s:executable - t:executable
  s:executed - t:executed
  s:negotiable - t:negotiable
  s:offered - t:offered
  s:policy - t:policy
  s:rejected - t:rejected
  s:renewed - t:renewed
  s:revoked - t:revoked
  s:resolved - t:resolved
  s:terminated - t:terminated
}

uses "http://hl7.org/fhir/StructureDefinition/Contract" alias ContractR5 as source
uses "http://hl7.org/fhir/4.0/StructureDefinition/Contract" alias ContractR4 as target

imports "http://hl7.org/fhir/StructureMap/*5to4"

group Contract(source src : ContractR5, target tgt : ContractR4) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.url -> tgt.url;
  src.version -> tgt.version;
  src.status as v -> tgt.status = translate(v, '#ContractStatus', 'code');
  src.legalState -> tgt.legalState;
  src.instantiatesCanonical -> tgt.instantiatesCanonical;
  src.instantiatesUri -> tgt.instantiatesUri;
  src.contentDerivative -> tgt.contentDerivative;
  src.issued -> tgt.issued;
  src.applies -> tgt.applies;
  src.expirationType -> tgt.expirationType;
  src.subject -> tgt.subject;
  src.authority -> tgt.authority;
  src.domain -> tgt.domain;
  src.site -> tgt.site;
  src.name -> tgt.name;
  src.title -> tgt.title;
  src.subtitle -> tgt.subtitle;
  src.alias -> tgt.alias;
  src.author -> tgt.author;
  src.scope -> tgt.scope;
  src.topic : CodeableConcept -> tgt.topic;
  src.topic : Reference -> tgt.topic;
  src.type -> tgt.type;
  src.subType -> tgt.subType;
  src.contentDefinition as s -> tgt.contentDefinition as t then ContractContentDefinition(s, t);
  src.term as s -> tgt.term as t then ContractTerm(s, t);
  src.supportingInfo -> tgt.supportingInfo;
  src.relevantHistory -> tgt.relevantHistory;
  src.signer as s -> tgt.signer as t then ContractSigner(s, t);
  src.friendly as s -> tgt.friendly as t then ContractFriendly(s, t);
  src.legal as s -> tgt.legal as t then ContractLegal(s, t);
  src.rule as s -> tgt.rule as t then ContractRule(s, t);
  src.legallyBinding : Attachment -> tgt.legallyBinding;
  src.legallyBinding : Reference -> tgt.legallyBinding;
}

group ContractContentDefinition(source src, target tgt) extends BackboneElement {
  src.type -> tgt.type;
  src.subType -> tgt.subType;
  src.publisher -> tgt.publisher;
  src.publicationDate -> tgt.publicationDate;
  src.publicationStatus as v -> tgt.publicationStatus = translate(v, '#ContractPublicationStatus', 'code');
  src.copyright -> tgt.copyright;
}

group ContractTerm(source src, target tgt) extends BackboneElement {
  src.identifier -> tgt.identifier;
  src.issued -> tgt.issued;
  src.applies -> tgt.applies;
  src.topic : CodeableConcept -> tgt.topic;
  src.topic : Reference -> tgt.topic;
  src.type -> tgt.type;
  src.subType -> tgt.subType;
  src.text -> tgt.text;
  src.securityLabel as s -> tgt.securityLabel as t then ContractTermSecurityLabel(s, t);
  src.offer as s -> tgt.offer as t then ContractTermOffer(s, t);
  src.asset as s -> tgt.asset as t then ContractTermAsset(s, t);
  src.action as s -> tgt.action as t then ContractTermAction(s, t);
}

group ContractTermSecurityLabel(source src, target tgt) extends BackboneElement {
  src.number -> tgt.number;
  src.classification -> tgt.classification;
  src.category -> tgt.category;
  src.control -> tgt.control;
}

group ContractTermOffer(source src, target tgt) extends BackboneElement {
  src.identifier -> tgt.identifier;
  src.party as s -> tgt.party as t then ContractTermOfferParty(s, t);
  src.topic -> tgt.topic;
  src.type -> tgt.type;
  src.decision -> tgt.decision;
  src.decisionMode -> tgt.decisionMode;
  src.answer as s -> tgt.answer as t then ContractTermOfferAnswer(s, t);
  src.text -> tgt.text;
  src.linkId -> tgt.linkId;
  src.securityLabelNumber -> tgt.securityLabelNumber;
}

group ContractTermOfferParty(source src, target tgt) extends BackboneElement {
  src.reference -> tgt.reference;
  src.role -> tgt.role;
}

group ContractTermOfferAnswer(source src, target tgt) extends BackboneElement {
  src.value : boolean -> tgt.value;
  src.value : decimal -> tgt.value;
  src.value : integer -> tgt.value;
  src.value : date -> tgt.value;
  src.value : dateTime -> tgt.value;
  src.value : time -> tgt.value;
  src.value : string -> tgt.value;
  src.value : uri -> tgt.value;
  src.value : Attachment -> tgt.value;
  src.value : Coding -> tgt.value;
  src.value : Quantity -> tgt.value;
  src.value : Reference -> tgt.value;
}

group ContractTermAsset(source src, target tgt) extends BackboneElement {
  src.scope -> tgt.scope;
  src.type -> tgt.type;
  src.typeReference -> tgt.typeReference;
  src.subtype -> tgt.subtype;
  src.relationship -> tgt.relationship;
  src.context as s -> tgt.context as t then ContractTermAssetContext(s, t);
  src.condition -> tgt.condition;
  src.periodType -> tgt.periodType;
  src.period -> tgt.period;
  src.usePeriod -> tgt.usePeriod;
  src.text -> tgt.text;
  src.linkId -> tgt.linkId;
  src.securityLabelNumber -> tgt.securityLabelNumber;
  src.valuedItem as s -> tgt.valuedItem as t then ContractTermAssetValuedItem(s, t);
}

group ContractTermAssetContext(source src, target tgt) extends BackboneElement {
  src.reference -> tgt.reference;
  src.code -> tgt.code;
  src.text -> tgt.text;
}

group ContractTermAssetValuedItem(source src, target tgt) extends BackboneElement {
  src.entity : CodeableConcept -> tgt.entity;
  src.entity : Reference -> tgt.entity;
  src.identifier -> tgt.identifier;
  src.effectiveTime -> tgt.effectiveTime;
  src.quantity -> tgt.quantity;
  src.unitPrice -> tgt.unitPrice;
  src.factor -> tgt.factor;
  src.points -> tgt.points;
  src.net -> tgt.net;
  src.payment -> tgt.payment;
  src.paymentDate -> tgt.paymentDate;
  src.responsible -> tgt.responsible;
  src.recipient -> tgt.recipient;
  src.linkId -> tgt.linkId;
  src.securityLabelNumber -> tgt.securityLabelNumber;
}

group ContractTermAction(source src, target tgt) extends BackboneElement {
  src.doNotPerform -> tgt.doNotPerform;
  src.type -> tgt.type;
  src.subject as s -> tgt.subject as t then ContractTermActionSubject(s, t);
  src.intent -> tgt.intent;
  src.linkId -> tgt.linkId;
  src.status -> tgt.status;
  src.context -> tgt.context;
  src.contextLinkId -> tgt.contextLinkId;
  src.occurrence : dateTime -> tgt.occurrence;
  src.occurrence : Period -> tgt.occurrence;
  src.occurrence : Timing -> tgt.occurrence;
  src.requester -> tgt.requester;
  src.requesterLinkId -> tgt.requesterLinkId;
  src.performerType -> tgt.performerType;
  src.performerRole -> tgt.performerRole;
  src.performer -> tgt.performer;
  src.performerLinkId -> tgt.performerLinkId;
  src.reason -> tgt.reason;
  src.reasonLinkId -> tgt.reasonLinkId;
  src.note -> tgt.note;
  src.securityLabelNumber -> tgt.securityLabelNumber;
}

group ContractTermActionSubject(source src, target tgt) extends BackboneElement {
  src.reference -> tgt.reference;
  src.role -> tgt.role;
}

group ContractSigner(source src, target tgt) extends BackboneElement {
  src.type -> tgt.type;
  src.party -> tgt.party;
  src.signature -> tgt.signature;
}

group ContractFriendly(source src, target tgt) extends BackboneElement {
  src.content : Attachment -> tgt.content;
  src.content : Reference -> tgt.content;
}

group ContractLegal(source src, target tgt) extends BackboneElement {
  src.content : Attachment -> tgt.content;
  src.content : Reference -> tgt.content;
}

group ContractRule(source src, target tgt) extends BackboneElement {
  src.content : Attachment -> tgt.content;
  src.content : Reference -> tgt.content;
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Condition4to5'
/// name = 'Condition4to5'
/// title = 'FML Conversion for Condition: R4 to R5'
/// status = 'active'

uses "http://hl7.org/fhir/4.0/StructureDefinition/Condition" alias ConditionR4 as source
uses "http://hl7.org/fhir/StructureDefinition/Condition" alias ConditionR5 as target

imports "http://hl7.org/fhir/StructureMap/*4to5"

group Condition(source src : ConditionR4, target tgt : ConditionR5) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.clinicalStatus -> tgt.clinicalStatus;
  src.verificationStatus -> tgt.verificationStatus;
  src.category -> tgt.category;
  src.severity -> tgt.severity;
  src.code -> tgt.code;
  src.bodySite -> tgt.bodySite;
  src.subject -> tgt.subject;
  src.encounter -> tgt.encounter;
  src.onset : dateTime -> tgt.onset;
  src.onset : Age -> tgt.onset;
  src.onset : Period -> tgt.onset;
  src.onset : Range -> tgt.onset;
  src.onset : string -> tgt.onset;
  src.abatement : dateTime -> tgt.abatement;
  src.abatement : Age -> tgt.abatement;
  src.abatement : Period -> tgt.abatement;
  src.abatement : Range -> tgt.abatement;
  src.abatement : string -> tgt.abatement;
  src.recordedDate -> tgt.recordedDate;
  src.recorder as s -> tgt.participant as t then ConditionRecorder(s, t);
  src.asserter as s -> tgt.participant as t then ConditionAsserter(s, t);
  src.stage as s -> tgt.stage as t then ConditionStage(s, t);
  src.evidence as s -> tgt then {
    s.code : CodeableConcept as c -> tgt.evidence;
    s.detail : Reference as d -> tgt.evidence;
  };
  src.note -> tgt.note;
}

group ConditionStage(source src, target tgt) extends BackboneElement {
  src.summary -> tgt.summary;
  src.assessment -> tgt.assessment;
  src.type -> tgt.type;
}

group ConditionRecorder(source src, target tgt) extends BackboneElement {
  src.reference as v ->  tgt.function = create('CodeableConcept') as t,  t.coding = create('Coding') as tc,  tc.system = 'http://terminology.hl7.org/CodeSystem/provenance-participant-type',  tc.code = 'enterer',  tc.display = 'Enterer';
  src : Reference as v -> tgt.actor = v "reference";
}

group ConditionAsserter(source src, target tgt) extends BackboneElement {
  src.reference as v ->  tgt.function = create('CodeableConcept') as t,  t.coding = create('Coding') as tc,  tc.system = 'http://terminology.hl7.org/CodeSystem/provenance-participant-type',  tc.code = 'author',  tc.display = 'Author';
  src : Reference as v -> tgt.actor = v "reference";
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/ImagingStudy4Bto5'
/// name = 'ImagingStudy4Bto5'
/// title = 'FML Conversion for ImagingStudy: R4B to R5'
/// status = 'active'

conceptmap "ImagingStudyStatus" {
  prefix s = "http://hl7.org/fhir/4.3/imagingstudy-status"
  prefix t = "http://hl7.org/fhir/imagingstudy-status"

  s:registered - t:registered
  s:available - t:available
  s:cancelled - t:cancelled
  s:"entered-in-error" - t:"entered-in-error"
  s:unknown - t:unknown
}

uses "http://hl7.org/fhir/4.3/StructureDefinition/ImagingStudy" alias ImagingStudyR4B as source
uses "http://hl7.org/fhir/StructureDefinition/ImagingStudy" alias ImagingStudyR5 as target

imports "http://hl7.org/fhir/StructureMap/*4Bto5"

group ImagingStudy(source src : ImagingStudyR4B, target tgt : ImagingStudyR5) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.status as v -> tgt.status = translate(v, '#ImagingStudyStatus', 'code');
  src.modality -> tgt.modality;
  src.subject -> tgt.subject;
  src.encounter -> tgt.encounter;
  src.started -> tgt.started;
  src.basedOn -> tgt.basedOn;
  src.referrer -> tgt.referrer; // src.partOf -> tgt.partOf;
  src.endpoint -> tgt.endpoint;
  src.numberOfSeries -> tgt.numberOfSeries;
  src.numberOfInstances -> tgt.numberOfInstances;
  src.procedureCode : CodeableConcept -> tgt.procedure;
  src.procedureReference : Reference -> tgt.procedure;
  src.location -> tgt.location;
  src.reasonCode : CodeableConcept -> tgt.reason;
  src.reasonReference : Reference -> tgt.reason;
  src.note -> tgt.note;
  src.description -> tgt.description;
  src.series as s -> tgt.series as t then ImagingStudySeries(s, t);
}

group ImagingStudySeries(source src, target tgt) extends BackboneElement {
  src.uid -> tgt.uid;
  src.number -> tgt.number;
  src.modality -> tgt.modality;
  src.description -> tgt.description;
  src.numberOfInstances -> tgt.numberOfInstances;
  src.endpoint -> tgt.endpoint;
  src.bodySite -> tgt.bodySite;
  src.laterality -> tgt.laterality;
  src.specimen -> tgt.specimen;
  src.started -> tgt.started;
  src.performer as s -> tgt.performer as t then ImagingStudySeriesPerformer(s, t);
  src.instance as s -> tgt.instance as t then ImagingStudySeriesInstance(s, t);
}

group ImagingStudySeriesPerformer(source src, target tgt) extends BackboneElement {
  src.function -> tgt.function;
  src.actor -> tgt.actor;
}

group ImagingStudySeriesInstance(source src, target tgt) extends BackboneElement {
  src.uid -> tgt.uid;
  src.sopClass -> tgt.sopClass;
  src.number -> tgt.number;
  src.title -> tgt.title;
}

# entry[].resource.title
FML Conversion for ImagingStudy: R4B to R5

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Distance4Bto5'
/// name = 'Distance4Bto5'
/// title = 'FML Conversion for Distance: R4B to R5'
/// status = 'active'

uses "http://hl7.org/fhir/4.3/StructureDefinition/Distance" alias DistanceR4B as source
uses "http://hl7.org/fhir/StructureDefinition/Distance" alias DistanceR5 as target

imports "http://hl7.org/fhir/StructureMap/*4Bto5"

group Distance(source src : DistanceR4B, target tgt : DistanceR5) extends Quantity <<type+>> {
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/SearchParameter5to4'
/// name = 'SearchParameter5to4'
/// title = 'FML Conversion for SearchParameter: R5 to R4'
/// status = 'active'

conceptmap "PublicationStatus" {
  prefix s = "http://hl7.org/fhir/publication-status"
  prefix t = "http://hl7.org/fhir/4.0/publication-status"

  s:draft - t:draft
  s:active - t:active
  s:retired - t:retired
  s:unknown - t:unknown
}

conceptmap "SearchComparator" {
  prefix s = "http://hl7.org/fhir/search-comparator"
  prefix t = "http://hl7.org/fhir/4.0/search-comparator"

  s:eq - t:eq
  s:ne - t:ne
  s:gt - t:gt
  s:lt - t:lt
  s:ge - t:ge
  s:le - t:le
  s:sa - t:sa
  s:eb - t:eb
  s:ap - t:ap
}

conceptmap "SearchModifierCode" {
  prefix s = "http://hl7.org/fhir/search-modifier-code"
  prefix t = "http://hl7.org/fhir/4.0/search-modifier-code"

  s:missing - t:missing
  s:exact - t:exact
  s:contains - t:contains
  s:not - t:not
  s:text - t:text
  s:in - t:in
  s:"not-in" - t:"not-in"
  s:below - t:below
  s:above - t:above
  s:type - t:type
  s:identifier - t:identifier
}

conceptmap "SearchParamType" {
  prefix s = "http://hl7.org/fhir/search-param-type"
  prefix t = "http://hl7.org/fhir/4.0/search-param-type"

  s:number - t:number
  s:date - t:date
  s:string - t:string
  s:token - t:token
  s:reference - t:reference
  s:composite - t:composite
  s:quantity - t:quantity
  s:uri - t:uri
  s:special - t:special
}

conceptmap "SearchProcessingModeType" {
  prefix s = "http://hl7.org/fhir/search-processingmode"
  prefix t = "http://hl7.org/fhir/4.0/search-xpath-usage"

  s:normal - t:normal
  s:phonetic - t:phonetic
  s:other - t:other
}

uses "http://hl7.org/fhir/StructureDefinition/SearchParameter" alias SearchParameterR5 as source
uses "http://hl7.org/fhir/4.0/StructureDefinition/SearchParameter" alias SearchParameterR4 as target

imports "http://hl7.org/fhir/StructureMap/*5to4"

group SearchParameter(source src : SearchParameterR5, target tgt : SearchParameterR4) extends DomainResource <<type+>> {
  src.url -> tgt.url;
  src.version -> tgt.version; // src.identifier -> tgt.identifier;
  src.name -> tgt.name; // src.versionAlgorithm : string -> tgt.versionAlgorithm;
  src.derivedFrom -> tgt.derivedFrom; // src.title -> tgt.title;
  src.status as v -> tgt.status = translate(v, '#PublicationStatus', 'code');
  src.experimental -> tgt.experimental;
  src.date -> tgt.date;
  src.publisher -> tgt.publisher;
  src.contact -> tgt.contact;
  src.description -> tgt.description;
  src.useContext -> tgt.useContext;
  src.jurisdiction -> tgt.jurisdiction;
  src.purpose -> tgt.purpose;
  src.code -> tgt.code; // src.copyright -> tgt.copyright;
  src.base -> tgt.base;
  src.type as v -> tgt.type = translate(v, '#SearchParamType', 'code');
  src.expression -> tgt.expression;
  src.processingMode as v -> tgt.xpathUsage = translate(v, '#SearchProcessingModeType', 'code');
  src.target -> tgt.target; // src.constraint -> tgt.constraint;
  src.multipleOr -> tgt.multipleOr;
  src.multipleAnd -> tgt.multipleAnd;
  src.comparator as v -> tgt.comparator = translate(v, '#SearchComparator', 'code');
  src.modifier as v -> tgt.modifier = translate(v, '#SearchModifierCode', 'code');
  src.chain -> tgt.chain;
  src.component as s -> tgt.component as t then SearchParameterComponent(s, t);
}

group SearchParameterComponent(source src, target tgt) extends BackboneElement {
  src.definition -> tgt.definition;
  src.expression -> tgt.expression;
}

# entry[].resource.title
FML Conversion for SearchParameter: R5 to R4

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Goal5to4B'
/// name = 'Goal5to4B'
/// title = 'FML Conversion for Goal: R5 to R4B'
/// status = 'active'

conceptmap "GoalLifecycleStatus" {
  prefix s = "http://hl7.org/fhir/goal-status"
  prefix t = "http://hl7.org/fhir/4.3/goal-status"

  s:proposed - t:proposed
  s:planned - t:planned
  s:accepted - t:accepted
  s:active - t:active
  s:"on-hold" - t:"on-hold"
  s:completed - t:completed
  s:cancelled - t:cancelled
  s:"entered-in-error" - t:"entered-in-error"
  s:rejected - t:rejected
}

uses "http://hl7.org/fhir/StructureDefinition/Goal" alias GoalR5 as source
uses "http://hl7.org/fhir/4.3/StructureDefinition/Goal" alias GoalR4B as target

imports "http://hl7.org/fhir/StructureMap/*5to4B"

group Goal(source src : GoalR5, target tgt : GoalR4B) extends DomainResource <<type+>> {
  src.identifier -> tgt.identifier;
  src.lifecycleStatus as v -> tgt.lifecycleStatus = translate(v, '#GoalLifecycleStatus', 'code');
  src.achievementStatus -> tgt.achievementStatus;
  src.category -> tgt.category;
  src.priority -> tgt.priority; // src.continuous -> tgt.continuous;
  src.description -> tgt.description;
  src.subject -> tgt.subject;
  src.start : date -> tgt.start;
  src.start : CodeableConcept -> tgt.start;
  src.target as s -> tgt.target as t then GoalTarget(s, t);
  src.statusDate -> tgt.statusDate;
  src.statusReason -> tgt.statusReason;
  src.addresses -> tgt.addresses; // src.source -> tgt.source;
  src.note -> tgt.note;
  src.outcome -> tgt.outcomeCode;
  src.outcome -> tgt.outcomeReference;
}

group GoalTarget(source src, target tgt) extends BackboneElement {
  src.measure -> tgt.measure;
  src.detail : Quantity -> tgt.detail;
  src.detail : Range -> tgt.detail;
  src.detail : CodeableConcept -> tgt.detail;
  src.detail : string -> tgt.detail;
  src.detail : boolean -> tgt.detail;
  src.detail : integer -> tgt.detail;
  src.detail : Ratio -> tgt.detail;
  src.due : date -> tgt.due;
  src.due : Duration -> tgt.due;
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/ExampleScenario5to4B'
/// name = 'ExampleScenario5to4B'
/// title = 'FML Conversion for ExampleScenario: R5 to R4B'
/// status = 'active'

conceptmap "ExampleScenarioActorType" {
  prefix s = "http://hl7.org/fhir/examplescenario-actor-type"
  prefix t = "http://hl7.org/fhir/4.3/examplescenario-actor-type"

  s:person - t:person
  s:system - t:entity
}

conceptmap "PublicationStatus" {
  prefix s = "http://hl7.org/fhir/publication-status"
  prefix t = "http://hl7.org/fhir/4.3/publication-status"

  s:draft - t:draft
  s:active - t:active
  s:retired - t:retired
  s:unknown - t:unknown
}

uses "http://hl7.org/fhir/StructureDefinition/ExampleScenario" alias ExampleScenarioR5 as source
uses "http://hl7.org/fhir/4.3/StructureDefinition/ExampleScenario" alias ExampleScenarioR4B as target

imports "http://hl7.org/fhir/StructureMap/*5to4B"

group ExampleScenario(source src : ExampleScenarioR5, target tgt : ExampleScenarioR4B) extends DomainResource <<type+>> {
  src.url -> tgt.url;
  src.identifier -> tgt.identifier;
  src.version -> tgt.version;
  src.name -> tgt.name; // src.versionAlgorithm : string -> tgt.versionAlgorithm;
  src.status as v -> tgt.status = translate(v, '#PublicationStatus', 'code'); // src.title -> tgt.title;
  src.experimental -> tgt.experimental;
  src.date -> tgt.date;
  src.publisher -> tgt.publisher;
  src.contact -> tgt.contact;
  src.useContext -> tgt.useContext; // src.description -> tgt.description;
  src.jurisdiction -> tgt.jurisdiction;
  src.purpose -> tgt.purpose;
  src.copyright -> tgt.copyright;
  src.actor as s -> tgt.actor as t then ExampleScenarioActor(s, t); // src.copyrightLabel -> tgt.copyrightLabel;
  src.instance as s -> tgt.instance as t then ExampleScenarioInstance(s, t);
  src.process as s -> tgt.process as t then ExampleScenarioProcess(s, t);
}

group ExampleScenarioActor(source src, target tgt) extends BackboneElement {
  src.key -> tgt.actorId;
  src.type as v -> tgt.type = translate(v, '#ExampleScenarioActorType', 'code');
  src.title -> tgt.name;
  src.description -> tgt.description;
}

group ExampleScenarioInstance(source src, target tgt) extends BackboneElement {
  src.key -> tgt.resourceId;
  src.structureType as s -> tgt then {
    s.code -> tgt.resourceType;
  };
  src.version as s -> tgt.version as t then ExampleScenarioInstanceVersion(s, t);
  src.title -> tgt.name; // src.structureProfile : canonical -> tgt.structureProfile;
  src.description -> tgt.description;
  src.containedInstance as s -> tgt.containedInstance as t then ExampleScenarioInstanceContainedInstance(s, t); // src.content -> tgt.content;
}

group ExampleScenarioInstanceVersion(source src, target tgt) extends BackboneElement {
  src.key -> tgt.versionId;
  src.description -> tgt.description; // src.title -> tgt.title;
}

group ExampleScenarioInstanceContainedInstance(source src, target tgt) extends BackboneElement {
  src.instanceReference -> tgt.resourceId;
  src.versionReference -> tgt.versionId;
}

group ExampleScenarioProcess(source src, target tgt) extends BackboneElement {
  src.title -> tgt.title;
  src.description -> tgt.description;
  src.preConditions -> tgt.preConditions;
  src.postConditions -> tgt.postConditions;
  src.step as s -> tgt.step as t then ExampleScenarioProcessStep(s, t);
}

group ExampleScenarioProcessStep(source src, target tgt) extends BackboneElement {
  src.operation as s -> tgt.operation as t then ExampleScenarioProcessStepOperation(s, t); // src.number -> tgt.number;
  src.alternative as s -> tgt.alternative as t then ExampleScenarioProcessStepAlternative(s, t);
  src.pause -> tgt.pause;
}

group ExampleScenarioProcessStepOperation(source src, target tgt) extends BackboneElement {
  src.title -> tgt.type; // src.type -> tgt.type;
  src.initiator -> tgt.initiator;
  src.receiver -> tgt.receiver;
  src.description -> tgt.description;
  src.initiatorActive -> tgt.initiatorActive;
  src.receiverActive -> tgt.receiverActive;
}

group ExampleScenarioProcessStepAlternative(source src, target tgt) extends BackboneElement {
  src.title -> tgt.title;
  src.description -> tgt.description;
}

# entry[].resource.title
FML Conversion for ExampleScenario: R5 to R4B

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Ratio4Bto5'
/// name = 'Ratio4Bto5'
/// title = 'FML Conversion for Ratio: R4B to R5'
/// status = 'active'

uses "http://hl7.org/fhir/4.3/StructureDefinition/Ratio" alias RatioR4B as source
uses "http://hl7.org/fhir/StructureDefinition/Ratio" alias RatioR5 as target

imports "http://hl7.org/fhir/StructureMap/*4Bto5"

group Ratio(source src : RatioR4B, target tgt : RatioR5) extends Element <<type+>> {
  src.numerator -> tgt.numerator;
  src.denominator -> tgt.denominator;
}

# entry[].resource.text.div
/// url = 'http://hl7.org/fhir/StructureMap/Meta4to5'
/// name = 'Meta4to5'
/// title = 'FML Conversion for Meta: R4 to R5'
/// status = 'active'

uses "http://hl7.org/fhir/4.0/StructureDefinition/Meta" alias MetaR4 as source
uses "http://hl7.org/fhir/StructureDefinition/Meta" alias MetaR5 as target

imports "http://hl7.org/fhir/StructureMap/*4to5"

group Meta(source src : MetaR4, target tgt : MetaR5) extends Element <<type+>> {
  src.versionId -> tgt.versionId;
  src.lastUpdated -> tgt.lastUpdated;
  src.source -> tgt.source;
  src.profile -> tgt.profile;
  src.security -> tgt.security;
  src.tag -> tgt.tag;
}

# entry[].resource.text.div
/// url = "http://salute.gov.it/ig/cda-fhir-maps/StructureMap/TesseraPortatoreImpianto"
/// name = "TesseraPortatoreImpianto"
/// title = "null"
/// status = "draft"

conceptmap "OBSstatus" {
  prefix s = "http://terminology.hl7.org/ValueSet/v3-statusCode"
  prefix t = "http://hl7.org/fhir/observation-status"

  s:completed == t:final
  s:active == t:registered
  s:aborted == t:cancelled
  s:suspended == t:partial
}

conceptmap "cm-v3-administrative-gender" {
  prefix s = "http://terminology.hl7.org/ValueSet/v3-AdministrativeGender"
  prefix t = "http://hl7.org/fhir/ValueSet/administrative-gender"

  s:M == t:male
  s:F == t:female
}

uses "http://hl7.org/cda/stds/core/StructureDefinition/ClinicalDocument" alias ClinicalDocument as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/AssignedAuthor" alias AssignedAuthor as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/AssignedEntity" alias AssignedEntity as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/AssociatedEntity" alias AssociatedEntity as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/CustodianOrganization" alias CustodianOrganization as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/OrganizationPartOf" alias OrganizationPartOf as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/Organization" alias rapresentedOrganization as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/Section" alias Section as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/PatientRole" alias PatientRole as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/AD" alias AD as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/Act" alias Act as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/IVL-PQ" alias IVL_PQ as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/PQ" alias PQ as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/ParticipantRole" alias participantRole as source
uses "http://hl7.org/cda/stds/core/StructureDefinition/PlayingEntity" alias playingEntity as source
uses "http://hl7.org/fhir/StructureDefinition/Bundle" alias Bundle as target
uses "http://hl7.org/fhir/StructureDefinition/Composition" alias Composition as target
uses "http://hl7.org/fhir/StructureDefinition/Patient" alias Patient as target
uses "http://hl7.org/fhir/StructureDefinition/Encounter" alias Encounter as target
uses "http://hl7.org/fhir/StructureDefinition/Person" alias Patient as target
uses "http://hl7.org/fhir/StructureDefinition/List" alias List as target
uses "http://hl7.org/fhir/StructureDefinition/Practitioner" alias Practitioner as target
uses "http://hl7.org/fhir/StructureDefinition/Organization" alias Organization as target
uses "http://hl7.org/fhir/StructureDefinition/SimpleQuantity" alias SimpleQuantity as target
uses "http://hl7.org/fhir/StructureDefinition/DeviceUseStatement" alias DeviceUseStatement as target
uses "http://hl7.org/fhir/StructureDefinition/DocumentReference" alias DocumentReference as target
uses "http://hl7.org/fhir/StructureDefinition/Device" alias Device as target
uses "http://hl7.org/fhir/StructureDefinition/PractitionerRole" alias PractitionerRole as target

imports "http://salute.gov.it/ig/cda-fhir-maps/StructureMap/CdaToFhirDataTypes"
imports "http://salute.gov.it/ig/cda-fhir-maps/StructureMap/FULLHEADER"

group CdaToBundle(source cda : ClinicalDocument, target bundle : Bundle) {
  cda ->  bundle.entry as e,  e.request = create('BackboneElement') as request,  request.method = 'POST',  e.resource = create('Composition') as composition,  composition.id = uuid() as uuid1,  e.fullUrl = append('https://example/Composition/', uuid1),  request.url = 'Composition',  bundle.entry as e2,  e2.request = create('BackboneElement') as requestPAT,  requestPAT.method = 'PUT',  e2.resource = create('Patient') as patient,  patient.id = uuid() as uuid2,  e2.fullUrl = append('https://example/Patient/', uuid2),  bundle.entry as e3,  e3.request = create('BackboneElement') as request,  request.method = 'POST',  e3.resource = create('Encounter') as encounter,  encounter.id = uuid() as uuid3,  e3.fullUrl = append('https://example/Encounter/', uuid3),  request.url = 'Encounter',  bundle.entry as e4,  e4.request = create('BackboneElement') as request,  request.method = 'POST',  e4.resource = create('DocumentReference') as DocumentReference,  DocumentReference.id = uuid() as uuid4,  e4.fullUrl = append('https://example/DocumentReference/', uuid4),  request.url = 'DocumentReference' then {
    cda then ClinicalDocumentToBundle(cda, patient, composition, encounter, bundle, DocumentReference) "cdatobundle";
    cda.recordTarget as recordTarget then {
      recordTarget.patientRole as patient then {
        patient.id as id -> patient.identifier as identifier then {
          id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
          id.extension as ext1 -> identifier.value = ext1 "value";
          id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        } "idfr";
        patient.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') or (root = '2.16.840.1.113883.2.9.4.3.7') or (root = '2.16.840.1.113883.2.9.4.3.3') or (root = '2.16.840.1.113883.2.9.4.3.17') or (root = '2.16.840.1.113883.2.9.4.3.18') or (root = '2.16.840.1.113883.2.9.2.10.4.1.1') or (root = '2.16.840.1.113883.2.9.2.20.4.1.1') or (root = '2.16.840.1.113883.2.9.2.30.4.1.1') or (root = '2.16.840.1.113883.2.9.2.41.4.1.1') or (root = '2.16.840.1.113883.2.9.2.42.4.1.1') or (root = '2.16.840.1.113883.2.9.2.50.4.1.1') or (root = '2.16.840.1.113883.2.9.2.60.4.1.1') or (root = '2.16.840.1.113883.2.9.2.70.4.1.1') or (root = '2.16.840.1.113883.2.9.2.80.4.1.1') or (root = '2.16.840.1.113883.2.9.2.90.4.1.1') or (root = '2.16.840.1.113883.2.9.2.100.4.1.1') or (root = '2.16.840.1.113883.2.9.2.110.4.1.1') or (root = '2.16.840.1.113883.2.9.2.120.4.1.1') or (root = '2.16.840.1.113883.2.9.2.130.4.1.1') or (root = '2.16.840.1.113883.2.9.2.140.4.1.1') or (root = '2.16.840.1.113883.2.9.2.150.4.1.1') or (root = '2.16.840.1.113883.2.9.2.160.4.1.1') or (root = '2.16.840.1.113883.2.9.2.170.4.1.1') or (root = '2.16.840.1.113883.2.9.2.180.4.1.1') or (root = '2.16.840.1.113883.2.9.2.190.4.1.1') or (root = '2.16.840.1.113883.2.9.2.200.4.1.1') or (root = '2.16.840.1.113883.2.9.2.10.4.1') or (root = '2.16.840.1.113883.2.9.2.20.4.1') or (root = '2.16.840.1.113883.2.9.2.30.4.1') or (root = '2.16.840.1.113883.2.9.2.41.4.1') or (root = '2.16.840.1.113883.2.9.2.42.4.1') or (root = '2.16.840.1.113883.2.9.2.50.4.1') or (root = '2.16.840.1.113883.2.9.2.60.4.1') or (root = '2.16.840.1.113883.2.9.2.70.4.1') or (root = '2.16.840.1.113883.2.9.2.80.4.1') or (root = '2.16.840.1.113883.2.9.2.90.4.1') or (root = '2.16.840.1.113883.2.9.2.100.4.1') or (root = '2.16.840.1.113883.2.9.2.110.4.1') or (root = '2.16.840.1.113883.2.9.2.120.4.1') or (root = '2.16.840.1.113883.2.9.2.130.4.1') or (root = '2.16.840.1.113883.2.9.2.140.4.1') or (root = '2.16.840.1.113883.2.9.2.150.4.1') or (root = '2.16.840.1.113883.2.9.2.160.4.1') or (root = '2.16.840.1.113883.2.9.2.170.4.1') or (root = '2.16.840.1.113883.2.9.2.180.4.1') or (root = '2.16.840.1.113883.2.9.2.190.4.1') or (root = '2.16.840.1.113883.2.9.2.200.4.1') or (root = '2.16.840.1.113883.2.9.4.3.15') then {
          id.extension as ext -> requestPAT.url = append('Patient?identifier=', ext) "UUID";
        } "ext";
      } "recPat";
    } "patient";
  } "ClinicalDocumentTo";
}

group ClinicalDocumentToBundle(source cda : ClinicalDocument, target patient : Patient, target composition : Composition, target encounter : Encounter, target bundle : Bundle, target DocumentReference : DocumentReference) {
  cda -> bundle.id = uuid() "id";
  cda.id -> bundle.identifier "identifier";
  cda -> bundle.type = 'transaction' "type";
  cda -> bundle.timestamp = (timestamp.now()) "date";
  cda then ClinicalDocumentComposition(cda, composition, patient, encounter, bundle, DocumentReference) "composition";
  cda ->  bundle.entry as e,  e.request = create('BackboneElement') as request,  request.method = 'POST',  e.resource = create('DeviceUseStatement') as DeviceUseStatement,  DeviceUseStatement.id = uuid() as uuid1,  e.fullUrl = append('https://example/DeviceUseStatement/', uuid1),  request.url = 'DeviceUseStatement' then {
    cda ->  DeviceUseStatement.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    cda.component as component then {
      component.structuredBody as body then {
        body.component as component then {
          component.section as srcSection then {
            srcSection.code -> composition.section as tgtSection then ClinicalDocumentSection(cda, srcSection, patient, DeviceUseStatement, tgtSection, bundle, DocumentReference);
          };
        };
      } "body";
    };
  } "DeviseUseStatement";
}

group ClinicalDocumentSection(source cda : ClinicalDocument, source src : Section, target patient : Patient, target dus : DeviceUseStatement, target tgt : Composition, target bundle : Bundle, target DocumentReference : DocumentReference) {
  src.title as t -> tgt.title = (t.xmlText);
  src.text as te -> tgt.text = (te.xmlText);
  src.code -> tgt.code;
  src ->  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/DeviceUseStatement/' + %dus.id) "reference";
  src.entry as entry then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
    entry then DeviceUseFunction(src, dus, bundle, tgt, patient) "dus";
  };
  src.component as component then {
    component.section as sec -> tgt.section as tgtSection then ClinicalDocumentSection(cda, src, patient, tgtSection, bundle, enc, dus);
  };
}

group DeviceUseFunction(source src : Section, target dus : DeviceUseStatement, target bundle : Bundle, target tgt, target patient : Patient) {
  src -> dus.status = 'active' "status";
  src ->  dus.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  src.entry as entry then {
    entry.organizer as organizer then {
      organizer.sdtcText as text -> dus.note as note then {
        text.reference as t -> note.text = (t.value) "t";
      } "dusnote";
      organizer.component as component then {
        component.supply as sup then {
          sup ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Device') as device,  device.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Device/', uuid1),  request.url = 'Device',  dus.device = create('Reference') as reference,  reference.reference = ('https://example/Device/' + %device.id),  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Device/' + %device.id) then {
            sup ->  device.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
            sup.id as id -> device.identifier as identifier then {
              id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
              id.extension as ext -> identifier.value = ext;
              id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
            } "identifier";
            sup.code -> device.type "type";
            sup.effectiveTime : IVL_TS as eff then {
              eff as eff where (low.exists()) -> dus.timing = create('Period') as value then IVLTSPeriod(eff, value) "valuePeriod";
            } "period";
            sup.entryRelationship as entry2 where entry2.observation.exists() then {
              entry2.observation as observation then {
                observation.value as value where (code = 'LA9633-4') -> device.status = 'active';
                observation.value as value where (code = 'LA9634-2') -> device.status = 'inactive';
              } "act";
            } "entry1";
            sup.product as product then {
              product.manufacturedProduct as manu then {
                manu.manufacturedMaterial as material then {
                  material.name as name -> device.deviceName as devname then {
                    name.item as v -> devname.name = (v.xmlText);
                    name -> devname.type = 'manufacturer-name' "deviceNametype";
                  };
                  material.lotNumberText as t -> device.lotNumber = (t.xmlText) "lotnumber";
                } "material";
                manu.manufacturerOrganization as manuorg ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Organization') as organization,  organization.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Organization/', uuid1),  request.url = 'Organization' then {
                  manuorg ->  device.owner = create('Reference') as reference,  reference.reference = ('https://example/Organization/' + %organization.id) "org";
                  manuorg.id as id -> organization.identifier as identifier then {
                    id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
                    id.extension as ext -> identifier.value = ext;
                    id.extension as ext -> identifier.value = ext then {
                      manuorg -> request.url = append('Organization?identifier=', ext) "UUID";
                    } "ext";
                    id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
                  } "identifier";
                  manuorg.name as name then {
                    name.item as v -> organization.name = (v.xmlText);
                  } "item";
                  manuorg.telecom -> organization.telecom;
                  manuorg.addr -> organization.address;
                } "manuorg";
              } "manu";
            };
            sup.participant as part1 where (typeCode = 'LOC') ->  bundle.entry as e2,  e2.request = create('BackboneElement') as request,  request.method = 'POST',  e2.resource = create('Procedure') as procedure,  procedure.id = uuid() as uuid1,  e2.fullUrl = append('https://example/Procedure/', uuid1),  request.url = 'Procedure',  dus.derivedFrom = create('Reference') as reference,  reference.reference = ('https://example/Procedure/' + %procedure.id) then {
              part1 -> procedure.status = 'completed' "status";
              part1 ->  procedure.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
              part1 -> procedure.performer as performer then {
                part1 ->  bundle.entry as e3,  e3.request = create('BackboneElement') as request,  request.method = 'PUT',  e3.resource = create('Organization') as organization,  organization.id = uuid() as uuid1,  e3.fullUrl = append('https://example/Organization/', uuid1),  request.url = 'Organization',  performer.actor = create('Reference') as reference,  reference.reference = ('https://example/Organization/' + %organization.id),  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Organization/' + %organization.id) then {
                  part1.participantRole as role then {
                    role.addr -> organization.address;
                    role.id as id -> organization.identifier as identifier then {
                      id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
                      id.extension as ext -> identifier.value = ext;
                      id.extension as ext -> identifier.value = ext then {
                        role -> request.url = append('Organization?identifier=', ext) "UUID";
                      } "ext";
                      id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
                    } "identifier";
                    role.playingEntity as entity then {
                      entity.name as name then {
                        name.item as v -> organization.name = (v.xmlText);
                      };
                    } "entity";
                  } "role";
                } "organization";
              } "performer";
            } "participantLOC";
            sup.participant as part2 where (typeCode = 'DEV') then {
              part2.participantRole as role then {
                role.playingDevice as pdevice then {
                  pdevice.manufacturerModelName as t -> device.modelNumber = (t.xmlText) "modelnumber";
                } "pdevice";
              } "role";
            } "participantDEV";
            sup.entryRelationship as entry1 where entry1.act.exists() then {
              entry1.act as act then {
                act.reference as ref then {
                  ref.externalDocument as extdoc then {
                    extdoc.id as id then {
                      id.extension as ext ->  tgt.entry = create('Reference') as reference,  reference.display = ext "reference";
                    } "ref";
                  } "extdoc";
                } "ref";
              };
            } "entry1";
          } "device";
        };
        component where component.observation.exists() then {
          component.observation as obs then {
            obs.value -> dus.bodySite "bodysite";
          } "obs";
        } "orgobs";
      };
    };
  };
}