/*
 *  call-seq:
 *     top_doc.to_s(field = :id) -> string
 *
 *  Returns a string representation of the top_doc in readable format.
 */
static VALUE
frt_td_to_s(int argc, VALUE *argv, VALUE self)
{
    int i;
    VALUE rhits = rb_funcall(self, id_hits, 0);
    Searcher *sea = (Searcher *)DATA_PTR(rb_funcall(self, id_searcher, 0));
    const int len = RARRAY(rhits)->len;
    char *str = ALLOC_N(char, len * 64 + 100);
    char *s = str;
    char *field = "id";
    VALUE rstr;

    if (argc) {
        field = frt_field(argv[0]);
    }

    sprintf(s, "TopDocs: total_hits = %ld, max_score = %f [\n",
            FIX2INT(rb_funcall(self, id_total_hits, 0)),
            NUM2DBL(rb_funcall(self, id_max_score, 0)));
    s += strlen(s);

    for (i = 0; i < len; i++) {
        VALUE rhit = RARRAY(rhits)->ptr[i];
        int doc_id = FIX2INT(rb_funcall(rhit, id_doc, 0));
        char *value = "";
        LazyDoc *lzd = sea->get_lazy_doc(sea, doc_id);
        LazyDocField *lzdf = h_get(lzd->field_dict, field);
        if (NULL != lzdf) {
            value = lazy_df_get_data(lzdf, 0);
        }

        sprintf(s, "\t%d \"%s\": %f\n", doc_id, value,
                NUM2DBL(rb_funcall(rhit, id_score, 0)));
        s += strlen(s);
        lazy_doc_close(lzd);
    }

    sprintf(s, "]\n");
    rstr = rb_str_new2(str);
    free(str);
    return rstr;
}