Adopt use of gnulib for portability.
[pspp-builds.git] / src / frequencies.q
index a9c5850d7ba29f6f3031b0dea7146629443e97a3..c165c21d6926bf2dbe6468f8ce55ec69c23ba4b7 100644 (file)
@@ -14,8 +14,8 @@
 
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
-   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-   02111-1307, USA. */
+   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+   02110-1301, USA. */
 
 /*
   TODO:
 */
 
 #include <config.h>
-#include <assert.h>
+#include "error.h"
 #include <math.h>
 #include <stdlib.h>
+#include <gsl/gsl_histogram.h>
+
 #include "alloc.h"
 #include "bitvector.h"
+#include "case.h"
+#include "dictionary.h"
 #include "hash.h"
 #include "pool.h"
 #include "command.h"
 #include "lexer.h"
+#include "moments.h"
 #include "error.h"
 #include "algorithm.h"
 #include "magic.h"
 #include "misc.h"
-#include "stats.h"
 #include "output.h"
 #include "som.h"
 #include "str.h"
 #include "value-labels.h"
 #include "var.h"
 #include "vfm.h"
+#include "settings.h"
+#include "chart.h"
+
+#include "gettext.h"
+#define _(msgid) gettext (msgid)
+#define N_(msgid) msgid
+
+/* (headers) */
 
 #include "debug-print.h"
 
@@ -61,6 +73,9 @@
      barchart(ba_)=:minimum(d:min),
            :maximum(d:max),
            scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
+     piechart(pie_)=:minimum(d:min),
+           :maximum(d:max),
+           missing:missing/!nomissing;
      histogram(hi_)=:minimum(d:min),
            :maximum(d:max),
            scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
@@ -72,8 +87,8 @@
            norm:!nonormal/normal,
            incr:increment(d:inc,"%s>0");
      grouped=custom;
-     ntiles=custom;
-     percentiles=custom;
+     ntiles=integer;
+     +percentiles = double list;
      statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
            7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
            13|default,14|seskewness,15|sekurtosis,all,none.
 /* (declarations) */
 /* (functions) */
 
+/* Statistics. */
+enum
+  {
+    frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
+    frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
+    frq_sum, frq_n_stats
+  };
+
 /* Description of a statistic. */
 struct frq_info
   {
@@ -109,10 +132,25 @@ static struct frq_info st_name[frq_n_stats + 1] =
 };
 
 /* Percentiles to calculate. */
-static double *percentiles;
-static double *percentile_values;
+
+struct percentile
+{
+  double p;        /* the %ile to be calculated */
+  double value;    /* the %ile's value */
+  double x1;       /* The datum value <= the percentile */
+  double x2;       /* The datum value >= the percentile */
+  int flag;        
+  int flag2;       /* Set to 1 if this percentile value has been found */
+};
+
+
+static void add_percentile (double x) ;
+
+static struct percentile *percentiles;
 static int n_percentiles;
 
+static int implicit_50th ; 
+
 /* Groups of statistics. */
 #define BI          BIT_INDEX
 #define frq_default                                                    \
@@ -134,6 +172,7 @@ enum
     GFT_NONE,                  /* Don't draw graphs. */
     GFT_BAR,                   /* Draw bar charts. */
     GFT_HIST,                  /* Draw histograms. */
+    GFT_PIE,                    /* Draw piechart */
     GFT_HBAR                   /* Draw bar charts or histograms at our discretion. */
   };
 
@@ -141,7 +180,8 @@ enum
 static struct cmd_frequencies cmd;
 
 /* Summary of the barchart, histogram, and hbar subcommands. */
-static int chart;              /* NONE/BAR/HIST/HBAR. */
+/* FIXME: These should not be mututally exclusive */
+static int chart;              /* NONE/BAR/HIST/HBAR/PIE. */
 static double min, max;                /* Minimum, maximum on y axis. */
 static int format;             /* FREQ/PERCENT: Scaling of y axis. */
 static double scale, incr;     /* FIXME */
@@ -155,14 +195,78 @@ static struct variable **v_variables;
 static struct pool *int_pool;  /* Integer mode. */
 static struct pool *gen_pool;  /* General mode. */
 
-/* Easier access to a_statistics. */
-#define stat cmd.a_statistics
+/* Frequency tables. */
+
+/* Frequency table entry. */
+struct freq
+  {
+    union value v;             /* The value. */
+    double c;                  /* The number of occurrences of the value. */
+  };
+
+/* Types of frequency tables. */
+enum
+  {
+    FRQM_GENERAL,
+    FRQM_INTEGER
+  };
+
+/* Entire frequency table. */
+struct freq_tab
+  {
+    int mode;                  /* FRQM_GENERAL or FRQM_INTEGER. */
+
+    /* General mode. */
+    struct hsh_table *data;    /* Undifferentiated data. */
+
+    /* Integer mode. */
+    double *vector;            /* Frequencies proper. */
+    int min, max;              /* The boundaries of the table. */
+    double out_of_range;       /* Sum of weights of out-of-range values. */
+    double sysmis;             /* Sum of weights of SYSMIS values. */
+
+    /* All modes. */
+    struct freq *valid;         /* Valid freqs. */
+    int n_valid;               /* Number of total freqs. */
+
+    struct freq *missing;      /* Missing freqs. */
+    int n_missing;             /* Number of missing freqs. */
+
+    /* Statistics. */
+    double total_cases;                /* Sum of weights of all cases. */
+    double valid_cases;                /* Sum of weights of valid cases. */
+  };
+
+
+/* Per-variable frequency data. */
+struct var_freqs
+  {
+    /* Freqency table. */
+    struct freq_tab tab;       /* Frequencies table to use. */
+
+    /* Percentiles. */
+    int n_groups;              /* Number of groups. */
+    double *groups;            /* Groups. */
+
+    /* Statistics. */
+    double stat[frq_n_stats];
+  };
+
+static inline struct var_freqs *
+get_var_freqs (struct variable *v)
+{
+  assert (v != NULL);
+  assert (v->aux != NULL);
+  return v->aux;
+}
 
 static void determine_charts (void);
 
-static void precalc (void);
-static int calc (struct ccase *);
-static void postcalc (void);
+static void calc_stats (struct variable *v, double d[frq_n_stats]);
+
+static void precalc (void *);
+static int calc (struct ccase *, void *);
+static void postcalc (void *);
 
 static void postprocess_freq_tab (struct variable *);
 static void dump_full (struct variable *);
@@ -175,6 +279,15 @@ static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
+
+
+static void do_piechart(const struct variable *var,
+                       const struct freq_tab *frq_tab);
+
+gsl_histogram * 
+freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
+
+
 \f
 /* Parser and outline. */
 
@@ -202,16 +315,11 @@ internal_cmd_frequencies (void)
   int i;
 
   n_percentiles = 0;
-  percentile_values = NULL;
   percentiles = NULL;
 
   n_variables = 0;
   v_variables = NULL;
 
-  for (i = 0; i < dict_get_var_cnt (default_dict); i++)
-    dict_get_var(default_dict, i)->p.frq.used = 0;
-
-  lex_match_id ("FREQUENCIES");
   if (!parse_frequencies (&cmd))
     return CMD_FAILURE;
 
@@ -220,14 +328,14 @@ internal_cmd_frequencies (void)
 
   /* Figure out statistics to calculate. */
   stats = 0;
-  if (stat[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
+  if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
     stats |= frq_default;
-  if (stat[FRQ_ST_ALL])
+  if (cmd.a_statistics[FRQ_ST_ALL])
     stats |= frq_all;
   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
     stats &= ~frq_median;
   for (i = 0; i < frq_n_stats; i++)
-    if (stat[st_name[i].st_indx])
+    if (cmd.a_statistics[st_name[i].st_indx])
       stats |= BIT_INDEX (i);
   if (stats & frq_kurt)
     stats |= frq_sekurt;
@@ -245,8 +353,32 @@ internal_cmd_frequencies (void)
   if (chart != GFT_NONE || cmd.sbc_ntiles)
     cmd.sort = FRQ_AVALUE;
 
+  /* Work out what percentiles need to be calculated */
+  if ( cmd.sbc_percentiles ) 
+    {
+      for ( i = 0 ; i < MAXLISTS ; ++i ) 
+       {
+         int pl;
+         subc_list_double *ptl_list = &cmd.dl_percentiles[i];
+         for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
+             add_percentile(subc_list_double_at(ptl_list,pl) / 100.0 );
+       }
+    }
+  if ( cmd.sbc_ntiles ) 
+    {
+      for ( i = 0 ; i < cmd.sbc_ntiles ; ++i ) 
+       {
+         int j;
+         for (j = 0; j <= cmd.n_ntiles[i]; ++j ) 
+             add_percentile(j / (double) cmd.n_ntiles[i]);
+       }
+    }
+  
+
   /* Do it! */
-  procedure (precalc, calc, postcalc);
+  procedure_with_splits (precalc, calc, postcalc, NULL);
+
+  free_frequencies(&cmd);
 
   return CMD_SUCCESS;
 }
@@ -255,7 +387,8 @@ internal_cmd_frequencies (void)
 static void
 determine_charts (void)
 {
-  int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) + (!!cmd.sbc_hbar);
+  int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) + 
+    (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
 
   if (!count)
     {
@@ -273,6 +406,8 @@ determine_charts (void)
     chart = GFT_HIST;
   else if (cmd.sbc_barchart)
     chart = GFT_BAR;
+  else if (cmd.sbc_piechart)
+    chart = GFT_PIE;
   else
     chart = GFT_HBAR;
 
@@ -316,7 +451,7 @@ determine_charts (void)
          format = FRQ_PERCENT;
          scale = cmd.ba_pcnt;
        }
-      if (cmd.hi_norm)
+      if (cmd.hi_norm != FRQ_NONORMAL )
        normal = 1;
       if (cmd.hi_incr == FRQ_INCREMENT)
        incr = cmd.hi_inc;
@@ -355,26 +490,28 @@ determine_charts (void)
 
 /* Add data from case C to the frequency table. */
 static int
-calc (struct ccase *c)
+calc (struct ccase *c, void *aux UNUSED)
 {
   double weight;
   int i;
+  int bad_warn = 1;
 
-  weight = dict_get_case_weight (default_dict, c);
+  weight = dict_get_case_weight (default_dict, c, &bad_warn);
 
   for (i = 0; i < n_variables; i++)
     {
       struct variable *v = v_variables[i];
-      union value *val = &c->data[v->fv];
-      struct freq_tab *ft = &v->p.frq.tab;
+      const union value *val = case_data (c, v->fv);
+      struct freq_tab *ft = &get_var_freqs (v)->tab;
 
-      switch (v->p.frq.tab.mode)
+      switch (ft->mode)
        {
          case FRQM_GENERAL:
            {
+
              /* General mode. */
              struct freq **fpp = (struct freq **) hsh_probe (ft->data, val);
-         
+
              if (*fpp != NULL)
                (*fpp)->c += weight;
              else
@@ -388,15 +525,15 @@ calc (struct ccase *c)
        case FRQM_INTEGER:
          /* Integer mode. */
          if (val->f == SYSMIS)
-           v->p.frq.tab.sysmis += weight;
+           ft->sysmis += weight;
          else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
            {
              int i = val->f;
-             if (i >= v->p.frq.tab.min && i <= v->p.frq.tab.max)
-               v->p.frq.tab.vector[i - v->p.frq.tab.min] += weight;
+             if (i >= ft->min && i <= ft->max)
+               ft->vector[i - ft->min] += weight;
            }
          else
-           v->p.frq.tab.out_of_range += weight;
+           ft->out_of_range += weight;
          break;
        default:
          assert (0);
@@ -408,7 +545,7 @@ calc (struct ccase *c)
 /* Prepares each variable that is the target of FREQUENCIES by setting
    up its hash table. */
 static void
-precalc (void)
+precalc (void *aux UNUSED)
 {
   int i;
 
@@ -418,8 +555,9 @@ precalc (void)
   for (i = 0; i < n_variables; i++)
     {
       struct variable *v = v_variables[i];
+      struct freq_tab *ft = &get_var_freqs (v)->tab;
 
-      if (v->p.frq.tab.mode == FRQM_GENERAL)
+      if (ft->mode == FRQM_GENERAL)
        {
           hsh_hash_func *hash;
          hsh_compare_func *compare;
@@ -434,16 +572,16 @@ precalc (void)
               hash = hash_value_alpha;
               compare = compare_value_alpha_a;
             }
-         v->p.frq.tab.data = hsh_create (16, compare, hash, NULL, v);
+         ft->data = hsh_create (16, compare, hash, NULL, v);
        }
       else
        {
          int j;
 
-         for (j = (v->p.frq.tab.max - v->p.frq.tab.min); j >= 0; j--)
-           v->p.frq.tab.vector[j] = 0.0;
-         v->p.frq.tab.out_of_range = 0.0;
-         v->p.frq.tab.sysmis = 0.0;
+         for (j = (ft->max - ft->min); j >= 0; j--)
+           ft->vector[j] = 0.0;
+         ft->out_of_range = 0.0;
+         ft->sysmis = 0.0;
        }
     }
 }
@@ -451,20 +589,22 @@ precalc (void)
 /* Finishes up with the variables after frequencies have been
    calculated.  Displays statistics, percentiles, ... */
 static void
-postcalc (void)
+postcalc (void *aux UNUSED)
 {
   int i;
 
   for (i = 0; i < n_variables; i++)
     {
       struct variable *v = v_variables[i];
+      struct var_freqs *vf = get_var_freqs (v);
+      struct freq_tab *ft = &vf->tab;
       int n_categories;
       int dumped_freq_tab = 1;
 
       postprocess_freq_tab (v);
 
       /* Frequencies tables. */
-      n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
+      n_categories = ft->n_valid + ft->n_missing;
       if (cmd.table == FRQ_TABLE
          || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
        switch (cmd.cond)
@@ -491,7 +631,38 @@ postcalc (void)
       if (n_stats)
        dump_statistics (v, !dumped_freq_tab);
 
+
+
+      if ( chart == GFT_HIST) 
+       {
+         double d[frq_n_stats];
+         struct normal_curve norm;
+         gsl_histogram *hist ;
+
+
+         norm.N = vf->tab.valid_cases;
+
+         calc_stats(v,d);
+         norm.mean = d[frq_mean];
+         norm.stddev = d[frq_stddev];
+
+         hist = freq_tab_to_hist(ft,v);
+
+         histogram_plot(hist, var_to_string(v), &norm, normal);
+
+         gsl_histogram_free(hist);
+       }
+
+
+      if ( chart == GFT_PIE) 
+       {
+         do_piechart(v_variables[i], ft);
+       }
+
+
+
       cleanup_freq_tab (v);
+
     }
 }
 
@@ -518,6 +689,8 @@ get_freq_comparator (int frq_sort, int var_type)
   return 0;
 }
 
+/* Returns nonzero iff the value in struct freq F is non-missing
+   for variable V. */
 static int
 not_missing (const void *f_, void *v_) 
 {
@@ -527,26 +700,27 @@ not_missing (const void *f_, void *v_)
   return !is_missing (&f->v, v);
 }
 
+/* Summarizes the frequency table data for variable V. */
 static void
-postprocess_freq_tab (struct variable * v)
+postprocess_freq_tab (struct variable *v)
 {
   hsh_compare_func *compare;
   struct freq_tab *ft;
   size_t count;
-  void **data;
+  void *const *data;
   struct freq *freqs, *f;
   size_t i;
 
-  assert (v->p.frq.tab.mode == FRQM_GENERAL);
+  ft = &get_var_freqs (v)->tab;
+  assert (ft->mode == FRQM_GENERAL);
   compare = get_freq_comparator (cmd.sort, v->type);
-  ft = &v->p.frq.tab;
 
   /* Extract data from hash table. */
   count = hsh_count (ft->data);
   data = hsh_data (ft->data);
 
   /* Copy dereferenced data into freqs. */
-  freqs = xmalloc (count* sizeof *freqs);
+  freqs = xmalloc (count * sizeof *freqs);
   for (i = 0; i < count; i++) 
     {
       struct freq *f = data[i];
@@ -564,31 +738,40 @@ postprocess_freq_tab (struct variable * v)
   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
 
   /* Summary statistics. */
-  ft->total_cases = ft->valid_cases = 0.0;
-  for (f = ft->valid; f < ft->valid + ft->n_valid; f++
+  ft->valid_cases = 0.0;
+  for(i = 0 ;  i < ft->n_valid ; ++i 
     {
-      ft->total_cases += f->c;
+      f = &ft->valid[i];
+      ft->valid_cases += f->c;
 
-      if ((v->type != NUMERIC || f->v.f != SYSMIS)
-          && (cmd.miss != FRQ_EXCLUDE || !is_user_missing (&f->v, v)))
-        ft->valid_cases += f->c;
     }
+
+  ft->total_cases = ft->valid_cases ; 
+  for(i = 0 ;  i < ft->n_missing ; ++i ) 
+    {
+      f = &ft->missing[i];
+      ft->total_cases += f->c;
+    }
+
 }
 
+/* Frees the frequency table for variable V. */
 static void
 cleanup_freq_tab (struct variable *v)
 {
-  assert (v->p.frq.tab.mode == FRQM_GENERAL);
-  free (v->p.frq.tab.valid);
+  struct freq_tab *ft = &get_var_freqs (v)->tab;
+  assert (ft->mode == FRQM_GENERAL);
+  free (ft->valid);
+  hsh_destroy (ft->data);
 }
 
 /* Parses the VARIABLES subcommand, adding to
    {n_variables,v_variables}. */
 static int
-frq_custom_variables (struct cmd_frequencies *cmd unused)
+frq_custom_variables (struct cmd_frequencies *cmd UNUSED)
 {
   int mode;
-  int min, max;
+  int min = 0, max = 0;
 
   int old_n_variables = n_variables;
   int i;
@@ -602,9 +785,6 @@ frq_custom_variables (struct cmd_frequencies *cmd unused)
                        PV_APPEND | PV_NO_SCRATCH))
     return 0;
 
-  for (i = old_n_variables; i < n_variables; i++)
-    v_variables[i]->p.frq.tab.mode = FRQM_GENERAL;
-
   if (!lex_match ('('))
     mode = FRQM_GENERAL;
   else
@@ -633,45 +813,43 @@ frq_custom_variables (struct cmd_frequencies *cmd unused)
   for (i = old_n_variables; i < n_variables; i++)
     {
       struct variable *v = v_variables[i];
+      struct var_freqs *vf;
 
-      if (v->p.frq.used != 0)
+      if (v->aux != NULL)
        {
          msg (SE, _("Variable %s specified multiple times on VARIABLES "
                     "subcommand."), v->name);
          return 0;
        }
-      
-      v->p.frq.used = 1;               /* Used simply as a marker. */
-
-      v->p.frq.tab.valid = v->p.frq.tab.missing = NULL;
+      if (mode == FRQM_INTEGER && v->type != NUMERIC)
+        {
+          msg (SE, _("Integer mode specified, but %s is not a numeric "
+                     "variable."), v->name);
+          return 0;
+        }
 
+      vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
+      vf->tab.mode = mode;
+      vf->tab.valid = vf->tab.missing = NULL;
       if (mode == FRQM_INTEGER)
        {
-         if (v->type != NUMERIC)
-           {
-             msg (SE, _("Integer mode specified, but %s is not a numeric "
-                        "variable."), v->name);
-             return 0;
-           }
-         
-         v->p.frq.tab.min = min;
-         v->p.frq.tab.max = max;
-         v->p.frq.tab.vector = pool_alloc (int_pool,
-                                           sizeof (struct freq) * (max - min + 1));
+         vf->tab.min = min;
+         vf->tab.max = max;
+         vf->tab.vector = pool_alloc (int_pool,
+                                       sizeof (struct freq) * (max - min + 1));
        }
       else
-       v->p.frq.tab.vector = NULL;
-
-      v->p.frq.n_groups = 0;
-      v->p.frq.groups = NULL;
+       vf->tab.vector = NULL;
+      vf->n_groups = 0;
+      vf->groups = NULL;
     }
   return 1;
 }
 
-/* Parses the GROUPED subcommand, setting the frq.{n_grouped,grouped}
+/* Parses the GROUPED subcommand, setting the n_grouped, grouped
    fields of specified variables. */
 static int
-frq_custom_grouped (struct cmd_frequencies *cmd unused)
+frq_custom_grouped (struct cmd_frequencies *cmd UNUSED)
 {
   lex_match ('=');
   if ((token == T_ID && dict_lookup_var (default_dict, tokid) != NULL)
@@ -695,7 +873,7 @@ frq_custom_grouped (struct cmd_frequencies *cmd unused)
          {
            nl = ml = 0;
            dl = NULL;
-           while (token == T_NUM)
+           while (lex_integer ())
              {
                if (nl >= ml)
                  {
@@ -715,23 +893,29 @@ frq_custom_grouped (struct cmd_frequencies *cmd unused)
                return 0;
              }
          }
-       else
-         nl = 0;
+       else 
+          {
+            nl = 0;
+            dl = NULL;
+          }
 
        for (i = 0; i < n; i++)
-         {
-           if (v[i]->p.frq.used == 0)
-             msg (SE, _("Variables %s specified on GROUPED but not on "
-                  "VARIABLES."), v[i]->name);
-           if (v[i]->p.frq.groups != NULL)
-             msg (SE, _("Variables %s specified multiple times on GROUPED "
-                  "subcommand."), v[i]->name);
-           else
-             {
-               v[i]->p.frq.n_groups = nl;
-               v[i]->p.frq.groups = dl;
-             }
-         }
+          if (v[i]->aux == NULL)
+            msg (SE, _("Variables %s specified on GROUPED but not on "
+                       "VARIABLES."), v[i]->name);
+          else 
+            {
+              struct var_freqs *vf = get_var_freqs (v[i]);
+                
+              if (vf->groups != NULL)
+                msg (SE, _("Variables %s specified multiple times on GROUPED "
+                           "subcommand."), v[i]->name);
+              else
+                {
+                  vf->n_groups = nl;
+                  vf->groups = dl;
+                }
+            }
        free (v);
        if (!lex_match ('/'))
          break;
@@ -754,78 +938,35 @@ add_percentile (double x)
   int i;
 
   for (i = 0; i < n_percentiles; i++)
-    if (x <= percentiles[i])
-      break;
-  if (i >= n_percentiles || tokval != percentiles[i])
+    {
+      /* Do nothing if it's already in the list */
+      if ( fabs(x - percentiles[i].p) < DBL_EPSILON ) 
+       return;
+
+      if (x < percentiles[i].p)
+       break;
+    }
+
+  if (i >= n_percentiles || tokval != percentiles[i].p)
     {
       percentiles
         = pool_realloc (int_pool, percentiles,
-                        (n_percentiles + 1) * sizeof *percentiles);
-      percentile_values
-        = pool_realloc (int_pool, percentile_values,
-                        (n_percentiles + 1) * sizeof *percentile_values);
-      if (i < n_percentiles) 
-        {
+                        (n_percentiles + 1) * sizeof (struct percentile ));
+
+      if (i < n_percentiles)
           memmove (&percentiles[i + 1], &percentiles[i],
-                   (n_percentiles - i) * sizeof *percentiles);
-          memmove (&percentile_values[i + 1], &percentile_values[i],
-                   (n_percentiles - i) * sizeof *percentile_values);
-        }
-      percentiles[i] = x;
-      n_percentiles++;
-    }
-}
+                   (n_percentiles - i) * sizeof (struct percentile) );
 
-/* Parses the PERCENTILES subcommand, adding user-specified
-   percentiles to the list. */
-static int
-frq_custom_percentiles (struct cmd_frequencies *cmd unused)
-{
-  lex_match ('=');
-  if (token != T_NUM)
-    {
-      msg (SE, _("Percentile list expected after PERCENTILES."));
-      return 0;
-    }
-  
-  do
-    {
-      if (tokval <= 0 || tokval >= 100)
-       {
-         msg (SE, _("Percentiles must be greater than "
-                    "0 and less than 100."));
-         return 0;
-       }
-      
-      add_percentile (tokval / 100.0);
-      lex_get ();
-      lex_match (',');
+      percentiles[i].p = x;
+      n_percentiles++;
     }
-  while (token == T_NUM);
-  return 1;
 }
 
-/* Parses the NTILES subcommand, adding the percentiles that
-   correspond to the specified evenly-distributed ntiles. */
-static int
-frq_custom_ntiles (struct cmd_frequencies *cmd unused)
-{
-  int i;
-
-  lex_match ('=');
-  if (!lex_force_int ())
-    return 0;
-  for (i = 1; i < lex_integer (); i++)
-    add_percentile (1.0 / lex_integer () * i);
-  lex_get ();
-  return 1;
-}
-\f
 /* Comparison functions. */
 
 /* Hash of numeric values. */
 static unsigned
-hash_value_numeric (const void *value_, void *foo unused)
+hash_value_numeric (const void *value_, void *foo UNUSED)
 {
   const struct freq *value = value_;
   return hsh_hash_double (value->v.f);
@@ -833,18 +974,17 @@ hash_value_numeric (const void *value_, void *foo unused)
 
 /* Hash of string values. */
 static unsigned
-hash_value_alpha (const void *value_, void *len_ unused)
+hash_value_alpha (const void *value_, void *v_)
 {
   const struct freq *value = value_;
+  struct variable *v = v_;
 
-  static int len = MAX_SHORT_STRING;
-
-  return hsh_hash_bytes (value->v.s, len);
+  return hsh_hash_bytes (value->v.s, v->width);
 }
 
 /* Ascending numeric compare of values. */
 static int
-compare_value_numeric_a (const void *a_, const void *b_, void *foo unused)
+compare_value_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
 {
   const struct freq *a = a_;
   const struct freq *b = b_;
@@ -870,7 +1010,7 @@ compare_value_alpha_a (const void *a_, const void *b_, void *v_)
 
 /* Descending numeric compare of values. */
 static int
-compare_value_numeric_d (const void *a, const void *b, void *foo unused)
+compare_value_numeric_d (const void *a, const void *b, void *foo UNUSED)
 {
   return -compare_value_numeric_a (a, b, foo);
 }
@@ -885,14 +1025,14 @@ compare_value_alpha_d (const void *a, const void *b, void *v)
 /* Ascending numeric compare of frequency;
    secondary key on ascending numeric value. */
 static int
-compare_freq_numeric_a (const void *a_, const void *b_, void *foo unused)
+compare_freq_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
 {
   const struct freq *a = a_;
   const struct freq *b = b_;
 
-  if (a->v.c > b->v.c)
+  if (a->c > b->c)
     return 1;
-  else if (a->v.c < b->v.c)
+  else if (a->c < b->c)
     return -1;
 
   if (a->v.f > b->v.f)
@@ -912,9 +1052,9 @@ compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
   const struct freq *b = b_;
   const struct variable *v = v_;
 
-  if (a->v.c > b->v.c)
+  if (a->c > b->c)
     return 1;
-  else if (a->v.c < b->v.c)
+  else if (a->c < b->c)
     return -1;
   else
     return memcmp (a->v.s, b->v.s, v->width);
@@ -923,14 +1063,14 @@ compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
 /* Descending numeric compare of frequency;
    secondary key on ascending numeric value. */
 static int
-compare_freq_numeric_d (const void *a_, const void *b_, void *foo unused)
+compare_freq_numeric_d (const void *a_, const void *b_, void *foo UNUSED)
 {
   const struct freq *a = a_;
   const struct freq *b = b_;
 
-  if (a->v.c > b->v.c)
+  if (a->c > b->c)
     return -1;
-  else if (a->v.c < b->v.c)
+  else if (a->c < b->c)
     return 1;
 
   if (a->v.f > b->v.f)
@@ -950,9 +1090,9 @@ compare_freq_alpha_d (const void *a_, const void *b_, void *v_)
   const struct freq *b = b_;
   const struct variable *v = v_;
 
-  if (a->v.c > b->v.c)
+  if (a->c > b->c)
     return -1;
-  else if (a->v.c < b->v.c)
+  else if (a->c < b->c)
     return 1;
   else
     return memcmp (a->v.s, b->v.s, v->width);
@@ -978,9 +1118,10 @@ full_dim (struct tab_table *t, struct outp_driver *d)
 
 /* Displays a full frequency table for variable V. */
 static void
-dump_full (struct variable * v)
+dump_full (struct variable *v)
 {
   int n_categories;
+  struct freq_tab *ft;
   struct freq *f;
   struct tab_table *t;
   int r;
@@ -1013,7 +1154,8 @@ dump_full (struct variable * v)
 
   int lab = cmd.labels == FRQ_LABELS;
 
-  n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
+  ft = &get_var_freqs (v)->tab;
+  n_categories = ft->n_valid + ft->n_missing;
   t = tab_create (5 + lab, n_categories + 3, 0);
   tab_headers (t, 0, 0, 2, 0);
   tab_dim (t, full_dim);
@@ -1025,14 +1167,14 @@ dump_full (struct variable * v)
                  TAB_CENTER | TAT_TITLE, gettext (p->s));
 
   r = 2;
-  for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
+  for (f = ft->valid; f < ft->missing; f++)
     {
       double percent, valid_percent;
 
       cum_freq += f->c;
 
-      percent = f->c / v->p.frq.tab.total_cases * 100.0;
-      valid_percent = f->c / v->p.frq.tab.valid_cases * 100.0;
+      percent = f->c / ft->total_cases * 100.0;
+      valid_percent = f->c / ft->valid_cases * 100.0;
       cum_total += valid_percent;
 
       if (lab)
@@ -1049,7 +1191,7 @@ dump_full (struct variable * v)
       tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
       r++;
     }
-  for (; f < &v->p.frq.tab.valid[n_categories]; f++)
+  for (; f < &ft->valid[n_categories]; f++)
     {
       cum_freq += f->c;
 
@@ -1063,7 +1205,7 @@ dump_full (struct variable * v)
       tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
       tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
       tab_float (t, 2 + lab, r, TAB_NONE,
-                    f->c / v->p.frq.tab.total_cases * 100.0, 5, 1);
+                    f->c / ft->total_cases * 100.0, 5, 1);
       tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
       r++;
     }
@@ -1081,6 +1223,7 @@ dump_full (struct variable * v)
 
   tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
   tab_submit (t);
+
 }
 
 /* Sets the widths of all the columns and heights of all the rows in
@@ -1104,15 +1247,17 @@ condensed_dim (struct tab_table *t, struct outp_driver *d)
 
 /* Display condensed frequency table for variable V. */
 static void
-dump_condensed (struct variable * v)
+dump_condensed (struct variable *v)
 {
   int n_categories;
+  struct freq_tab *ft;
   struct freq *f;
   struct tab_table *t;
   int r;
   double cum_total = 0.0;
 
-  n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
+  ft = &get_var_freqs (v)->tab;
+  n_categories = ft->n_valid + ft->n_missing;
   t = tab_create (4, n_categories + 2, 0);
 
   tab_headers (t, 0, 0, 2, 0);
@@ -1124,12 +1269,12 @@ dump_condensed (struct variable * v)
   tab_dim (t, condensed_dim);
 
   r = 2;
-  for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
+  for (f = ft->valid; f < ft->missing; f++)
     {
       double percent;
 
-      percent = f->c / v->p.frq.tab.total_cases * 100.0;
-      cum_total += f->c / v->p.frq.tab.valid_cases * 100.0;
+      percent = f->c / ft->total_cases * 100.0;
+      cum_total += f->c / ft->valid_cases * 100.0;
 
       tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
       tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
@@ -1137,12 +1282,12 @@ dump_condensed (struct variable * v)
       tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
       r++;
     }
-  for (; f < &v->p.frq.tab.valid[n_categories]; f++)
+  for (; f < &ft->valid[n_categories]; f++)
     {
       tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
       tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
       tab_float (t, 2, r, TAB_NONE,
-                f->c / v->p.frq.tab.total_cases * 100.0, 3, 0);
+                f->c / ft->total_cases * 100.0, 3, 0);
       r++;
     }
 
@@ -1160,43 +1305,129 @@ dump_condensed (struct variable * v)
 /* Calculates all the pertinent statistics for variable V, putting
    them in array D[].  FIXME: This could be made much more optimal. */
 static void
-calc_stats (struct variable * v, double d[frq_n_stats])
+calc_stats (struct variable *v, double d[frq_n_stats])
 {
-  double W = v->p.frq.tab.valid_cases;
-  double X_bar, X_mode, M2, M3, M4;
-  struct freq *f;
+  struct freq_tab *ft = &get_var_freqs (v)->tab;
+  double W = ft->valid_cases;
+  struct moments *m;
+  struct freq *f=0; 
   int most_often;
+  double X_mode;
 
-  double cum_total;
+  double rank;
   int i = 0;
-  double previous_value;
-
-  /* Calculate the mean. */
-  X_bar = 0.0;
-  for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
-    X_bar += f->v.f * f->c;
-  X_bar /= W;
+  int idx;
+  double *median_value;
 
   /* Calculate percentiles. */
-  cum_total = 0;
-  previous_value = SYSMIS;
-  for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
+
+  /* If the 50th percentile was not explicitly requested then we must 
+     calculate it anyway --- it's the median */
+  median_value = 0 ;
+  for (i = 0; i < n_percentiles; i++) 
+    {
+      if (percentiles[i].p == 0.5)
+       {
+         median_value = &percentiles[i].value;
+         break;
+       }
+    }
+
+  if ( 0 == median_value )  
+    {
+      add_percentile (0.5);
+      implicit_50th = 1;
+    }
+
+  for (i = 0; i < n_percentiles; i++) 
+    {
+      percentiles[i].flag = 0;
+      percentiles[i].flag2 = 0;
+    }
+
+  rank = 0;
+  for (idx = 0; idx < ft->n_valid; ++idx)
     {
-      cum_total += f->c ;
-      for (; i < n_percentiles; i++) 
+      static double prev_value = SYSMIS;
+      f = &ft->valid[idx]; 
+      rank += f->c ;
+      for (i = 0; i < n_percentiles; i++) 
         {
-          if (cum_total / v->p.frq.tab.valid_cases < percentiles[i])
-            break;
+         double tp;
+         if ( percentiles[i].flag2  ) continue ; 
+
+         if ( get_algorithm() != COMPATIBLE ) 
+           tp = 
+             (ft->valid_cases - 1) *  percentiles[i].p;
+         else
+           tp = 
+             (ft->valid_cases + 1) *  percentiles[i].p - 1;
+
+         if ( percentiles[i].flag ) 
+           {
+             percentiles[i].x2 = f->v.f;
+             percentiles[i].x1 = prev_value;
+             percentiles[i].flag2 = 1;
+             continue;
+           }
+
+          if (rank >  tp ) 
+         {
+           if ( f->c > 1 && rank - (f->c - 1) > tp ) 
+             {
+               percentiles[i].x2 = percentiles[i].x1 = f->v.f;
+               percentiles[i].flag2 = 1;
+             }
+           else
+             {
+               percentiles[i].flag=1;
+             }
 
-          percentile_values[i] = previous_value;
+           continue;
+         }
         }
-      previous_value = f->v.f;
+      prev_value = f->v.f;
+    }
+
+  for (i = 0; i < n_percentiles; i++) 
+    {
+      /* Catches the case when p == 100% */
+      if ( ! percentiles[i].flag2 ) 
+       percentiles[i].x1 = percentiles[i].x2 = f->v.f;
+
+      /*
+      printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
+            i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
+      */
+    }
+
+  for (i = 0; i < n_percentiles; i++) 
+    {
+      struct freq_tab *ft = &get_var_freqs (v)->tab;
+      double s;
+
+      double dummy;
+      if ( get_algorithm() != COMPATIBLE ) 
+       {
+         s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
+       }
+      else
+       {
+         s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
+       }
+
+      percentiles[i].value = percentiles[i].x1 + 
+       ( percentiles[i].x2 - percentiles[i].x1) * s ; 
+
+      if ( percentiles[i].p == 0.50) 
+       median_value = &percentiles[i].value; 
     }
 
+
   /* Calculate the mode. */
   most_often = -1;
   X_mode = SYSMIS;
-  for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
+  for (f = ft->valid; f < ft->missing; f++)
     {
       if (most_often < f->c) 
         {
@@ -1211,69 +1442,47 @@ calc_stats (struct variable * v, double d[frq_n_stats])
         }
     }
 
-  /* Calculate moments about the mean. */
-  M2 = M3 = M4 = 0.0;
-  for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
-    {
-      double dev = f->v.f - X_bar;
-      double tmp;
-      tmp = dev * dev;
-      M2 += f->c * tmp;
-      tmp *= dev;
-      M3 += f->c * tmp;
-      tmp *= dev;
-      M4 += f->c * tmp;
-    }
-
+  /* Calculate moments. */
+  m = moments_create (MOMENT_KURTOSIS);
+  for (f = ft->valid; f < ft->missing; f++)
+    moments_pass_one (m, f->v.f, f->c);
+  for (f = ft->valid; f < ft->missing; f++)
+    moments_pass_two (m, f->v.f, f->c);
+  moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
+                     &d[frq_skew], &d[frq_kurt]);
+  moments_destroy (m);
+                     
   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
-  d[frq_min] = v->p.frq.tab.valid[0].v.f;
-  d[frq_max] = v->p.frq.tab.valid[v->p.frq.tab.n_valid - 1].v.f;
+  d[frq_min] = ft->valid[0].v.f;
+  d[frq_max] = ft->valid[ft->n_valid - 1].v.f;
   d[frq_mode] = X_mode;
   d[frq_range] = d[frq_max] - d[frq_min];
-  d[frq_median] = SYSMIS;
-  d[frq_mean] = X_bar;
-  d[frq_sum] = X_bar * W;
-  d[frq_variance] = M2 / (W - 1);
+  d[frq_median] = *median_value;
+  d[frq_sum] = d[frq_mean] * W;
   d[frq_stddev] = sqrt (d[frq_variance]);
   d[frq_semean] = d[frq_stddev] / sqrt (W);
-  if (W >= 3.0 && d[frq_variance] > 0)
-    {
-      double S = d[frq_stddev];
-      d[frq_skew] = (W * M3 / ((W - 1.0) * (W - 2.0) * S * S * S));
-      d[frq_seskew] = sqrt (6.0 * W * (W - 1.0)
-                           / ((W - 2.0) * (W + 1.0) * (W + 3.0)));
-    }
-  else
-    {
-      d[frq_skew] = d[frq_seskew] = SYSMIS;
-    }
-  if (W >= 4.0 && d[frq_variance] > 0)
-    {
-      double S2 = d[frq_variance];
-      double SE_g1 = d[frq_seskew];
-
-      d[frq_kurt] = ((W * (W + 1.0) * M4 - 3.0 * M2 * M2 * (W - 1.0))
-                    / ((W - 1.0) * (W - 2.0) * (W - 3.0) * S2 * S2));
-      d[frq_sekurt] = sqrt ((4.0 * (W * W - 1.0) * SE_g1 * SE_g1)
-                           / ((W - 3.0) * (W + 5.0)));
-    }
-  else
-    {
-      d[frq_kurt] = d[frq_sekurt] = SYSMIS;
-    }
+  d[frq_seskew] = calc_seskew (W);
+  d[frq_sekurt] = calc_sekurt (W);
 }
 
 /* Displays a table of all the statistics requested for variable V. */
 static void
-dump_statistics (struct variable * v, int show_varname)
+dump_statistics (struct variable *v, int show_varname)
 {
+  struct freq_tab *ft;
   double stat_value[frq_n_stats];
   struct tab_table *t;
   int i, r;
 
+  int n_explicit_percentiles = n_percentiles;
+
+  if ( implicit_50th && n_percentiles > 0 ) 
+    --n_percentiles;
+
   if (v->type == ALPHA)
     return;
-  if (v->p.frq.tab.n_valid == 0)
+  ft = &get_var_freqs (v)->tab;
+  if (ft->n_valid == 0)
     {
       msg (SW, _("No valid data for variable %s; statistics not displayed."),
           v->name);
@@ -1281,29 +1490,44 @@ dump_statistics (struct variable * v, int show_varname)
     }
   calc_stats (v, stat_value);
 
-  t = tab_create (2, n_stats + n_percentiles, 0);
+  t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
   tab_dim (t, tab_natural_dimensions);
-  tab_vline (t, TAL_1 | TAL_SPACING, 1, 0, n_stats - 1);
-  for (i = r = 0; i < frq_n_stats; i++)
+
+  tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
+
+
+  tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
+  tab_vline (t, TAL_1 | TAL_SPACING , 1, 0, tab_nr(t) - 1 ) ;
+  
+  r=2; /* N missing and N valid are always dumped */
+
+  for (i = 0; i < frq_n_stats; i++)
     if (stats & BIT_INDEX (i))
       {
        tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
                      gettext (st_name[i].s10));
-       tab_float (t, 1, r, TAB_NONE, stat_value[i], 11, 3);
+       tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
        r++;
       }
 
-  for (i = 0; i < n_percentiles; i++, r++) 
-    {
-      struct string ds;
+  tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
+  tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
+  tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
 
-      ds_init (gen_pool, &ds, 20);
-      ds_printf (&ds, "%s %d", _("Percentile"), (int) (percentiles[i] * 100));
+  tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
+  tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
+
+
+  for (i = 0; i < n_explicit_percentiles; i++, r++) 
+    {
+      if ( i == 0 ) 
+       { 
+         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
+       }
 
-      tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, ds.string);
-      tab_float (t, 1, r, TAB_NONE, percentile_values[i], 11, 3);
+      tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
+      tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
 
-      ds_destroy (&ds);
     }
 
   tab_columns (t, SOM_COL_DOWN, 1);
@@ -1316,9 +1540,100 @@ dump_statistics (struct variable * v, int show_varname)
     }
   else
     tab_flags (t, SOMF_NO_TITLE);
-  
+
+
   tab_submit (t);
 }
+
+
+/* Create a gsl_histogram from a freq_tab */
+gsl_histogram *
+freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
+{
+  int i;
+  double x_min = DBL_MAX;
+  double x_max = -DBL_MAX;
+
+  gsl_histogram *hist;
+  const double bins = 11;
+
+  struct hsh_iterator hi;
+  struct hsh_table *fh = ft->data;
+  struct freq *frq;
+
+  /* Find out the extremes of the x value */
+  for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) ) 
+    {
+      if ( is_missing(&frq->v, var))
+       continue;
+
+      if ( frq->v.f < x_min ) x_min = frq->v.f ;
+      if ( frq->v.f > x_max ) x_max = frq->v.f ;
+    }
+
+  hist = histogram_create(bins, x_min, x_max);
+
+  for( i = 0 ; i < ft->n_valid ; ++i ) 
+    {
+      frq = &ft->valid[i];
+      gsl_histogram_accumulate(hist, frq->v.f, frq->c);
+    }
+
+  return hist;
+}
+
+
+static struct slice *
+freq_tab_to_slice_array(const struct freq_tab *frq_tab, 
+                       const struct variable *var,
+                       int *n_slices);
+
+
+/* Allocate an array of slices and fill them from the data in frq_tab
+   n_slices will contain the number of slices allocated.
+   The caller is responsible for freeing slices
+*/
+static struct slice *
+freq_tab_to_slice_array(const struct freq_tab *frq_tab, 
+                       const struct variable *var,
+                       int *n_slices)
+{
+  int i;
+  struct slice *slices;
+
+  *n_slices = frq_tab->n_valid;
+  
+  slices = xmalloc ( *n_slices * sizeof (struct slice ) );
+
+  for (i = 0 ; i < *n_slices ; ++i ) 
+    {
+      const struct freq *frq = &frq_tab->valid[i];
+
+      slices[i].label = value_to_string(&frq->v, var);
+
+      slices[i].magnetude = frq->c;
+    }
+
+  return slices;
+}
+
+
+
+
+static void
+do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
+{
+  struct slice *slices;
+  int n_slices;
+
+  slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
+
+  piechart_plot(var_to_string(var), slices, n_slices);
+
+  free(slices);
+}
+
+
 /* 
    Local Variables:
    mode: c