str: Add function xstrdup_if_nonnull() and introduce many users.
[pspp] / src / language / stats / autorecode.c
index 14332acabee5029c94b28725cb3cd4c949268263..3b51928fc64e4633008d0cc24b5e484d3312d618 100644 (file)
@@ -36,6 +36,7 @@
 #include "libpspp/message.h"
 #include "libpspp/pool.h"
 #include "libpspp/str.h"
+#include "output/pivot-table.h"
 
 #include "gl/xalloc.h"
 #include "gl/c-xvasprintf.h"
@@ -44,8 +45,7 @@
 
 #include "gettext.h"
 #define _(msgid) gettext (msgid)
-
-/* FIXME: Implement PRINT subcommand. */
+#define N_(msgid) (msgid)
 
 /* Explains how to recode one value. */
 struct arc_item
@@ -54,6 +54,7 @@ struct arc_item
     union value from;           /* Original value. */
     int width;                  /* Width of the original value */
     bool missing;               /* Is 'from' missing in its source varible? */
+    char *value_label;          /* Value label in source variable, if any. */
 
     double to;                  /* Recoded value. */
   };
@@ -63,8 +64,11 @@ struct arc_spec
   {
     int width;                  /* Variable width. */
     int src_idx;                /* Case index of source variable. */
+    char *src_name;             /* Name of source variable. */
+    struct fmt_spec format;     /* Print format in source variable. */
     struct variable *dst;       /* Target variable. */
     struct missing_values mv;   /* Missing values of source variable. */
+    char *label;                /* Variable label of source variable. */
     struct rec_items *items;
   };
 
@@ -124,6 +128,7 @@ cmd_autorecode (struct lexer *lexer, struct dataset *ds)
   size_t n_dsts = 0;
 
   enum arc_direction direction = ASCENDING;
+  bool print = false;
 
   /* Create procedure. */
   struct autorecode_pgm *arc = xzalloc (sizeof *arc);
@@ -169,9 +174,7 @@ cmd_autorecode (struct lexer *lexer, struct dataset *ds)
       if (lex_match_id (lexer, "DESCENDING"))
         direction = DESCENDING;
       else if (lex_match_id (lexer, "PRINT"))
-        {
-          /* Not yet implemented. */
-        }
+        print = true;
       else if (lex_match_id (lexer, "GROUP"))
         group = true;
       else if (lex_match_id (lexer, "BLANK"))
@@ -238,6 +241,11 @@ cmd_autorecode (struct lexer *lexer, struct dataset *ds)
 
       spec->width = var_get_width (src_vars[i]);
       spec->src_idx = var_get_case_index (src_vars[i]);
+      spec->src_name = xstrdup (var_get_name (src_vars[i]));
+      spec->format = *var_get_print_format (src_vars[i]);
+
+      const char *label = var_get_label (src_vars[i]);
+      spec->label = xstrdup_if_nonnull (label);
 
       if (group && i > 0)
         spec->items = arc->specs[0].items;
@@ -296,12 +304,19 @@ cmd_autorecode (struct lexer *lexer, struct dataset *ds)
         if (find_arc_item (spec->items, value, width, hash))
           continue;
 
+        struct string value_label = DS_EMPTY_INITIALIZER;
+        var_append_value_name__ (src_vars[i], value,
+                                 SETTINGS_VALUE_SHOW_LABEL, &value_label);
+
         struct arc_item *item = xmalloc (sizeof *item);
         item->width = width;
         value_clone (&item->from, value, width);
         item->missing = mv_is_value_missing_varwidth (&spec->mv, value, spec->width,
                                                       MV_ANY);
+        item->value_label = ds_steal_cstr (&value_label);
         hmap_insert (&spec->items->ht, &item->hmap_node, hash);
+
+        ds_destroy (&value_label);
       }
   bool ok = casereader_destroy (input);
   ok = proc_commit (ds) && ok;
@@ -314,21 +329,24 @@ cmd_autorecode (struct lexer *lexer, struct dataset *ds)
   for (size_t i = 0; i < arc->n_specs; i++)
     {
       struct arc_spec *spec = &arc->specs[i];
-      struct arc_item **items;
-      struct arc_item *item;
-      size_t n_items;
-      size_t j;
 
       /* Create destination variable. */
       spec->dst = dict_create_var_assert (dict, dst_names[i], 0);
+      var_set_label (spec->dst, spec->label);
+
+      /* Set print format. */
+      size_t n_items = hmap_count (&spec->items->ht);
+      char *longest_value = xasprintf ("%zu", n_items);
+      struct fmt_spec format = { .type = FMT_F, .w = strlen (longest_value) };
+      var_set_both_formats (spec->dst, &format);
+      free (longest_value);
 
       /* Create array of pointers to items. */
-      n_items = hmap_count (&spec->items->ht);
-      items = xmalloc (n_items * sizeof *items);
-      j = 0;
+      struct arc_item **items = xmalloc (n_items * sizeof *items);
+      struct arc_item *item;
+      size_t j = 0;
       HMAP_FOR_EACH (item, struct arc_item, hmap_node, &spec->items->ht)
         items[j++] = item;
-
       assert (j == n_items);
 
       /* Sort array by value. */
@@ -338,6 +356,51 @@ cmd_autorecode (struct lexer *lexer, struct dataset *ds)
       for (j = 0; j < n_items; j++)
         items[j]->to = j + 1;
 
+      if (print && (!group || i == 0))
+        {
+          struct pivot_value *title
+            = (group
+               ? pivot_value_new_text (N_("Recoding grouped variables."))
+               : spec->label && spec->label[0]
+               ? pivot_value_new_text_format (N_("Recoding %s into %s (%s)."),
+                                              spec->src_name,
+                                              var_get_name (spec->dst),
+                                              spec->label)
+               : pivot_value_new_text_format (N_("Recoding %s into %s."),
+                                              spec->src_name,
+                                              var_get_name (spec->dst)));
+          struct pivot_table *table = pivot_table_create__ (title, "Recoding");
+
+          pivot_dimension_create (
+            table, PIVOT_AXIS_COLUMN, N_("Attributes"),
+            N_("New Value"), N_("Value Label"));
+
+          struct pivot_dimension *old_values = pivot_dimension_create (
+            table, PIVOT_AXIS_ROW, N_("Old Value"));
+          old_values->root->show_label = true;
+
+          for (size_t k = 0; k < n_items; k++)
+            {
+              const struct arc_item *item = items[k];
+              int old_value_idx = pivot_category_create_leaf (
+                old_values->root, pivot_value_new_value (
+                  &item->from, item->width,
+                  (item->width
+                   ? &(struct fmt_spec) { FMT_F, item->width, 0 }
+                   : &spec->format),
+                  dict_get_encoding (dict)));
+              pivot_table_put2 (table, 0, old_value_idx,
+                                pivot_value_new_integer (item->to));
+
+              const char *value_label = item->value_label;
+              if (value_label && value_label[0])
+                pivot_table_put2 (table, 1, old_value_idx,
+                                  pivot_value_new_user_text (value_label, -1));
+            }
+
+          pivot_table_submit (table);
+        }
+
       /* Assign user-missing values.
 
          User-missing values in the source variable(s) must be marked
@@ -372,35 +435,15 @@ cmd_autorecode (struct lexer *lexer, struct dataset *ds)
           mv_destroy (&mv);
         }
 
-      /* Add value labels to the destination variable which indicate
-         the source value from whence the new value comes. */
+      /* Add value labels to the destination variable. */
       for (j = 0; j < n_items; j++)
         {
-          const union value *from = &items[j]->from;
-          const int src_width = items[j]->width;
-          char *recoded_value;
-          if (src_width > 0)
-            {
-              const char *str = CHAR_CAST_BUG (const char *, from->s);
-
-              recoded_value = recode_string (UTF8, dict_get_encoding (dict),
-                                             str, src_width);
-            }
-          else
-            recoded_value = c_xasprintf ("%.*g", DBL_DIG + 1, from->f);
-
-          /* Remove trailing whitespace. */
-          size_t len = strlen (recoded_value);
-          while (len > 0 && recoded_value[len - 1] == ' ')
-            recoded_value[--len] = '\0';
-
-          /* Add value label, if it would be nonempty. */
-          if (len)
+          const char *value_label = items[j]->value_label;
+          if (value_label && value_label[0])
             {
               union value to_val = { .f = items[j]->to };
-              var_add_value_label (spec->dst, &to_val, recoded_value);
+              var_add_value_label (spec->dst, &to_val, value_label);
             }
-          free (recoded_value);
         }
 
       /* Free array. */
@@ -438,16 +481,20 @@ arc_free (struct autorecode_pgm *arc)
                               &spec->items->ht)
             {
               value_destroy (&item->from, item->width);
+              free (item->value_label);
               hmap_delete (&spec->items->ht, &item->hmap_node);
               free (item);
             }
+          free (spec->label);
+          free (spec->src_name);
           mv_destroy (&spec->mv);
         }
 
       size_t n_rec_items =
-        (arc->n_specs == 1 || arc->specs[0].items == arc->specs[1].items
+        (arc->n_specs >= 2 && arc->specs[0].items == arc->specs[1].items
          ? 1
          : arc->n_specs);
+
       for (size_t i = 0; i < n_rec_items; i++)
         {
           struct arc_spec *spec = &arc->specs[i];