protected Letter.FileContents[] ProcessReferrersLetters(bool viewListOnly, ArrayList bookingsForCurrentReferrer, bool autoSendFaxesAsEmailsIfNoEmailExistsToGPs, ref string debugOutput, int bulkLetterSendingQueueBatchID)
    {
        if (bookingsForCurrentReferrer.Count == 0)
        {
            return(new Letter.FileContents[0]);
        }


        // to return - only files to print, as emailing will have been completed
        ArrayList filesToPrint = new ArrayList();


        // single db lookup per referrer to get email
        Tuple <Booking, PatientReferrer, bool, bool, HealthCard> firstTuple = (Tuple <Booking, PatientReferrer, bool, bool, HealthCard>)bookingsForCurrentReferrer[0];
        PatientReferrer firstPR = firstTuple.Item2;


        int s = firstPR.RegisterReferrer.RegisterReferrerID;



        string[] refEmails = ContactDB.GetEmailsByEntityID(firstPR.RegisterReferrer.Organisation.EntityID);
        string[] refFaxes  = ContactDB.GetFaxesByEntityID(firstPR.RegisterReferrer.Organisation.EntityID);

        bool   firstRefHasEmail = refEmails.Length > 0;
        string refEmail         = refEmails.Length > 0 ? string.Join(",", refEmails) : null;

        bool   firstRefHasFax = refFaxes.Length > 0;
        string refFax         = refFaxes.Length > 0 ? refFaxes[0] : null;


        int  siteID  = Convert.ToInt32(Session["SiteID"]);
        Site site    = SiteDB.GetByID(siteID);
        int  staffID = Convert.ToInt32(Session["StaffID"]);

        Site[] sites = SiteDB.GetAll();
        for (int i = 0; i < bookingsForCurrentReferrer.Count; i++)
        {
            Tuple <Booking, PatientReferrer, bool, bool, HealthCard> curTuple = (Tuple <Booking, PatientReferrer, bool, bool, HealthCard>)bookingsForCurrentReferrer[i];
            Booking         curBooking     = curTuple.Item1;
            PatientReferrer curPR          = curTuple.Item2;
            bool            curRefHasEmail = curTuple.Item3;
            bool            curRefHasFax   = curTuple.Item4;
            HealthCard      curHC          = curTuple.Item5;


            bool needToGenerateLetters = curBooking.NeedToGenerateFirstLetter || curBooking.NeedToGenerateLastLetter ||
                                         (curPR.RegisterReferrer.ReportEveryVisitToReferrer && curBooking.NoteCount > 0);
            if (needToGenerateLetters)
            {
                SendMethod sendMethod = (curRefHasEmail && this.SelectedSendMethod == SendMethod.Email ? SendMethod.Email : SendMethod.Print);

                if (!viewListOnly)
                {
                    bool sendViaEmail = autoSendFaxesAsEmailsIfNoEmailExistsToGPs ? (curRefHasEmail || curRefHasFax) : curRefHasEmail;
                    if (sendViaEmail && this.SelectedSendMethod == SendMethod.Email)
                    {
                        string toEmail = autoSendFaxesAsEmailsIfNoEmailExistsToGPs ?
                                         (curRefHasEmail ? refEmail : Regex.Replace(refFax, "[^0-9]", "") + "@fax.houseofit.com.au")
                            :
                                         refEmail;

                        if (UseBulkLetterSender)
                        {
                            BulkLetterSendingQueueAdditionalLetter[] filesList = GetFilesInfo(curBooking, Letter.FileFormat.PDF, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, false, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, curPR.RegisterReferrer.ReportEveryVisitToReferrer, siteID, staffID, sendMethod == SendMethod.Email ? 2 : 1);

                            if (filesList != null && filesList.Length > 0)
                            {
                                string from_email = ((SystemVariables)System.Web.HttpContext.Current.Session["SystemVariables"])["Email_FromEmail"].Value;
                                string subject    = "Referral/Treatment Note Letters From Mediclinic" + (curPR.Patient == null ? string.Empty : " For " + curPR.Patient.Person.FullnameWithoutMiddlename);
                                string text       = "Dr. " + curPR.RegisterReferrer.Referrer.Person.FullnameWithoutMiddlename + "<br /><br />Please find attached referral/treatment note letters for your referrered patient" + (curPR.Patient == null ? string.Empty : " <b>" + curPR.Patient.Person.FullnameWithoutMiddlename + "</b>") + "<br /><br />Best regards,<br />" + site.Name;

                                int bulk_letter_sending_queue_id = BulkLetterSendingQueueDB.Insert
                                                                   (
                                    bulkLetterSendingQueueBatchID,
                                    2,                                          // bulk_letter_sending_queue_method_id (2 = email)
                                    staffID,                                    // added_by
                                    curPR.Patient.PatientID,                    // patient_id
                                    curPR.RegisterReferrer.Referrer.ReferrerID, // referrer_id
                                    curBooking.BookingID,                       // booking_id
                                    "",                                         // phone_number
                                    toEmail,                                    // email_to_address
                                    "",                                         // email_to_name
                                    from_email,                                 // email_from_address
                                    site.Name,                                  // email_from_name
                                    text,                                       // text
                                    subject,                                    // email_subject
                                    "",                                         // email_attachment_location
                                    false,                                      // email_attachment_delete_after_sending
                                    false,                                      // email_attachment_folder_delete_after_sending

                                    filesList[0].EmailLetterLetterID,
                                    filesList[0].EmailLetterKeepHistoryInDb,
                                    filesList[0].EmailLetterKeepHistoryInFile,
                                    filesList[0].EmailLetterLetterPrintHistorySendMethodID,
                                    filesList[0].EmailLetterHistoryDir,
                                    filesList[0].EmailLetterHistoryFilename,
                                    filesList[0].EmailLetterSiteID,
                                    filesList[0].EmailLetterOrganisationID,
                                    filesList[0].EmailLetterBookingID,
                                    filesList[0].EmailLetterPatientID,
                                    filesList[0].EmailLetterRegisterReferrerIdToUseInsteadOfPatientsRegRef,
                                    filesList[0].EmailLetterStaffID,
                                    filesList[0].EmailLetterHealthCardActionID,
                                    filesList[0].EmailLetterSourceTemplatePath,
                                    filesList[0].EmailLetterOutputDocPath,
                                    false, // filesList[0].EmailLetterIsDoubleSidedPrinting,
                                    filesList[0].EmailLetterExtraPages,
                                    filesList[0].EmailLetterItemSeperator,

                                    "",    // sql_to_run_on_completion
                                    ""     // sql_to_run_on_failure
                                                                   );

                                for (int f = 1; f < filesList.Length; f++)
                                {
                                    BulkLetterSendingQueueAdditionalLetterDB.Insert(
                                        bulk_letter_sending_queue_id,
                                        filesList[f].EmailLetterLetterID,
                                        filesList[f].EmailLetterKeepHistoryInDb,
                                        filesList[f].EmailLetterKeepHistoryInFile,
                                        filesList[f].EmailLetterLetterPrintHistorySendMethodID,
                                        filesList[f].EmailLetterHistoryDir,
                                        filesList[f].EmailLetterHistoryFilename,
                                        filesList[f].EmailLetterSiteID,
                                        filesList[f].EmailLetterOrganisationID,
                                        filesList[f].EmailLetterBookingID,
                                        filesList[f].EmailLetterPatientID,
                                        filesList[f].EmailLetterRegisterReferrerIdToUseInsteadOfPatientsRegRef,
                                        filesList[f].EmailLetterStaffID,
                                        filesList[f].EmailLetterHealthCardActionID,
                                        filesList[f].EmailLetterSourceTemplatePath,
                                        filesList[f].EmailLetterOutputDocPath,
                                        false, // filesList[f].EmailLetterIsDoubleSidedPrinting,
                                        filesList[f].EmailLetterExtraPages,
                                        filesList[f].EmailLetterItemSeperator);
                                }
                            }
                        }
                        else
                        {
                            Letter.FileContents[] fileContentsList = curBooking.GetSystemLettersList(Letter.FileFormat.PDF, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, false, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, curPR.RegisterReferrer.ReportEveryVisitToReferrer, false, Convert.ToInt32(Session["SiteID"]), Convert.ToInt32(Session["StaffID"]), sendMethod == SendMethod.Email ? 2 : 1);
                            if (fileContentsList != null && fileContentsList.Length > 0)
                            {
                                //Logger.LogQuery("ReferrerEPCLetters_Reprint -- Email Send Item Starting!");
                                Site bkSite = SiteDB.GetSiteByType(curBooking.Organisation.IsAgedCare ? SiteDB.SiteType.AgedCare : SiteDB.SiteType.Clinic, sites);
                                Letter.EmailSystemLetter(bkSite.Name, toEmail, fileContentsList);
                                //Logger.LogQuery("ReferrerEPCLetters_Reprint -- Email Send Item Done!");
                            }
                        }
                    }
                    else
                    {
                        Letter.FileContents[] fileContentsList = curBooking.GetSystemLettersList(Letter.FileFormat.Word, curBooking.Patient, curHC, curBooking.Offering.Field.ID, curPR.RegisterReferrer.Referrer, false, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, curPR.RegisterReferrer.ReportEveryVisitToReferrer, false, Convert.ToInt32(Session["SiteID"]), Convert.ToInt32(Session["StaffID"]), sendMethod == SendMethod.Email ? 2 : 1);
                        if (fileContentsList != null && fileContentsList.Length > 0)
                        {
                            filesToPrint.AddRange(fileContentsList);
                        }
                    }

                    BookingDB.UpdateSetGeneratedSystemLetters(curBooking.BookingID, curBooking.NeedToGenerateFirstLetter, curBooking.NeedToGenerateLastLetter, true);
                }

                ArrayList toGenerateList = new ArrayList();
                if (curBooking.NeedToGenerateFirstLetter)
                {
                    toGenerateList.Add("First");
                }
                if (curBooking.NeedToGenerateLastLetter)
                {
                    toGenerateList.Add("Last");
                }
                if (curPR.RegisterReferrer.ReportEveryVisitToReferrer && curBooking.NoteCount > 0)
                {
                    toGenerateList.Add("Notes");
                }
                string toGenerate = string.Join(",", (string[])toGenerateList.ToArray(typeof(string)));

                debugOutput += @"<tr>
                                    <td>" + sendMethod + @"</td>
                                    <td style=""white-space:nowrap;"">" + curBooking.BookingID + " &nbsp;&nbsp;&nbsp;[" + curBooking.DateStart.ToString("dd-MM-yyyy") + "&nbsp;&nbsp;&nbsp;" + curBooking.DateStart.ToString("HH:mm") + "-" + curBooking.DateEnd.ToString("HH:mm") + "]" + @"</td>
                                    <td>" + toGenerate + @"</td>
                                    <td>" + curPR.RegisterReferrer.Referrer.Person.FullnameWithoutMiddlename + @"</td>
                                    <td style=""white-space:nowrap;"">" + (curRefHasEmail ? refEmail : "") + @"</td>
                                    <td style=""white-space:nowrap;"">" + (curRefHasFax ? refFax : "") + @"</td>
                                    <td>" + curPR.Patient.Person.FullnameWithoutMiddlename + @"</td>
                                </tr>";
            }
        }

        return((Letter.FileContents[])filesToPrint.ToArray(typeof(Letter.FileContents)));
    }