private void DoOrg(int b, List <string> rx)
        {
            organisation.Id = FhirHelper.MakeId();
            organisation.Identifier.Add(FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/ods-organization-code", rx[b + EMUData.SDSORGANISATIONID]));
            ContactPoint cp = new ContactPoint
            {
                System = ContactPoint.ContactPointSystem.Phone,
                Use    = ContactPoint.ContactPointUse.Work,
                Value  = rx[b + EMUData.ORGANISATIONTELECOM]
            };

            organisation.Telecom.Add(cp);
            CodeableConcept cc = new CodeableConcept();

            cc.Coding.Add(FhirHelper.MakeCoding("https://fhir.nhs.uk/R4/CodeSystem/organisation-type", rx[b + EMUData.ORGANISATIONTYPE], null));
            organisation.Type.Add(cc);
            organisation.Name = rx[b + EMUData.ORGANISATIONNAME];
            organisation.Address.Add(MakeAddress(b, rx));
            Identifier        pct    = FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/ods-organization-code", rx[b + EMUData.PCTORGANISATIONSDSID]);
            ResourceReference pctref = new ResourceReference
            {
                Identifier = pct
            };

            organisation.PartOf = pctref;
        }
        private static MedicationRequest.DispenseRequestComponent MakeDispenseRequest(ResourceReference nom, System.Collections.Generic.List <string> rx,
                                                                                      System.Collections.Generic.List <string> item)
        {
            MedicationRequest.DispenseRequestComponent dr = new MedicationRequest.DispenseRequestComponent();
            Extension e = FhirHelper.MakeExtension(null, "https://fhir.nhs.uk/R4/StructureDefinition/Extension-performerType",
                                                   FhirHelper.MakeCoding("https://fhir.nhs.uk/R4/CodeSystem/dispensing-site-preference", rx[EMUData.DISPENSINGSITEPREFERENCE], null));

            try
            {
                dr.Quantity = new SimpleQuantity
                {
                    Code   = item[EMUData.QUANTITYCODE],
                    System = "http://snomed.info/sct",
                    Unit   = item[EMUData.QUANTITYTEXT],
                    Value  = Convert.ToDecimal(item[EMUData.QUANTITYCOUNT])
                };
            }
            catch (Exception ex)
            {
#pragma warning disable CA2241 // Provide correct arguments to formatting methods
                Console.WriteLine("Exception: {ex} making SimpleQuantity: {value}", ex.Message, item[EMUData.QUANTITYCOUNT]);
#pragma warning restore CA2241 // Provide correct arguments to formatting methods
            }
            if (nom != null)
            {
                dr.Performer = nom;
            }
            dr.Extension.Add(e);
            return(dr);
        }
        private static void DoResponsiblePractitioner(MedicationRequest m, ParticipantMaker a)
        {
            Extension e = FhirHelper.MakeExtension(null, "https://fhir.nhs.uk/R4/StructureDefinition/Extension-DM-ResponsiblePractitioner",
                                                   FhirHelper.MakeInternalReference(a.Role));

            m.Extension.Add(e);
        }
        private static CodeableConcept DoMedication(System.Collections.Generic.List <string> item)
        {
            CodeableConcept cc = new CodeableConcept();

            cc.Coding.Add(FhirHelper.MakeCoding("http://snomed.info/sct", item[EMUData.SUBSTANCECODE], item[EMUData.DISPLAYNAME]));
            return(cc);
        }
        private static void AddPatientGp(Patient p, System.Collections.Generic.List <string> rx)
        {
            ResourceReference r = new ResourceReference
            {
                Identifier = FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/ods-organization-code", rx[EMUData.PATIENTPRIMARYCAREPROVIDESDSID])
            };

            p.ManagingOrganization = r;
        }
        private static Identifier MakeGroupIdentifier(System.Collections.Generic.List <string> rx)
        {
            Identifier sfid = FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/prescription-short-form",
                                                        rx[EMUData.PRESCRIPTIONID]);
            Extension e = FhirHelper.MakeExtension(null, "https://fhir.nhs.uk/R4/StructureDefinition/Extension-PrescriptionId",
                                                   FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/prescription", rx[EMUData.PRESCRIPTIONCLINICALSTATEMENTID]));

            sfid.Extension.Add(e);
            return(sfid);
        }
        private static MessageHeader.MessageSourceComponent MakeSource()
        {
            MessageHeader.MessageSourceComponent s = new MessageHeader.MessageSourceComponent();
            Extension a = FhirHelper.MakeExtension("https://fhir.nhs.uk/R4/StructureDefinition/Extension-spineEndpoint",
                                                   FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/spine-ASID", asid));

            s.Extension.Add(a);
            s.Name     = ods;
            s.Endpoint = url;
            return(s);
        }
        private static void DoPrescriptionType(MedicationRequest m, System.Collections.Generic.List <string> rx)
        {
            Coding ptc = FhirHelper.MakeCoding("https://fhir.nhs.uk/R4/CodeSystem/prescription-type", rx[EMUData.PRESCRIPTIONTYPE], null);

            if (rx[EMUData.PRESCRIPTIONTYPE].Equals("0001"))
            {
                ptc.Display = "General Practitioner Prescribing";
            }
            Extension e = FhirHelper.MakeExtension(null, "https://fhir.nhs.uk/R4/StructureDefinition/Extension-prescriptionType", ptc);

            m.Extension.Add(e);
        }
        private static MessageHeader MakeMessageHeader(ParticipantMaker a)
        {
            MessageHeader header = new MessageHeader
            {
                Id     = FhirHelper.MakeId(),
                Event  = FhirHelper.MakeCoding("https://fhir.nhs.uk/R4/CodeSystem/message-event", "prescription-order", "Prescription Order"),
                Sender = FhirHelper.MakeInternalReference(a.Role)
            };

            header.Sender.Display = a.Practitioner.Name[0].Text;
            header.Source         = MakeSource();
            return(header);
        }
        private static ResourceReference GetNominatedPharmacyReference(System.Collections.Generic.List <string> rx)
        {
            ResourceReference r = null;
            string            n = rx[EMUData.NOMINATEDPHARMACYID].Trim();

            if (n.Length > 0)
            {
                r = new ResourceReference
                {
                    Identifier = FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/ods-organization-code", n)
                };
            }
            return(r);
        }
        public void Go()
        {
            SanityCheckOutput();
            EMUData emu = new EMUData(prescriptionsFile, itemsFile);

            emu.Load();
            foreach (string pid in emu.GetPrescriptionIDs())
            {
                Bundle b = MakeBundle(emu.GetPrescriptionData(pid), emu.GetItems(pid));
                if (b != null)
                {
                    FhirHelper.WriteResource(pid, b, outputDirectory, xml);
                }
            }
        }
        private void DoRole(int b, List <string> rx)
        {
            role.Id = FhirHelper.MakeId();
            role.Identifier.Add(FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/sds-role-profile-id", rx[b + EMUData.ROLEPROFILE]));
            role.Practitioner = FhirHelper.MakeInternalReference(practitioner);
            role.Organization = FhirHelper.MakeInternalReference(organisation);
            ContactPoint cp = new ContactPoint
            {
                System = ContactPoint.ContactPointSystem.Phone,
                Use    = ContactPoint.ContactPointUse.Work,
                Value  = rx[b + EMUData.ORGANISATIONTELECOM]
            };

            role.Telecom.Add(cp);
        }
        private void DoPractitioner(int b, List <string> rx)
        {
            practitioner.Id = FhirHelper.MakeId();
            HumanName h = new HumanName
            {
                Text = rx[b + EMUData.PERSONNAME]
            };
            List <HumanName> ah = new List <HumanName>
            {
                h
            };

            practitioner.Name = ah;
            practitioner.Identifier.Add(FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/sds-user-id", rx[b + EMUData.SDSUSERID]));
        }
        private static void AddNhsNumber(Patient p, System.Collections.Generic.List <string> rx)
        {
            currentNhsNumber = rx[EMUData.PATIENTID];
            Identifier n   = FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/nhs-number", rx[EMUData.PATIENTID]);
            Extension  evs = new Extension
            {
                Url = "https://fhir.nhs.uk/R4/StructureDefinition/Extension-UKCore-NHSNumberVerificationStatus"
            };
            CodeableConcept vccvs = new CodeableConcept();

            vccvs.Coding.Add(FhirHelper.MakeCoding("https://fhir.nhs.uk/R4/CodeSystem/UKCore-NHSNumberVerificationStatus",
                                                   "01", "Number present and verified"));
            evs.Value = vccvs;
            n.Extension.Add(evs);
            p.Identifier.Add(n);
        }
        public static void WriteResource(string pid, Resource r, string outputDirectory, bool xml)
        {
            string rid   = pid ?? r.Id;
            string rname = r.ResourceType.ToString();

            if (xml)
            {
                FhirXmlSerializer xs = new FhirXmlSerializer();
                string            sr = xs.SerializeToString(r);
                FhirHelper.Write(rid, rname, sr, outputDirectory, xml);
            }
            else
            {
                FhirJsonSerializer js = new FhirJsonSerializer();
                string             sr = js.SerializeToString(r);
                FhirHelper.Write(rid, rname, sr, outputDirectory, xml);
            }
        }
        private static Patient MakePatient(System.Collections.Generic.List <string> rx)
        {
            DateTime d = new DateTime();

            if (!FhirHelper.MakeDate(rx[EMUData.PATIENTBIRTHTIME], out d))
            {
                Console.WriteLine("Failed to parse birth date: " + rx[EMUData.PATIENTBIRTHTIME]);
            }
            Patient p = new Patient
            {
                Id        = FhirHelper.MakeId(),
                BirthDate = FhirHelper.FormatDate(d),
                Gender    = GetGender(rx[EMUData.PATIENTGENDER])
            };

            AddNhsNumber(p, rx);
            AddPatientName(p, rx);
            AddPatientAddress(p, rx);
            AddPatientGp(p, rx);
            return(p);
        }
        private static MedicationRequest MakeMedicationRequest(Patient p, System.Collections.Generic.List <string> rx,
                                                               System.Collections.Generic.List <string> item, ResourceReference nom, ParticipantMaker a)
        {
            MedicationRequest m = new MedicationRequest
            {
                Id = FhirHelper.MakeId()
            };

            m.Status  = MedicationRequest.medicationrequestStatus.Active;
            m.Intent  = MedicationRequest.medicationRequestIntent.Order;
            m.Subject = FhirHelper.MakeInternalReference(p);
            m.Identifier.Add(FhirHelper.MakeIdentifier("https://fhir.nhs.uk/Id/prescription-line-id", item[EMUData.LINEITEMID]));
            ResourceReference rq = FhirHelper.MakeInternalReference(a.Role);

            rq.Display        = a.Practitioner.Name[0].Text;
            m.Requester       = rq;
            m.AuthoredOn      = rx[EMUData.AUTHORPARTICIPATIONTIME];
            m.GroupIdentifier = MakeGroupIdentifier(rx);

            DoPrescriptionType(m, rx);
            DoResponsiblePractitioner(m, a);
            m.Medication          = DoMedication(item);
            m.CourseOfTherapyType = MakeCourseOfTherapyType(rx);
            if (item[EMUData.DOSAGEINTRUCTIONS].Trim().Length > 0)
            {
                Dosage di = new Dosage
                {
                    Text = item[EMUData.DOSAGEINTRUCTIONS]
                };
                m.DosageInstruction.Add(di);
                if (item[EMUData.ADDITIONALINSTRUCTIONS].Trim().Length > 0)
                {
                    di.PatientInstruction = item[EMUData.ADDITIONALINSTRUCTIONS];
                }
            }
            m.DispenseRequest = MakeDispenseRequest(nom, rx, item);
            return(m);
        }
        private static Bundle MakeBundle(System.Collections.Generic.List <string> rx, System.Collections.Generic.List <System.Collections.Generic.List <string> > items)
        {
            Bundle b = new Bundle
            {
                Id   = FhirHelper.MakeId(),
                Type = Bundle.BundleType.Message
            };
            ParticipantMaker author = new ParticipantMaker();

            author.Make(EMUData.AUTHORROLEPROFILE, rx);
            GetParticipantIdentifiers(author);
            Patient p = MakePatient(rx);

            if (resdir != null)
            {
                if (!practitioners.ContainsKey(currentPractitioner))
                {
                    FhirHelper.WriteResource(null, author.Practitioner, resdir, xml);
                    practitioners.Add(currentPractitioner, author.Practitioner.Id);
                }
                else
                {
                    author.Practitioner.Id = practitioners[currentPractitioner];
                }
                if (!organisations.ContainsKey(currentOrganisation))
                {
                    FhirHelper.WriteResource(null, author.Organisation, resdir, xml);
                    organisations.Add(currentOrganisation, author.Organisation.Id);
                }
                else
                {
                    author.Organisation.Id = organisations[currentOrganisation];
                }
                if (!roles.ContainsKey(currentRole))
                {
                    FhirHelper.WriteResource(null, author.Role, resdir, xml);
                    roles.Add(currentRole, author.Role.Id);
                }
                else
                {
                    author.Role.Id = roles[currentRole];
                }
                if (!patients.ContainsKey(currentNhsNumber))
                {
                    FhirHelper.WriteResource(null, p, resdir, xml);
                    patients.Add(currentNhsNumber, p.Id);
                }
                else
                {
                    p.Id = patients[currentNhsNumber];
                }
            }
            MessageHeader header = MakeMessageHeader(author);

            FhirHelper.AddEntryToBundle(b, header);
            FhirHelper.AddEntryToBundle(b, p);
            FhirHelper.AddEntryToBundle(b, author.Practitioner);
            FhirHelper.AddEntryToBundle(b, author.Organisation);
            FhirHelper.AddEntryToBundle(b, author.Role);
            ResourceReference nominatedPharmacy = GetNominatedPharmacyReference(rx);

            foreach (System.Collections.Generic.List <string> item in items)
            {
                MedicationRequest m = MakeMedicationRequest(p, rx, item, nominatedPharmacy, author);
                if (m != null)
                {
                    FhirHelper.AddEntryToBundle(b, m);
                    header.Focus.Add(FhirHelper.MakeInternalReference(m));
                    FhirHelper.WriteResource(null, m, resdir, xml);
                }
            }

            header.Focus.Add(FhirHelper.MakeInternalReference(p));
            header.Focus.Add(FhirHelper.MakeInternalReference(author.Role));
            return(b);
        }