public void Simple_Results_JSON(HttpResponse Response, List <string> UrlSegments, NameValueCollection QueryString, Microservice_Endpoint_Protocol_Enum Protocol, bool IsDebug)
        {
            Custom_Tracer tracer = new Custom_Tracer();

            tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_JSON", "Parse request to determine search requested");

            // Get all the searh field necessary from the query string
            Results_Arguments args = new Results_Arguments(QueryString);

            // Additional results arguments
            // limit number of results
            int     artificial_result_limitation = -1;
            Boolean isNumeric = false;

            if (!String.IsNullOrEmpty(QueryString["limit_results"]))
            {
                isNumeric = Int32.TryParse(QueryString["limit_results"], out artificial_result_limitation);

                if (!isNumeric)
                {
                    artificial_result_limitation = -1;
                }
                else if (artificial_result_limitation < 1)
                {
                    artificial_result_limitation = -1;
                }
            }

            int pagenum = 1;

            if (!String.IsNullOrEmpty(QueryString["page"]))
            {
                isNumeric = Int32.TryParse(QueryString["page"], out pagenum);

                if (!isNumeric)
                {
                    pagenum = 1;
                }
                else if (pagenum < 1)
                {
                    pagenum = 1;
                }
                else if (pagenum > 1)
                {
                    artificial_result_limitation = -1;
                }
            }

            // Was a collection indicated?
            if (UrlSegments.Count > 0)
            {
                args.Aggregation = UrlSegments[0];
            }

            // Get the aggregation object (we need to know which facets to use, etc.. )
            tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_JSON", "Get the '" + args.Aggregation + "' item aggregation (for facets, etc..)");
            Complete_Item_Aggregation aggr = AggregationServices.get_complete_aggregation(args.Aggregation, true, tracer);

            // If no aggregation was returned, that is an error
            if (aggr == null)
            {
                tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_JSON", "Returned aggregation was NULL... aggregation code may not be valid");

                if (IsDebug)
                {
                    Response.ContentType = "text/plain";
                    Response.Output.WriteLine("DEBUG MODE DETECTED");
                    Response.Output.WriteLine();
                    Response.Output.WriteLine(tracer.Text_Trace);
                    return;
                }

                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Error occurred or aggregation '" + args.Aggregation + "' not valid");
                Response.StatusCode = 500;
                return;
            }

            // Perform the search
            tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_JSON", "Perform the search");
            Search_Results_Statistics   resultsStats;
            List <iSearch_Title_Result> resultsPage;
            ResultsEndpointErrorEnum    error = Get_Search_Results(args, aggr, false, tracer, out resultsStats, out resultsPage);


            // Was this in debug mode?
            // If this was debug mode, then just write the tracer
            if (IsDebug)
            {
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("DEBUG MODE DETECTED");
                Response.Output.WriteLine();
                Response.Output.WriteLine(tracer.Text_Trace);
                return;
            }

            Response.Output.WriteLine("{\"stats\":{\"total_items\":\"" + resultsStats.Total_Items + "\",\"total_titles\":\"" + resultsStats.Total_Titles + "\"},");
            Response.Output.WriteLine(" \"results\":[");

            // Map to the results object title / item
            tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_JSON", "Map to the results object title / item");
            int items_counter = 0;
            int resultnum     = 0;

            if (resultsPage != null)
            {
                foreach (iSearch_Title_Result thisResult in resultsPage)
                {
                    // Every results should have an item
                    if (thisResult.Item_Count == 0)
                    {
                        continue;
                    }
                    else
                    {
                        resultnum++;
                    }

                    if (artificial_result_limitation != -1 && resultnum > artificial_result_limitation)
                    {
                        tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML", "Reached limit [" + artificial_result_limitation + "].");
                        break;
                    }
                    // Was this NOT the first item?
                    if (items_counter > 0)
                    {
                        Response.Output.WriteLine(",");
                    }

                    Response.Output.Write("        ");
                    items_counter++;

                    // add each descriptive field over
                    iSearch_Item_Result itemResult = thisResult.Get_Item(0);

                    string bibid     = thisResult.BibID;
                    string title     = thisResult.GroupTitle;
                    string vid       = itemResult.VID;
                    string thumbnail = itemResult.MainThumbnail;

                    // {"bibid":"1212", "vid":"00001", "title":"sdsd", "subjects":["subj1", "subj2", "subj3"] },

                    Response.Output.Write("{ \"bibid\":\"" + bibid + "\", \"vid\":\"" + vid + "\", ");
                    Response.Output.Write("\"title\":\"" + HttpUtility.HtmlEncode(title) + "\",");
                    Response.Output.Write("\"url_item\":\"" + Engine_ApplicationCache_Gateway.Settings.Servers.Application_Server_URL + bibid + "/" + vid + "/\",");
                    Response.Output.Write("\"url_thumbnail\":\"" + Engine_ApplicationCache_Gateway.Settings.Servers.Image_URL +
                                          SobekFileSystem.AssociFilePath(bibid, vid).Replace("\\", "/") + thumbnail + "\"");

                    int field_index = 0;

                    if (resultsStats.Metadata_Labels.Count > 0)
                    {
                        foreach (string metadataTerm in resultsStats.Metadata_Labels)
                        {
                            if (!String.IsNullOrWhiteSpace(thisResult.Metadata_Display_Values[field_index]))
                            {
                                // how to display this metadata field?
                                string metadataTermDisplay = metadataTerm;

                                string termString = thisResult.Metadata_Display_Values[field_index];
                                Response.Output.Write(",\"" + metadataTermDisplay + "\":[");

                                int individual_term_counter = 0;

                                if (termString.IndexOf("|") > 0)
                                {
                                    string[] splitter = termString.Split("|".ToCharArray());

                                    foreach (string thisSplit in splitter)
                                    {
                                        if (!String.IsNullOrWhiteSpace(thisSplit))
                                        {
                                            if (individual_term_counter > 0)
                                            {
                                                Response.Output.Write(", \"" + HttpUtility.HtmlEncode(thisSplit.Trim()) + "\"");
                                            }
                                            else
                                            {
                                                Response.Output.Write("\"" + HttpUtility.HtmlEncode(thisSplit.Trim()) + "\"");
                                            }

                                            individual_term_counter++;
                                        }
                                    }
                                }
                                else
                                {
                                    Response.Output.Write("\"" + HttpUtility.HtmlEncode(termString.Trim()) + "\"");
                                }

                                Response.Output.Write("]");
                            }

                            field_index++;
                        }
                    }

                    Response.Output.Write("}");
                }
            }

            Response.Output.WriteLine();
            Response.Output.WriteLine("    ]");
            Response.Output.WriteLine("} ");

            // If an error occurred, return the error
            switch (error)
            {
            case ResultsEndpointErrorEnum.Database_Exception:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Database exception");
                Response.StatusCode = 500;
                return;

            case ResultsEndpointErrorEnum.Database_Timeout_Exception:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Database timeout");
                Response.StatusCode = 500;
                return;

            case ResultsEndpointErrorEnum.Solr_Exception:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Solr exception");
                Response.StatusCode = 500;
                return;

            case ResultsEndpointErrorEnum.Unknown:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Unknown error");
                Response.StatusCode = 500;
                return;
            }
        }
        /// <summary> Get just the search statistics information for a search or browse </summary>
        /// <param name="Response"></param>
        /// <param name="UrlSegments"></param>
        /// <param name="QueryString"></param>
        /// <param name="Protocol"></param>
        /// <param name="IsDebug"></param>
        public void AGGCOUNTS_Results_XML(HttpResponse Response, List <string> UrlSegments, NameValueCollection QueryString, Microservice_Endpoint_Protocol_Enum Protocol, bool IsDebug)
        {
            double                 started = DateTimeToUnixTimestamp(DateTime.Now);
            double                 ended;
            Results_Arguments      args = new Results_Arguments(QueryString);
            String                 url, data, dataaggs, code, name, isActive, isHidden, id, type;
            XmlDocument            doc, docaggs;
            XmlNodeList            nodes;
            XmlNode                solrnode;
            XmlAttributeCollection attrs;
            DataSet                tempSet = null, darkSet = null, aliasesSet = null;
            DataTable              aggregations, darkAggregations, aliases;
            int   idx        = 0;
            short mask       = 0;
            long  count      = 0;
            int   errorcount = 0;

            Response.Output.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>");
            //Response.Output.WriteLine("<!-- connection string is " + SecurityElement.Escape(Engine_Database.Connection_String) + "]. -->");

            url = "http://dis.lib.usf.edu:8080/documents/select/?q=%28*:*%29&rows=0&facet=true&facet.field=aggregation_code&facet.limit=-1";
            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] raw       = wc.DownloadData(url);
            dataaggs = System.Text.Encoding.UTF8.GetString(raw);
            //dataaggs = dataaggs.Replace("<response>", "<response xmlns=\"http://dummy.solr.org/dummy\">");
            //Response.Output.WriteLine("<!-- got " + dataaggs.Length + " bytes from solr -->");
            docaggs = new XmlDocument();

            try
            {
                docaggs.LoadXml(dataaggs);
                //Response.Output.WriteLine("<!-- loaded xml into docaggs successfully. -->");
            }
            catch (XmlException e)
            {
                docaggs = null;
                //Response.Output.WriteLine("<!-- xmlexception trying to load solr xml into docaggs-->");
            }

            Dictionary <String, String> solraggs = new Dictionary <String, String>();

            byte[] byteArray = Encoding.ASCII.GetBytes(dataaggs);
            //Response.Output.WriteLine("<!-- " + byteArray.Length + " elements in byteArray -->");
            MemoryStream stream = new MemoryStream(byteArray);
            //Response.Output.WriteLine("<!-- " + stream.Length + " bytes in stream -->");

            XElement root = XElement.Load(stream);

            if (root.HasElements)
            {
                //Response.Output.WriteLine("<!-- root has elements -->");
            }
            else
            {
                //Response.Output.WriteLine("<!-- root has NO elements -->");
            }

            IEnumerable <XElement> aggs =
                from agg in root.Descendants("int")
                select agg;

            //Response.Output.WriteLine("<!-- aggCount=" + aggs.Count() + " -->");
            String myvalue;

            if (aggs.Count() > 0)
            {
                idx = 0;

                foreach (XElement agg in aggs)
                {
                    idx++;

                    try
                    {
                        myvalue = agg.Value;
                    }
                    catch (Exception e)
                    {
                        myvalue = "0";
                    }

                    try
                    {
                        //Response.Output.WriteLine("<!-- agg " + idx + ". " + agg.Attribute("name").Value.ToLower() + "=" + myvalue + " -->");

                        solraggs.Add(agg.Attribute("name").Value.ToString().ToLower(), myvalue);
                    }
                    catch (Exception e)
                    {
                        //Response.Output.WriteLine("<!-- exception trying to display or add to solraggs [" + e.Message + "] -->");
                    }
                }

                //Response.Output.WriteLine("<!-- solraggs has " + solraggs.Count + "  entries -->");
            }

            /*
             * try
             * {
             *  int idxelements = 0;
             *
             *  foreach (XElement myelement in XElement.Load(stream).Elements("lst"))
             *  {
             *      idxelements++;
             *
             *      Response.Output.WriteLine("<!-- myelement@name=" + myelement.Attribute("name").Value + " -->");
             *
             *      if (myelement.Attribute("name").Value == "facet_counts")
             *      {
             *          foreach (XElement mysubelement in myelement.Elements("int"))
             *          {
             *              Response.Output.WriteLine("<!-- mysubelement: " + mysubelement.Attribute("name").Value + " -->");
             *
             *              solraggs.Add(new KeyValuePair<String, String>(mysubelement.Attribute("name").Value.ToString(), mysubelement.Value.ToString()));
             *
             *          }
             *      }
             *  }
             *
             *  Response.Output.WriteLine("<!-- idxelements=" + idxelements + " -->");
             * }
             * catch (Exception e)
             * {
             *  Response.Output.WriteLine("<!-- exception trying to get solraggs [" + e.Message + "]:[" + e.StackTrace + "] -->");
             *  solraggs = null;
             * }
             *
             * if (solraggs==null)
             * {
             *  Response.Output.WriteLine("<!-- solraggs was null -->");
             * }
             * else
             * {
             *  Response.Output.WriteLine("<!-- solraggs count=" + solraggs.Count + " -->");
             * }
             *
             * if (solraggs!=null && solraggs.Count>0)
             * {
             *  Response.Output.WriteLine("<!-- there are " + solraggs.Count + " in solraggs list -->");
             *
             *  foreach  (KeyValuePair<String,String> agg in solraggs)
             *  {
             *      Response.Output.WriteLine("<!-- " + agg.Key + "=" + agg.Value + " -->");
             *  }
             * }
             * else
             * {
             *  Response.Output.WriteLine("<!-- solraggs was null or had no count -->");
             * }
             *
             */

            try
            {
                EalDbParameter[] paramList = new EalDbParameter[2];
                tempSet = EalDbAccess.ExecuteDataset(EalDbTypeEnum.MSSQL, Engine_Database.Connection_String, CommandType.StoredProcedure, "SobekCM_Get_Item_Aggregation_Status_Counts", paramList);

                //Response.Output.WriteLine("<!-- tempSet has " + tempSet.Tables.Count + " tables. -->");
                //Response.Output.WriteLine("<!-- tempSet table 0 has " + tempSet.Tables[0].Rows.Count + " rows -->");

                aggregations = tempSet.Tables[0];
            }
            catch (Exception e)
            {
                aggregations = null;
                Response.Output.WriteLine("<!-- " + e.Message + " -->");
            }

            // darkSet
            try
            {
                EalDbParameter[] paramList = new EalDbParameter[2];
                darkSet = EalDbAccess.ExecuteDataset(EalDbTypeEnum.MSSQL, Engine_Database.Connection_String, CommandType.StoredProcedure, "SobekCM_Get_Item_Aggregation_Dark_Counts", paramList);

                //Response.Output.WriteLine("<!-- tempSet has " + tempSet.Tables.Count + " tables. -->");
                //Response.Output.WriteLine("<!-- tempSet table 0 has " + tempSet.Tables[0].Rows.Count + " rows -->");

                darkAggregations = darkSet.Tables[0];
            }
            catch (Exception e)
            {
                darkAggregations = null;
                Response.Output.WriteLine("<!-- " + e.Message + " -->");
            }

            //aliasSet
            try
            {
                EalDbParameter[] paramList = new EalDbParameter[2];
                aliasesSet = EalDbAccess.ExecuteDataset(EalDbTypeEnum.MSSQL, Engine_Database.Connection_String, CommandType.StoredProcedure, "SobekCM_Get_Item_Aggregation_Aliases", paramList);
                aliases    = aliasesSet.Tables[0];
            }
            catch (Exception e)
            {
                aliases = null;
                Response.Output.WriteLine("<!-- exception trying to get aliasesSet [" + e.Message + "] -->");
            }

            url = Engine_ApplicationCache_Gateway.Settings.Servers.Application_Server_URL + "/engine/aggregations/all/xml";

            wc   = new System.Net.WebClient();
            raw  = wc.DownloadData(url);
            data = System.Text.Encoding.UTF8.GetString(raw);
            doc  = new XmlDocument();
            doc.LoadXml(data);

            nodes = doc.SelectNodes("//Item_Aggregation_Related_Aggregations");
            idx   = 0;

            Response.Output.WriteLine("<results date=\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\" count=\"" + nodes.Count + "\">");

            foreach (XmlNode node in nodes)
            {
                idx++;

                attrs    = node.Attributes;
                code     = attrs["code"].Value.ToLower();
                name     = attrs["name"].Value;
                isActive = attrs["isActive"].Value;
                isHidden = attrs["isHidden"].Value;
                id       = attrs["id"].Value;
                type     = attrs["type"].Value;

                Response.Output.Write("<result rownum=\"" + idx + "\" code=\"" + code + "\" name=\"" + SecurityElement.Escape(name) + "\" id=\"" + id + "\" type=\"" + type + "\" isActive=\"" + isActive + "\" isHidden=\"" + isHidden + "\" ");

                IEnumerable <DataRow> query =
                    from aggregation in aggregations.AsEnumerable()
                    select aggregation;

                IEnumerable <DataRow> thisagg =
                    query.Where(p => p.Field <string>("code").Equals(code));

                foreach (DataRow p in thisagg)
                {
                    //Response.Output.WriteLine("<counts code=\"" + p.Field<String>("code") + "\">");

                    try
                    {
                        try
                        {
                            mask = p.Field <short>("mask");
                        }
                        catch (Exception e)
                        {
                            mask = 999;
                        }

                        try
                        {
                            //Response.Output.WriteLine(" mycount=\"" + p["count"].ToString() + "\" ");
                            count = long.Parse(p["count"].ToString());
                        }
                        catch (Exception e)
                        {
                            count = 32767;
                            errorcount++;
                            Response.Output.Write("error" + errorcount + "=\"" + e.Message + " [" + SecurityElement.Escape(e.StackTrace) + "]\" ");
                        }

                        if (mask == 0)
                        {
                            Response.Output.Write("count_public=\"" + count + "\" ");
                        }
                        else if (mask == -1)
                        {
                            Response.Output.Write("count_private=\"" + count + "\" ");
                        }
                        else
                        {
                            Response.Output.Write("count_mask" + Math.Abs(mask) + "=\"" + count + "\" ");
                        }
                    }
                    catch (Exception e)
                    {
                        errorcount++;
                        Response.Output.Write(" error" + errorcount + "=\"mask or count retrieval issue - " + e.Message + " [" + SecurityElement.Escape(e.StackTrace) + "]\" ");
                    }
                }

                // dark
                query =
                    from dark in darkAggregations.AsEnumerable()
                    select dark;

                thisagg = query.Where(p => p.Field <string>("code").Equals(code));

                foreach (DataRow p in thisagg)
                {
                    Response.Output.Write("count_dark=\"" + p["count"] + "\" ");
                }

                try
                {
                    // aliases
                    query =
                        from alias in aliases.AsEnumerable()
                        select alias;

                    IEnumerable <DataRow> thisaliases = query.Where(p => p.Field <string>("Code").Equals(code));

                    String cids = "";

                    foreach (DataRow p in thisaliases)
                    {
                        cids += p["AggregationAlias"].ToString().ToUpper() + ",";
                    }

                    if (cids.Length > 0)
                    {
                        cids = cids.Substring(0, cids.Length - 1);

                        if (cids.Length > 3)
                        {
                            Response.Output.Write("aliases=");
                        }
                        else
                        {
                            Response.Output.Write("alias=");
                        }

                        Response.Output.Write("\"" + cids + "\" ");
                    }
                    else
                    {
                        Response.Output.Write("alias=\"NONE\" ");
                    }
                }
                catch (Exception e)
                {
                    errorcount++;
                    Response.Output.Write("error" + errorcount + "=\"trying to get cids [" + e.Message + "]\" ");
                }

                try
                {
                    // >xpath("//lst[@name='aggregation_code']/int");

                    /*
                     * solrnode = docaggs.SelectSingleNode("//results/lst[@name='facet_counts']/lst[@name='facet_fields']/lst[@name='aggregation_code']/int[@name='" + code.ToUpper() + "']/text()");
                     *
                     * if (solrnode != null)
                     * {
                     *  Response.Output.WriteLine(" indexed=\"" + solrnode.Value + "\" ");
                     * }
                     * else
                     * {
                     *  errorcount++;
                     *  Response.Output.WriteLine(" error" + errorcount + "=\"solrnode was null\" ");
                     * }
                     */


                    String indexedcount = solraggs[code];

                    Response.Output.Write("count_indexed=\"" + indexedcount + "\" ");
                }
                catch (Exception e)
                {
                    errorcount++;
                    Response.Output.Write("count_indexed=\"0\" ");
                }

                Response.Output.Write("/>\r\n");
            }

            Response.Output.WriteLine("</results>");

            ended = DateTimeToUnixTimestamp(DateTime.Now);

            Response.Output.WriteLine("<!-- generated in " + (ended - started) + " seconds. -->");
        }
        public void Simple_Results_XML(HttpResponse Response, List <string> UrlSegments, NameValueCollection QueryString, Microservice_Endpoint_Protocol_Enum Protocol, bool IsDebug)
        {
            // Local trace
            Custom_Tracer tracer = new Custom_Tracer();

            tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML");

            // Get all the searh field necessary from the query string
            Results_Arguments args = new Results_Arguments(QueryString);

            // Additional results arguments
            // limit number of results
            int     artificial_result_limitation = -1;
            Boolean isNumeric = false;

            if (!String.IsNullOrEmpty(QueryString["limit_results"]))
            {
                isNumeric = Int32.TryParse(QueryString["limit_results"], out artificial_result_limitation);

                if (!isNumeric)
                {
                    artificial_result_limitation = -1;
                }
                else if (artificial_result_limitation < 1)
                {
                    artificial_result_limitation = -1;
                }
            }

            int pagenum = 1;

            if (!String.IsNullOrEmpty(QueryString["page"]))
            {
                isNumeric = Int32.TryParse(QueryString["page"], out pagenum);

                if (!isNumeric)
                {
                    pagenum = 1;
                }
                else if (pagenum < 1)
                {
                    pagenum = 1;
                }
                else if (pagenum > 1)
                {
                    artificial_result_limitation = -1;
                }
            }

            // Was a collection indicated?
            if (UrlSegments.Count > 0)
            {
                args.Aggregation = UrlSegments[0];
            }

            // Get the aggregation object (we need to know which facets to use, etc.. )
            tracer.Add_Trace("SimpleResultsEndpoints.Get_Search_Results_Set", "Get the '" + args.Aggregation + "' item aggregation (for facets, etc..)");
            Complete_Item_Aggregation aggr = AggregationServices.get_complete_aggregation(args.Aggregation, true, tracer);

            // If no aggregation was returned, that is an error
            if (aggr == null)
            {
                tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML", "Returned aggregation was NULL... aggregation code may not be valid");

                if (IsDebug)
                {
                    Response.ContentType = "text/plain";
                    Response.Output.WriteLine("DEBUG MODE DETECTED");
                    Response.Output.WriteLine();
                    Response.Output.WriteLine(tracer.Text_Trace);
                    return;
                }

                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Error occurred or aggregation '" + args.Aggregation + "' not valid");
                Response.StatusCode = 500;
                return;
            }

            // Perform the search
            tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML", "Perform the search");
            Search_Results_Statistics   resultsStats;
            List <iSearch_Title_Result> resultsPage;
            ResultsEndpointErrorEnum    error = Get_Search_Results(args, aggr, false, tracer, out resultsStats, out resultsPage);

            // Was this in debug mode?
            // If this was debug mode, then just write the tracer
            if (IsDebug)
            {
                tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML", "Debug mode detected");

                Response.ContentType = "text/plain";
                Response.Output.WriteLine("DEBUG MODE DETECTED");
                Response.Output.WriteLine();
                Response.Output.WriteLine(tracer.Text_Trace);
                return;
            }

            try
            {
                tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML", "Begin writing the XML result to the response");
                Response.Output.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>");

                int count_pages = (int)Math.Floor((double)resultsStats.Total_Items / 20);

                if (count_pages == 0)
                {
                    count_pages = 1;
                }

                if (pagenum > count_pages)
                {
                    pagenum = count_pages;
                }

                Response.Output.WriteLine("<results total_items=\"" + resultsStats.Total_Items + "\" total_titles=\"" + resultsStats.Total_Titles + "\" page_count=\"" + count_pages + "\" max_results_per_page=\"20\"");

                if (artificial_result_limitation != -1)
                {
                    Response.Output.WriteLine("limit_results=\"" + artificial_result_limitation + "\"");
                }

                Response.Output.WriteLine(">");

                // Map to the results object title / item
                tracer.Add_Trace("SimpleResultsEndpoints.Get_Search_Results_Set", "Map to the results object title / item");

                // resultnum
                int resultnum = 0;

                if (pagenum > 1)
                {
                    resultnum = ((pagenum - 1) * 20);
                }

                if (resultsPage != null)
                {
                    foreach (iSearch_Title_Result thisResult in resultsPage)
                    {
                        // Every results should have an item
                        if (thisResult.Item_Count == 0)
                        {
                            continue;
                        }
                        else
                        {
                            resultnum++;
                        }

                        if (artificial_result_limitation != -1 && resultnum > artificial_result_limitation)
                        {
                            tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML", "Reached limit [" + artificial_result_limitation + "].");
                            break;
                        }

                        // add each descriptive field over
                        iSearch_Item_Result itemResult = thisResult.Get_Item(0);

                        string bibid     = thisResult.BibID;
                        string title     = thisResult.GroupTitle;
                        string vid       = itemResult.VID;
                        string thumbnail = itemResult.MainThumbnail;

                        Response.Output.WriteLine("  <result resultnum=\"" + resultnum + "\" bibid=\"" + bibid + "\" vid=\"" + vid + "\">");
                        Response.Output.WriteLine("    <title>" + HttpUtility.HtmlEncode(title) + "</title>");
                        Response.Output.WriteLine("    <url_item>" + Engine_ApplicationCache_Gateway.Settings.Servers.Application_Server_URL + bibid + "/" + vid + "/</url_item>");

                        if (!String.IsNullOrEmpty(thumbnail))
                        {
                            try
                            {
                                Response.Output.WriteLine("    <url_thumbnail>" + Engine_ApplicationCache_Gateway.Settings.Servers.Image_URL +
                                                          SobekFileSystem.AssociFilePath(bibid, vid).Replace("\\", "/") + thumbnail.Trim() + "</url_thumbnail>");
                            }
                            catch (Exception ee)
                            {
                                Response.Output.WriteLine("ERROR WRITING THUMBNAIL");
                                Response.Output.WriteLine(ee.Message);
                                Response.Output.WriteLine(ee.StackTrace);
                            }
                        }

                        int field_index = 0;

                        if (resultsStats.Metadata_Labels.Count > 0)
                        {
                            Response.Output.WriteLine("<metadata>");

                            foreach (string metadataTerm in resultsStats.Metadata_Labels)
                            {
                                if (!String.IsNullOrWhiteSpace(thisResult.Metadata_Display_Values[field_index]))
                                {
                                    // how to display this metadata field?
                                    string metadataTermDisplay = metadataTerm;
                                    string termString          = thisResult.Metadata_Display_Values[field_index];

                                    if (termString.IndexOf("|") > 0)
                                    {
                                        string[] splitter = termString.Split("|".ToCharArray());

                                        foreach (string thisSplit in splitter)
                                        {
                                            if (!String.IsNullOrWhiteSpace(thisSplit))
                                            {
                                                Response.Output.WriteLine("    <" + metadataTermDisplay + ">" + HttpUtility.HtmlEncode(thisSplit.Trim()) + "</" + metadataTermDisplay + ">");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Response.Output.WriteLine("    <" + metadataTermDisplay + ">" + HttpUtility.HtmlEncode(termString.Trim()) + "</" + metadataTermDisplay + ">");
                                    }
                                }

                                field_index++;
                            }

                            Response.Output.WriteLine("</metadata>");
                        }

                        Response.Output.WriteLine("  </result>");
                    }
                }

                Response.Output.WriteLine("</results>");

                tracer.Add_Trace("SimpleResultsEndpoints.Simple_Results_XML", "Done writing the XML result to the response");
            }
            catch (Exception ee)
            {
                Response.Output.Write(ee.Message);
                Response.Output.Write(ee.StackTrace);
            }

            // If an error occurred, return the error
            switch (error)
            {
            case ResultsEndpointErrorEnum.Database_Exception:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Database exception");
                Response.StatusCode = 500;
                return;

            case ResultsEndpointErrorEnum.Database_Timeout_Exception:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Database timeout");
                Response.StatusCode = 500;
                return;

            case ResultsEndpointErrorEnum.Solr_Exception:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Solr exception");
                Response.StatusCode = 500;
                return;

            case ResultsEndpointErrorEnum.Unknown:
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("Unknown error");
                Response.StatusCode = 500;
                return;
            }

            // If debug, show the trace
            if (IsDebug)
            {
                Response.ContentType = "text/plain";
                Response.Output.WriteLine("DEBUG MODE DETECTED");
                Response.Output.WriteLine();
                Response.Output.WriteLine(tracer.Text_Trace);
                return;
            }
        }