private claim FindClaim(DataRow anImportRow, claim.ClaimTypes claimType)
        {
            string importID = anImportRow[dms.claim_id_column].ToString();
            string importDB = anImportRow[dms.claim_db_column].ToString();

            try
            {
                claim c = new claim();
                c.claimidnum = importID;
                c.claimdb    = importDB;
                DataTable matches = c.Search();

                if (matches.Rows.Count != 0)
                {
                    c.Load(matches.Rows[0]);
                }
                else
                {
                    // ****** Finding recreated claims *************
                    // Above, we checked for the common ID/DB match
                    // Here we try to find if a claim that is not in Tracker has been recreated
                    // We match by all fields minus 1 - if two primary fields have been changed
                    // Tracker can't track it
                    // If we find a possible match, we check to see that the current claim isn't in Dentrix
                    // to avoid false positives

                    bool     possibleMatchFound = false;
                    bool     claimInDentrix     = true;
                    claim    workingClaim       = new claim();
                    DateTime?dateOfService      = null;

                    try
                    { dateOfService = Convert.ToDateTime(anImportRow["PLDATE"]); }
                    catch { }
                    string  lastName              = anImportRow["PatLastName"].ToString();
                    string  firstName             = anImportRow["PatFirstName"].ToString();
                    decimal amount                = Convert.ToDecimal(anImportRow["TOTAL"]); // stored as cents
                    string  doctorFirstName       = anImportRow["DoctorFirstName"].ToString();
                    string  doctorLastName        = anImportRow["DoctorLastName"].ToString();
                    string  subscriberInsuranceID = anImportRow["ID_NUM_ON_CLAIM"].ToString();
                    string  matchingClaimInfo     = matchingClaimInfo = string.Format("Patient: {0}, Doctor: {1}, Total: {2}, DOS: {3}, Ins ID: {4}, ID: {5}, Type: {6}", firstName + " " + lastName,
                                                                                      doctorFirstName + " " + doctorLastName, amount, dateOfService, subscriberInsuranceID, importID + " | " + importDB, claimType.ToString());
                    int?newClaimID = null;



                    // Search for a patient match first. If the patient doesn't match try to match on the other two fields
                    workingClaim.patient_first_name = firstName;
                    workingClaim.patient_last_name  = lastName;

                    workingClaim.open = 1;
                    DataTable patientMatches = workingClaim.Search();

                    if (patientMatches.Rows.Count > 0)
                    {
                        // Iterate through all rows where the patient data matches
                        foreach (DataRow aRow in patientMatches.Rows)
                        {
                            int numMatchesForclaim = 0;
                            workingClaim.Load(aRow);

                            if (workingClaim.amount_of_claim * 100 == amount)
                            {
                                numMatchesForclaim++;
                            }
                            if (workingClaim.doctor_first_name == doctorFirstName && workingClaim.doctor_last_name == doctorLastName)
                            {
                                numMatchesForclaim++;
                            }
                            if (workingClaim.date_of_service == dateOfService)
                            {
                                numMatchesForclaim++;
                            }
                            if (workingClaim.subscriber_alternate_number == subscriberInsuranceID)
                            {
                                numMatchesForclaim++;
                            }
                            if (workingClaim.claim_type == claimType)
                            {
                                numMatchesForclaim++;
                            }


                            if (numMatchesForclaim >= 4)
                            {
                                // Found a claim that appears to match
                                newClaimID         = workingClaim.id;
                                possibleMatchFound = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        // Look for a match on date of service, amount, provider, insurance id, and type
                        workingClaim                             = new claim();
                        workingClaim.open                        = 1;
                        workingClaim.amount_of_claim             = amount / 100;
                        workingClaim.doctor_first_name           = doctorFirstName;
                        workingClaim.doctor_last_name            = doctorLastName;
                        workingClaim.subscriber_alternate_number = subscriberInsuranceID;
                        workingClaim.claim_type                  = claimType;


                        string    searchSQL    = workingClaim.SearchSQL + string.Format(" AND DATEDIFF(d, [date_of_service], '{0}') = 0", dateOfService.GetValueOrDefault().ToShortDateString());
                        DataTable otherMatches = workingClaim.Search(searchSQL);
                        if (otherMatches.Rows.Count > 0)
                        {
                            newClaimID         = (int)otherMatches.Rows[0]["id"];
                            possibleMatchFound = true;
                        }
                    }

                    if (possibleMatchFound)
                    {
                        // Check Dentrix to verify that the current ID/DB can't be found
                        if (newClaimID.HasValue && ClaimTrackerCommon.ClaimExists(new claim(newClaimID.Value))) // No match found
                        {
                            // Log this temporarily for recordkeeping
                            claimInDentrix = true;
                            AddReportMessage("Found a possible claim to merge, but the claim exists in Dentrix. Did not merge claim..." + matchingClaimInfo, true);
                            LoggingHelper.Log("Tried to merge a claim, but it was found in Dentrix. Claim info:\n" + matchingClaimInfo, LogSeverity.Information);
                        }
                        else
                        {
                            claimInDentrix = false;
                        }
                    }

                    if (!claimInDentrix && possibleMatchFound)
                    {
                        // Already loaded claim, should have "correct" data
                        c.Load(newClaimID.GetValueOrDefault(0));
                        AddReportMessage(string.Format("Merged a claim in Dentrix with an existing claim tracker claim. The claim's old ID/DB is {0}/{1}. The matching claim information is {2}",
                                                       c.claimidnum, c.claimdb, matchingClaimInfo), true);

                        c.claimidnum = importID;
                        c.claimdb    = importDB;

                        LoggingHelper.Log("Successfully merged a claim. \n" + matchingClaimInfo, LogSeverity.Information);
                    }
                    else
                    {
                        AddReportMessage("New claim imported - " + matchingClaimInfo);
                        c.created_by = "Automatic Database Importer";
                        c.updated_on = null;
                    }
                }
                return(c);
            }
            catch (Exception err)
            {
                // Somewhat dangerous, but it ensures that the import won't crash
                LoggingHelper.Log("Error in frmImportData.FindClaim", LogSeverity.Critical, err, false);
                claim c = new claim();
                c.claimidnum = importID;
                c.claimdb    = importDB;
                return(c);
            }
        }
        /// <summary>
        /// Returns a list of all Insurance Company Groups and all Insurance Companies not in a group
        /// </summary>
        /// <returns></returns>
        internal List <Claims_Primary.InsuranceCompanyGroups> GetInsuranceCompaniesAsGroup(bool includeMultipleCarriers = false)
        {
            List <Claims_Primary.InsuranceCompanyGroups> allGroups = new List <Claims_Primary.InsuranceCompanyGroups>();
            List <company>          companiesInAGroup = new List <company>();
            insurance_company_group icg = new insurance_company_group();

            foreach (DataRow aRow in icg.GetAllData("name").Rows)
            {
                icg = new insurance_company_group(aRow);

                if (includeMultipleCarriers || !icg.multiple_carriers)
                {
                    Claims_Primary.InsuranceCompanyGroups newGroup = new Claims_Primary.InsuranceCompanyGroups();
                    List <company> matchingComps = icg.GetMatchingCompanies();

                    newGroup.Name      = icg.name;
                    newGroup.Companies = matchingComps;
                    newGroup.Group     = icg;
                    allGroups.Add(newGroup);

                    companiesInAGroup.AddRange(matchingComps);
                }
            }

            string searchSQL;

            if (companiesInAGroup.Count == 0)
            {
                searchSQL = "SELECT * FROM companies ORDER BY name";
            }
            else
            {
                searchSQL = string.Format("SELECT * FROM companies WHERE ID NOT IN ({0}) ORDER BY name", ClaimTrackerCommon.CompaniesToInString(companiesInAGroup));
            }


            DataTable companiesNotInGroup = icg.Search(searchSQL);

            foreach (DataRow aRow in companiesNotInGroup.Rows)
            {
                company c = new company(aRow);
                Claims_Primary.InsuranceCompanyGroups newGroup = new Claims_Primary.InsuranceCompanyGroups(c.name, c);

                allGroups.Add(newGroup);
            }

            allGroups.Sort(SortInsuranceGroupsByName);

            return(allGroups);
        }