Option -d dumps records to the current log file instead of stderr.
[pazpar2-moved-to-github.git] / src / logic.c
index 624a474..f8a8f4d 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: logic.c,v 1.22 2007-04-26 11:03:54 marc Exp $
+/* $Id: logic.c,v 1.52 2007-07-16 09:00:22 adam Exp $
    Copyright (c) 2006-2007, Index Data.
 
 This file is part of Pazpar2.
@@ -45,9 +45,7 @@ Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
 #include <yaz/nmem.h>
 #include <yaz/query-charset.h>
 #include <yaz/querytowrbuf.h>
-#if YAZ_VERSIONL >= 0x020163
 #include <yaz/oid_db.h>
-#endif
 
 #if HAVE_CONFIG_H
 #include "cconfig.h"
@@ -70,6 +68,9 @@ Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
 #include "database.h"
 #include "client.h"
 #include "settings.h"
+#include "normalize7bit.h"
+
+#define TERMLIST_HIGH_SCORE 25
 
 #define MAX_CHUNK 15
 
@@ -78,10 +79,10 @@ struct parameters global_parameters =
 {
     "",
     "",
-    "",
-    "",
-    0,
+    "", 
     0,
+    0, /* dump_records */
+    0, /* debug_mode */
     30,
     "81",
     "Index Data PazPar2",
@@ -121,75 +122,6 @@ void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
     }
 }
 
-char *normalize_mergekey(char *buf, int skiparticle)
-{
-    char *p = buf, *pout = buf;
-
-    if (skiparticle)
-    {
-        char firstword[64];
-        char articles[] = "the den der die des an a "; // must end in space
-
-        while (*p && !isalnum(*p))
-            p++;
-        pout = firstword;
-        while (*p && *p != ' ' && pout - firstword < 62)
-            *(pout++) = tolower(*(p++));
-        *(pout++) = ' ';
-        *(pout++) = '\0';
-        if (!strstr(articles, firstword))
-            p = buf;
-        pout = buf;
-    }
-
-    while (*p)
-    {
-        while (*p && !isalnum(*p))
-            p++;
-        while (isalnum(*p))
-            *(pout++) = tolower(*(p++));
-        if (*p)
-            *(pout++) = ' ';
-        while (*p && !isalnum(*p))
-            p++;
-    }
-    if (buf != pout)
-        do {
-            *(pout--) = '\0';
-        }
-        while (pout > buf && *pout == ' ');
-
-    return buf;
-}
-
-// Extract what appears to be years from buf, storing highest and
-// lowest values.
-static int extract_years(const char *buf, int *first, int *last)
-{
-    *first = -1;
-    *last = -1;
-    while (*buf)
-    {
-        const char *e;
-        int len;
-
-        while (*buf && !isdigit(*buf))
-            buf++;
-        len = 0;
-        for (e = buf; *e && isdigit(*e); e++)
-            len++;
-        if (len == 4)
-        {
-            int value = atoi(buf);
-            if (*first < 0 || value < *first)
-                *first = value;
-            if (*last < 0 || value > *last)
-                *last = value;
-        }
-        buf = e;
-    }
-    return *first;
-}
 
 
 static void add_facet(struct session *s, const char *type, const char *value)
@@ -211,118 +143,159 @@ static void add_facet(struct session *s, const char *type, const char *value)
 
         s->termlists[i].name = nmem_strdup(s->nmem, type);
         s->termlists[i].termlist 
-            = termlist_create(s->nmem, s->expected_maxrecs, 15);
+            = termlist_create(s->nmem, s->expected_maxrecs,
+                              TERMLIST_HIGH_SCORE);
         s->num_termlists = i + 1;
     }
     termlist_insert(s->termlists[i].termlist, value);
 }
 
-xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
+xmlDoc *record_to_xml(struct session_database *sdb, Z_External *rec)
 {
-    struct database_retrievalmap *m;
     struct database *db = sdb->database;
-    xmlNode *res;
-    xmlDoc *rdoc;
+    xmlDoc *rdoc = 0;
+    const Odr_oid *oid = rec->direct_reference;
 
-    // First normalize to XML
-    if (sdb->yaz_marc)
+    /* convert response record to XML somehow */
+    if (rec->which == Z_External_octet && oid
+        && !oid_oidcmp(oid, yaz_oid_recsyn_xml))
     {
-        char *buf;
-        int len;
-        if (rec->which != Z_External_octet)
+        /* xml already */
+        rdoc = xmlParseMemory((char*) rec->u.octet_aligned->buf,
+                              rec->u.octet_aligned->len);
+        if (!rdoc)
         {
-            yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
+            yaz_log(YLOG_FATAL, "Non-wellformed XML received from %s",
                     db->url);
             return 0;
         }
-        buf = (char*) rec->u.octet_aligned->buf;
-        len = rec->u.octet_aligned->len;
-        if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
+    }
+    else if (rec->which == Z_External_OPAC)
+    {
+        if (!sdb->yaz_marc)
         {
-            yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
+            yaz_log(YLOG_WARN, "MARC decoding not configured");
             return 0;
         }
-
-        yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
-        if (yaz_marc_write_xml(sdb->yaz_marc, &res,
-                    "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
+        else
         {
-            yaz_log(YLOG_WARN, "Failed to encode as XML %s",
-                    db->url);
+            /* OPAC gets converted to XML too */
+            WRBUF wrbuf_opac = wrbuf_alloc();
+            /* MARCXML inside the OPAC XML. Charset is in effect because we
+               use the yaz_marc handle */
+            yaz_marc_xml(sdb->yaz_marc, YAZ_MARC_MARCXML);
+            yaz_opac_decode_wrbuf(sdb->yaz_marc, rec->u.opac, wrbuf_opac);
+            
+            rdoc = xmlParseMemory((char*) wrbuf_buf(wrbuf_opac),
+                                  wrbuf_len(wrbuf_opac));
+            if (!rdoc)
+                yaz_log(YLOG_WARN, "Unable to parse OPAC XML");
+            wrbuf_destroy(wrbuf_opac);
+        }
+    }
+    else if (oid && yaz_oid_is_iso2709(oid))
+    {
+        /* ISO2709 gets converted to MARCXML */
+        if (!sdb->yaz_marc)
+        {
+            yaz_log(YLOG_WARN, "MARC decoding not configured");
             return 0;
         }
-        rdoc = xmlNewDoc((xmlChar *) "1.0");
-        xmlDocSetRootElement(rdoc, res);
-
+        else
+        {
+            xmlNode *res;
+            char *buf;
+            int len;
+            
+            if (rec->which != Z_External_octet)
+            {
+                yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
+                        db->url);
+                return 0;
+            }
+            buf = (char*) rec->u.octet_aligned->buf;
+            len = rec->u.octet_aligned->len;
+            if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
+            {
+                yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
+                return 0;
+            }
+            
+            yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
+            if (yaz_marc_write_xml(sdb->yaz_marc, &res,
+                                   "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
+            {
+                yaz_log(YLOG_WARN, "Failed to encode as XML %s",
+                        db->url);
+                return 0;
+            }
+            rdoc = xmlNewDoc((xmlChar *) "1.0");
+            xmlDocSetRootElement(rdoc, res);
+        }
     }
     else
     {
+        char oid_name_buf[OID_STR_MAX];
+        const char *oid_name = yaz_oid_to_string_buf(oid, 0, oid_name_buf);
         yaz_log(YLOG_FATAL, 
-                "Unknown native_syntax in normalize_record from %s",
-                db->url);
+                "Unable to handle record of type %s from %s", 
+                oid_name, db->url);
         return 0;
     }
-
-    if (global_parameters.dump_records){
-        fprintf(stderr, 
-                "Input Record (normalized) from %s\n----------------\n",
-                db->url);
+    
+    if (global_parameters.dump_records)
+    {
+        FILE *lf = yaz_log_file();
+        if (lf)
+        {
+            yaz_log(YLOG_LOG, "Normalized record from %s", db->url);
 #if LIBXML_VERSION >= 20600
-        xmlDocFormatDump(stderr, rdoc, 1);
+            xmlDocFormatDump(lf, rdoc, 1);
 #else
-        xmlDocDump(stderr, rdoc);
+            xmlDocDump(lf, rdoc);
 #endif
+            fprintf(lf, "\n");
+        }
     }
+    return rdoc;
+}
 
-    for (m = sdb->map; m; m = m->next){
-        xmlDoc *new = 0;
-
-#if 1
-        {
-            xmlNodePtr root = 0;
-            new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
-            root= xmlDocGetRootElement(new);
-        if (!new || !root || !(root->children))
-        {
-            yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
-                    sdb->database->url);
-            xmlFreeDoc(new);
+xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
+{
+    struct database_retrievalmap *m;
+    xmlDoc *rdoc = record_to_xml(sdb, rec);
+    if (rdoc)
+    {
+        for (m = sdb->map; m; m = m->next){
+            xmlDoc *new = 0;
+            
+            {
+                xmlNodePtr root = 0;
+                new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
+                root= xmlDocGetRootElement(new);
+                if (!new || !root || !(root->children))
+                {
+                    yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
+                            sdb->database->url);
+                    xmlFreeDoc(new);
+                    xmlFreeDoc(rdoc);
+                    return 0;
+                }
+            }
+            
             xmlFreeDoc(rdoc);
-            return 0;
-        }
+            rdoc = new;
         }
-#endif
-
-#if 0
-        // do it another way to detect transformation errors right now
-        // but does not seem to work either!
+        if (global_parameters.dump_records)
         {
-            xsltTransformContextPtr ctxt;
-            ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
-            new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
-            if ((ctxt->state == XSLT_STATE_ERROR) ||
-                (ctxt->state == XSLT_STATE_STOPPED)){
-                yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
-                        cl->database->database->url);
-                xmlFreeDoc(new);
-                xmlFreeDoc(rdoc);
-                return 0;
-            }
-        }
-#endif      
-   
-        xmlFreeDoc(rdoc);
-        rdoc = new;
-    }
-    if (global_parameters.dump_records)
-    {
-        fprintf(stderr, "Record from %s\n----------------\n", 
-                sdb->database->url);
+            fprintf(stderr, "Record from %s\n----------------\n", 
+                    sdb->database->url);
 #if LIBXML_VERSION >= 20600
-        xmlDocFormatDump(stderr, rdoc, 1);
+            xmlDocFormatDump(stderr, rdoc, 1);
 #else
-        xmlDocDump(stderr, rdoc);
+            xmlDocDump(stderr, rdoc);
 #endif
+        }
     }
     return rdoc;
 }
@@ -401,7 +374,7 @@ static int prepare_map(struct session *se, struct session_database *sdb)
             (*m)->next = 0;
             if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
             {
-                yaz_log(YLOG_FATAL, "Unable to load stylesheet: %s",
+                yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
                         stylesheets[i]);
                 return -1;
             }
@@ -438,21 +411,39 @@ static int prepare_session_database(struct session *se,
     return 0;
 }
 
+// called if watch should be removed because http_channel is to be destroyed
+static void session_watch_cancel(void *data, struct http_channel *c)
+{
+    struct session_watchentry *ent = data;
+
+    ent->fun = 0;
+    ent->data = 0;
+    ent->obs = 0;
+}
 
-void session_set_watch(struct session *s, int what, 
-                       session_watchfun fun, void *data)
+// set watch. Returns 0=OK, -1 if watch is already set
+int session_set_watch(struct session *s, int what, 
+                      session_watchfun fun, void *data,
+                      struct http_channel *chan)
 {
+    if (s->watchlist[what].fun)
+        return -1;
     s->watchlist[what].fun = fun;
     s->watchlist[what].data = data;
+    s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
+                                               session_watch_cancel);
+    return 0;
 }
 
 void session_alert_watch(struct session *s, int what)
 {
     if (!s->watchlist[what].fun)
         return;
+    http_remove_observer(s->watchlist[what].obs);
     (*s->watchlist[what].fun)(s->watchlist[what].data);
     s->watchlist[what].fun = 0;
     s->watchlist[what].data = 0;
+    s->watchlist[what].obs = 0;
 }
 
 //callback for grep_databases
@@ -528,14 +519,19 @@ static struct database_criterion *parse_filter(NMEM m, const char *buf)
     return res;
 }
 
-char *search(struct session *se, char *query, char *filter)
+enum pazpar2_error_code search(struct session *se,
+                               char *query, char *filter,
+                               const char **addinfo)
 {
     int live_channels = 0;
+    int no_working = 0;
+    int no_failed = 0;
     struct client *cl;
     struct database_criterion *criteria;
 
     yaz_log(YLOG_DEBUG, "Search");
 
+    *addinfo = 0;
     nmem_reset(se->nmem);
     criteria = parse_filter(se->nmem, filter);
     se->requestid++;
@@ -550,25 +546,34 @@ char *search(struct session *se, char *query, char *filter)
         se->expected_maxrecs = maxrecs;
     }
     else
-        return "NOTARGETS";
+        return PAZPAR2_NO_TARGETS;
 
     se->relevance = 0;
 
     for (cl = se->clients; cl; cl = client_next_in_session(cl))
     {
         if (prepare_session_database(se, client_get_database(cl)) < 0)
-            return "CONFIG_ERROR";
-        // Query must parse for all targets
-        if (client_parse_query(cl, query) < 0)  
-            return "QUERY";
+        {
+            *addinfo = client_get_database(cl)->database->url;
+            return PAZPAR2_CONFIG_TARGET;
+        }
+        // Parse query for target
+        if (client_parse_query(cl, query) < 0)
+            no_failed++;
+        else
+        {
+            no_working++;
+            client_prep_connection(cl);
+        }
     }
 
-    for (cl = se->clients; cl; cl = client_next_in_session(cl))
+    // If no queries could be mapped, we signal an error
+    if (no_working == 0)
     {
-        client_prep_connection(cl);
+        *addinfo = "query";
+        return PAZPAR2_MALFORMED_PARAMETER_VALUE;
     }
-
-    return 0;
+    return PAZPAR2_NO_ERROR;
 }
 
 // Creates a new session_database object for a database
@@ -581,6 +586,16 @@ static void session_init_databases_fun(void *context, struct database *db)
 
     new->database = db;
     new->yaz_marc = 0;
+    
+#ifdef HAVE_ICU
+    if (global_parameters.server && global_parameters.server->icu_chn)
+        new->pct = pp2_charset_create(global_parameters.server->icu_chn);
+    else
+        new->pct = pp2_charset_create(0);
+#else // HAVE_ICU
+    new->pct = pp2_charset_create(0);
+#endif // HAVE_ICU
+
     new->map = 0;
     new->settings 
         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
@@ -604,6 +619,8 @@ static void session_database_destroy(struct session_database *sdb)
         xsltFreeStylesheet(m->stylesheet);
     if (sdb->yaz_marc)
         yaz_marc_destroy(sdb->yaz_marc);
+    if (sdb->pct)
+        pp2_charset_destroy(sdb->pct);
 }
 
 // Initialize session_database list -- this represents this session's view
@@ -611,7 +628,7 @@ static void session_database_destroy(struct session_database *sdb)
 void session_init_databases(struct session *se)
 {
     se->databases = 0;
-    grep_databases(se, 0, session_init_databases_fun);
+    predef_grep_databases(se, 0, session_init_databases_fun);
 }
 
 // Probably session_init_databases_fun should be refactored instead of
@@ -644,13 +661,19 @@ void session_apply_setting(struct session *se, char *dbname, char *setting,
 {
     struct session_database *sdb = find_session_database(se, dbname);
     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
-    int offset = settings_offset(setting);
+    int offset = settings_offset_cprefix(setting);
 
     if (offset < 0)
     {
         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
         return;
     }
+    // Jakub: This breaks the filter setting.
+    /*if (offset == PZ_ID)
+    {
+        yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
+        return;
+    }*/
     new->precedence = 0;
     new->target = dbname;
     new->name = setting;
@@ -686,7 +709,6 @@ void destroy_session(struct session *s)
 {
     struct session_database *sdb;
 
-    yaz_log(YLOG_LOG, "Destroying session");
     while (s->clients)
         client_destroy(s->clients);
     for (sdb = s->databases; sdb; sdb = sdb->next)
@@ -702,6 +724,7 @@ struct session *new_session(NMEM nmem)
 
     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
     
+    session->relevance = 0;
     session->total_hits = 0;
     session->total_records = 0;
     session->num_termlists = 0;
@@ -712,7 +735,7 @@ struct session *new_session(NMEM nmem)
     session->session_nmem = nmem;
     session->nmem = nmem_create();
     session->wrbuf = wrbuf_alloc();
-    session_init_databases(session);
+    session->databases = 0;
     for (i = 0; i <= SESSION_WATCH_MAX; i++)
     {
         session->watchlist[i].data = 0;
@@ -791,34 +814,44 @@ struct record_cluster **show(struct session *s, struct reclist_sortparms *sp,
     yaz_timing_t t = yaz_timing_create();
 #endif
 
-    for (spp = sp; spp; spp = spp->next)
-        if (spp->type == Metadata_sortkey_relevance)
-        {
-            relevance_prepare_read(s->relevance, s->reclist);
-            break;
-        }
-    reclist_sort(s->reclist, sp);
-
-    *total = s->reclist->num_records;
-    *sumhits = s->total_hits;
-
-    for (i = 0; i < start; i++)
-        if (!reclist_read_record(s->reclist))
-        {
-            *num = 0;
-            recs = 0;
-            break;
-        }
-
-    for (i = 0; i < *num; i++)
+    if (!s->relevance)
     {
-        struct record_cluster *r = reclist_read_record(s->reclist);
-        if (!r)
+        *num = 0;
+        *total = 0;
+        *sumhits = 0;
+        recs = 0;
+    }
+    else
+    {
+        for (spp = sp; spp; spp = spp->next)
+            if (spp->type == Metadata_sortkey_relevance)
+            {
+                relevance_prepare_read(s->relevance, s->reclist);
+                break;
+            }
+        reclist_sort(s->reclist, sp);
+        
+        *total = s->reclist->num_records;
+        *sumhits = s->total_hits;
+        
+        for (i = 0; i < start; i++)
+            if (!reclist_read_record(s->reclist))
+            {
+                *num = 0;
+                recs = 0;
+                break;
+            }
+        
+        for (i = 0; i < *num; i++)
         {
-            *num = i;
-            break;
+            struct record_cluster *r = reclist_read_record(s->reclist);
+            if (!r)
+            {
+                *num = i;
+                break;
+            }
+            recs[i] = r;
         }
-        recs[i] = r;
     }
 #if USE_TIMING
     yaz_timing_stop(t);
@@ -902,38 +935,6 @@ void start_proxy(void)
     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
 }
 
-void start_zproxy(void)
-{
-    struct conf_server *ser = global_parameters.server;
-
-    if (*global_parameters.zproxy_override){
-        yaz_log(YLOG_LOG, "Z39.50 proxy  %s", 
-                global_parameters.zproxy_override);
-        return;
-    }
-
-    else if (ser->zproxy_host || ser->zproxy_port)
-    {
-        char hp[128] = "";
-
-        strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
-        if (ser->zproxy_port)
-        {
-            if (*hp)
-                strcat(hp, ":");
-            else
-                strcat(hp, "@:");
-
-            sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
-        }
-        strcpy(global_parameters.zproxy_override, hp);
-        yaz_log(YLOG_LOG, "Z39.50 proxy  %s", 
-                global_parameters.zproxy_override);
-
-    }
-    else
-        return;
-}
 
 // Master list of connections we're handling events to
 static IOCHAN channel_list = 0; 
@@ -948,12 +949,36 @@ void pazpar2_event_loop()
     event_loop(&channel_list);
 }
 
+static struct record_metadata *record_metadata_init(
+    NMEM nmem, char *value, enum conf_metadata_type type)
+{
+    struct record_metadata *rec_md = record_metadata_create(nmem);
+    if (type == Metadata_type_generic)
+    {
+        char * p = value;
+        p = normalize7bit_generic(p, " ,/.:([");
+        
+        rec_md->data.text = nmem_strdup(nmem, p);
+    }
+    else if (type == Metadata_type_year)
+    {
+        int first, last;
+        if (extract7bit_years((char *) value, &first, &last) < 0)
+            return 0;
+        rec_md->data.number.min = first;
+        rec_md->data.number.max = last;
+    }
+    else
+        return 0;
+    return rec_md;
+}
+
 struct record *ingest_record(struct client *cl, Z_External *rec,
                              int record_no)
 {
     xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
     xmlNode *root, *n;
-    struct record *res;
+    struct record *record;
     struct record_cluster *cluster;
     struct session *se = client_get_session(cl);
     xmlChar *mergekey, *mergekey_norm;
@@ -972,21 +997,17 @@ struct record *ingest_record(struct client *cl, Z_External *rec,
         return 0;
     }
 
-    res = nmem_malloc(se->nmem, sizeof(struct record));
-    res->next = 0;
-    res->client = cl;
-    res->metadata = nmem_malloc(se->nmem,
-            sizeof(struct record_metadata*) * service->num_metadata);
-    memset(res->metadata, 0, 
-           sizeof(struct record_metadata*) * service->num_metadata);
+    record = record_create(se->nmem, 
+                           service->num_metadata, service->num_sortkeys, cl,
+                           record_no);
 
     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
     xmlFree(mergekey);
-    normalize_mergekey((char *) mergekey_norm, 0);
+    normalize7bit_mergekey((char *) mergekey_norm, 0);
 
     cluster = reclist_insert(se->reclist, 
                              global_parameters.server->service, 
-                             res, (char *) mergekey_norm, 
+                             record, (char *) mergekey_norm, 
                              &se->total_merged);
     if (global_parameters.dump_records)
         yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
@@ -999,6 +1020,8 @@ struct record *ingest_record(struct client *cl, Z_External *rec,
     }
     relevance_newrec(se->relevance, cluster);
 
+
+    // now parsing XML record and adding data to cluster or record metadata
     for (n = root->children; n; n = n->next)
     {
         if (type)
@@ -1013,164 +1036,144 @@ struct record *ingest_record(struct client *cl, Z_External *rec,
         {
             struct conf_metadata *ser_md = 0;
             struct conf_sortkey *ser_sk = 0;
-            struct record_metadata **wheretoput, *newm;
+            struct record_metadata **wheretoput = 0;
+            struct record_metadata *rec_md = 0;
             int md_field_id = -1;
             int sk_field_id = -1;
-            int first, last;
 
             type = xmlGetProp(n, (xmlChar *) "type");
-            value = xmlNodeListGetString(xdoc, n->children, 0);
+            value = xmlNodeListGetString(xdoc, n->children, 1);
 
             if (!type || !value)
                 continue;
 
-            // First, find out what field we're looking at
-            for (md_field_id = 0; md_field_id < service->num_metadata;
-                 md_field_id++)
-                if (!strcmp((const char *) type,
-                            service->metadata[md_field_id].name))
-                {
-                    ser_md = &service->metadata[md_field_id];
-                    if (ser_md->sortkey_offset >= 0)
-                        ser_sk = &service->sortkeys[ser_md->sortkey_offset];
-                    break;
-                }
-            if (!ser_md)
+            md_field_id 
+                = conf_service_metadata_field_id(service, (const char *) type);
+            if (md_field_id < 0)
             {
                 yaz_log(YLOG_WARN, 
                         "Ignoring unknown metadata element: %s", type);
                 continue;
             }
 
-            // Find out where we are putting it
-            if (ser_md->merge == Metadata_merge_no)
-                wheretoput = &res->metadata[md_field_id];
-            else
-                wheretoput = &cluster->metadata[md_field_id];
-            
-            // Put it there
-            newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
-            newm->next = 0;
-            if (ser_md->type == Metadata_type_generic)
-            {
-                char *p, *pe;
-                for (p = (char *) value; *p && isspace(*p); p++)
-                    ;
-                for (pe = p + strlen(p) - 1;
-                        pe > p && strchr(" ,/.:([", *pe); pe--)
-                    *pe = '\0';
-                newm->data.text = nmem_strdup(se->nmem, p);
+            ser_md = &service->metadata[md_field_id];
 
+            if (ser_md->sortkey_offset >= 0){
+                sk_field_id = ser_md->sortkey_offset;
+                ser_sk = &service->sortkeys[sk_field_id];
             }
-            else if (ser_md->type == Metadata_type_year)
-            {
-                if (extract_years((char *) value, &first, &last) < 0)
-                    continue;
-            }
-            else
-            {
-                yaz_log(YLOG_WARN, 
-                        "Unknown type in metadata element %s", type);
-                continue;
-            }
-            if (ser_md->type == Metadata_type_year 
-                && ser_md->merge != Metadata_merge_range)
+
+            // non-merged metadata
+            rec_md = record_metadata_init(se->nmem, (char *) value,
+                                          ser_md->type);
+            if (!rec_md)
             {
-                yaz_log(YLOG_WARN, "Only range merging supported for years");
+                yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
+                        value, type);
                 continue;
             }
+            rec_md->next = record->metadata[md_field_id];
+            record->metadata[md_field_id] = rec_md;
+
+            // merged metadata
+            rec_md = record_metadata_init(se->nmem, (char *) value,
+                                          ser_md->type);
+            wheretoput = &cluster->metadata[md_field_id];
+
+            // and polulate with data:
+            // assign cluster or record based on merge action
             if (ser_md->merge == Metadata_merge_unique)
             {
                 struct record_metadata *mnode;
                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
                     if (!strcmp((const char *) mnode->data.text, 
-                                newm->data.text))
+                                rec_md->data.text))
                         break;
                 if (!mnode)
                 {
-                    newm->next = *wheretoput;
-                    *wheretoput = newm;
+                    rec_md->next = *wheretoput;
+                    *wheretoput = rec_md;
                 }
             }
             else if (ser_md->merge == Metadata_merge_longest)
             {
                 if (!*wheretoput 
-                    || strlen(newm->data.text) 
+                    || strlen(rec_md->data.text) 
                        > strlen((*wheretoput)->data.text))
                 {
-                    *wheretoput = newm;
+                    *wheretoput = rec_md;
                     if (ser_sk)
                     {
-                        char *s = nmem_strdup(se->nmem, newm->data.text);
-                        if (!cluster->sortkeys[ser_md->sortkey_offset])
-                            cluster->sortkeys[ser_md->sortkey_offset] = 
+                        char *s = nmem_strdup(se->nmem, rec_md->data.text);
+                        if (!cluster->sortkeys[sk_field_id])
+                            cluster->sortkeys[sk_field_id] = 
                                 nmem_malloc(se->nmem, 
                                             sizeof(union data_types));
-                        normalize_mergekey(s,
+                        normalize7bit_mergekey(s,
                              (ser_sk->type == Metadata_sortkey_skiparticle));
-                        cluster->sortkeys[ser_md->sortkey_offset]->text = s;
+                        cluster->sortkeys[sk_field_id]->text = s;
                     }
                 }
             }
-            else if (ser_md->merge == Metadata_merge_all 
-                     || ser_md->merge == Metadata_merge_no)
+            else if (ser_md->merge == Metadata_merge_all)
             {
-                newm->next = *wheretoput;
-                *wheretoput = newm;
+                rec_md->next = *wheretoput;
+                *wheretoput = rec_md;
             }
             else if (ser_md->merge == Metadata_merge_range)
             {
-                assert(ser_md->type == Metadata_type_year);
                 if (!*wheretoput)
                 {
-                    *wheretoput = newm;
-                    (*wheretoput)->data.number.min = first;
-                    (*wheretoput)->data.number.max = last;
+                    *wheretoput = rec_md;
                     if (ser_sk)
-                        cluster->sortkeys[ser_md->sortkey_offset] 
-                            = &newm->data;
+                        cluster->sortkeys[sk_field_id] 
+                            = &rec_md->data;
                 }
                 else
                 {
-                    if (first < (*wheretoput)->data.number.min)
-                        (*wheretoput)->data.number.min = first;
-                    if (last > (*wheretoput)->data.number.max)
-                        (*wheretoput)->data.number.max = last;
+                    int this_min = rec_md->data.number.min;
+                    int this_max = rec_md->data.number.max;
+                    if (this_min < (*wheretoput)->data.number.min)
+                        (*wheretoput)->data.number.min = this_min;
+                    if (this_max > (*wheretoput)->data.number.max)
+                        (*wheretoput)->data.number.max = this_max;
                 }
 #ifdef GAGA
-                if (sk)
+                if (ser_sk)
                 {
                     union data_types *sdata 
-                        = cluster->sortkeys[md->sortkey_offset];
+                        = cluster->sortkeys[sk_field_id];
                     yaz_log(YLOG_LOG, "SK range: %d-%d",
                             sdata->number.min, sdata->number.max);
                 }
 #endif
             }
-            else
-                yaz_log(YLOG_WARN,
-                        "Don't know how to merge on element name %s",
-                        ser_md->name);
 
+
+            // ranking of _all_ fields enabled ... 
             if (ser_md->rank)
                 relevance_countwords(se->relevance, cluster, 
                                      (char *) value, ser_md->rank);
+
+            // construct facets ... 
             if (ser_md->termlist)
             {
                 if (ser_md->type == Metadata_type_year)
                 {
                     char year[64];
-                    sprintf(year, "%d", last);
+                    sprintf(year, "%d", rec_md->data.number.max);
                     add_facet(se, (char *) type, year);
-                    if (first != last)
+                    if (rec_md->data.number.max != rec_md->data.number.min)
                     {
-                        sprintf(year, "%d", first);
+                        sprintf(year, "%d", rec_md->data.number.min);
                         add_facet(se, (char *) type, year);
                     }
                 }
                 else
                     add_facet(se, (char *) type, (char *) value);
             }
+
+            // cleaning up
             xmlFree(type);
             xmlFree(value);
             type = value = 0;
@@ -1189,7 +1192,7 @@ struct record *ingest_record(struct client *cl, Z_External *rec,
     relevance_donerecord(se->relevance, cluster);
     se->total_records++;
 
-    return res;
+    return record;
 }