Changed a lot of non-const pointers to const.
[pspp-builds.git] / src / language / stats / frequencies.q
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19 /*
20   TODO:
21
22   * Remember that histograms, bar charts need mean, stddev.
23 */
24
25 #include <config.h>
26
27 #include <math.h>
28 #include <stdlib.h>
29 #include <gsl/gsl_histogram.h>
30
31 #include <data/case.h>
32 #include <data/dictionary.h>
33 #include <data/format.h>
34 #include <data/procedure.h>
35 #include <data/settings.h>
36 #include <data/value-labels.h>
37 #include <data/variable.h>
38 #include <language/command.h>
39 #include <language/dictionary/split-file.h>
40 #include <language/lexer/lexer.h>
41 #include <libpspp/alloc.h>
42 #include <libpspp/array.h>
43 #include <libpspp/bit-vector.h>
44 #include <libpspp/compiler.h>
45 #include <libpspp/hash.h>
46 #include <libpspp/magic.h>
47 #include <libpspp/message.h>
48 #include <libpspp/message.h>
49 #include <libpspp/misc.h>
50 #include <libpspp/pool.h>
51 #include <libpspp/str.h>
52 #include <math/histogram.h>
53 #include <math/moments.h>
54 #include <output/chart.h>
55 #include <output/charts/piechart.h>
56 #include <output/charts/plot-hist.h>
57 #include <output/manager.h>
58 #include <output/output.h>
59 #include <output/table.h>
60
61 #include "freq.h"
62
63 #include "minmax.h"
64
65 #include "gettext.h"
66 #define _(msgid) gettext (msgid)
67 #define N_(msgid) msgid
68
69 /* (headers) */
70
71 /* (specification)
72    FREQUENCIES (frq_):
73      *+variables=custom;
74      +format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
75              table:limit(n:limit,"%s>0")/notable/!table, 
76              labels:!labels/nolabels,
77              sort:!avalue/dvalue/afreq/dfreq,
78              spaces:!single/double,
79              paging:newpage/!oldpage;
80      missing=miss:include/!exclude;
81      barchart(ba_)=:minimum(d:min),
82             :maximum(d:max),
83             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
84      piechart(pie_)=:minimum(d:min),
85             :maximum(d:max),
86             missing:missing/!nomissing;
87      histogram(hi_)=:minimum(d:min),
88             :maximum(d:max),
89             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
90             norm:!nonormal/normal,
91             incr:increment(d:inc,"%s>0");
92      hbar(hb_)=:minimum(d:min),
93             :maximum(d:max),
94             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
95             norm:!nonormal/normal,
96             incr:increment(d:inc,"%s>0");
97      +grouped=custom;
98      +ntiles=integer;
99      +percentiles = double list;
100      +statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
101             7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
102             13|default,14|seskewness,15|sekurtosis,all,none.
103 */
104 /* (declarations) */
105 /* (functions) */
106
107 /* Statistics. */
108 enum
109   {
110     frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
111     frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
112     frq_sum, frq_n_stats
113   };
114
115 /* Description of a statistic. */
116 struct frq_info
117   {
118     int st_indx;                /* Index into a_statistics[]. */
119     const char *s10;            /* Identifying string. */
120   };
121
122 /* Table of statistics, indexed by dsc_*. */
123 static const struct frq_info st_name[frq_n_stats + 1] =
124 {
125   {FRQ_ST_MEAN, N_("Mean")},
126   {FRQ_ST_SEMEAN, N_("S.E. Mean")},
127   {FRQ_ST_MEDIAN, N_("Median")},
128   {FRQ_ST_MODE, N_("Mode")},
129   {FRQ_ST_STDDEV, N_("Std Dev")},
130   {FRQ_ST_VARIANCE, N_("Variance")},
131   {FRQ_ST_KURTOSIS, N_("Kurtosis")},
132   {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
133   {FRQ_ST_SKEWNESS, N_("Skewness")},
134   {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
135   {FRQ_ST_RANGE, N_("Range")},
136   {FRQ_ST_MINIMUM, N_("Minimum")},
137   {FRQ_ST_MAXIMUM, N_("Maximum")},
138   {FRQ_ST_SUM, N_("Sum")},
139   {-1, 0},
140 };
141
142 /* Percentiles to calculate. */
143
144 struct percentile
145 {
146   double p;        /* the %ile to be calculated */
147   double value;    /* the %ile's value */
148   double x1;       /* The datum value <= the percentile */
149   double x2;       /* The datum value >= the percentile */
150   int flag;        
151   int flag2;       /* Set to 1 if this percentile value has been found */
152 };
153
154
155 static void add_percentile (double x) ;
156
157 static struct percentile *percentiles;
158 static int n_percentiles;
159
160 static int implicit_50th ; 
161
162 /* Groups of statistics. */
163 #define BI          BIT_INDEX
164 #define frq_default                                                     \
165         (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
166 #define frq_all                                                 \
167         (BI (frq_sum) | BI(frq_min) | BI(frq_max)               \
168          | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev)       \
169          | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt)     \
170          | BI(frq_skew) | BI(frq_seskew) | BI(frq_range)        \
171          | BI(frq_range) | BI(frq_mode) | BI(frq_median))
172
173 /* Statistics; number of statistics. */
174 static unsigned long stats;
175 static int n_stats;
176
177 /* Types of graphs. */
178 enum
179   {
180     GFT_NONE,                   /* Don't draw graphs. */
181     GFT_BAR,                    /* Draw bar charts. */
182     GFT_HIST,                   /* Draw histograms. */
183     GFT_PIE,                    /* Draw piechart */
184     GFT_HBAR                    /* Draw bar charts or histograms at our discretion. */
185   };
186
187 /* Parsed command. */
188 static struct cmd_frequencies cmd;
189
190 /* Summary of the barchart, histogram, and hbar subcommands. */
191 /* FIXME: These should not be mututally exclusive */
192 static int chart;               /* NONE/BAR/HIST/HBAR/PIE. */
193 static double min, max;         /* Minimum, maximum on y axis. */
194 static int format;              /* FREQ/PERCENT: Scaling of y axis. */
195 static double scale, incr;      /* FIXME */
196 static int normal;              /* FIXME */
197
198 /* Variables for which to calculate statistics. */
199 static size_t n_variables;
200 static const struct variable **v_variables;
201
202 /* Arenas used to store semi-permanent storage. */
203 static struct pool *int_pool;   /* Integer mode. */
204 static struct pool *gen_pool;   /* General mode. */
205
206 /* Frequency tables. */
207
208 /* Types of frequency tables. */
209 enum
210   {
211     FRQM_GENERAL,
212     FRQM_INTEGER
213   };
214
215 /* Entire frequency table. */
216 struct freq_tab
217   {
218     int mode;                   /* FRQM_GENERAL or FRQM_INTEGER. */
219
220     /* General mode. */
221     struct hsh_table *data;     /* Undifferentiated data. */
222
223     /* Integer mode. */
224     double *vector;             /* Frequencies proper. */
225     int min, max;               /* The boundaries of the table. */
226     double out_of_range;        /* Sum of weights of out-of-range values. */
227     double sysmis;              /* Sum of weights of SYSMIS values. */
228
229     /* All modes. */
230     struct freq *valid;         /* Valid freqs. */
231     int n_valid;                /* Number of total freqs. */
232
233     struct freq *missing;       /* Missing freqs. */
234     int n_missing;              /* Number of missing freqs. */
235
236     /* Statistics. */
237     double total_cases;         /* Sum of weights of all cases. */
238     double valid_cases;         /* Sum of weights of valid cases. */
239   };
240
241
242 /* Per-variable frequency data. */
243 struct var_freqs
244   {
245     /* Freqency table. */
246     struct freq_tab tab;        /* Frequencies table to use. */
247
248     /* Percentiles. */
249     int n_groups;               /* Number of groups. */
250     double *groups;             /* Groups. */
251
252     /* Statistics. */
253     double stat[frq_n_stats];
254
255     /* Width and format for analysis and display.
256        This is normally the same as "width" and "print" in struct
257        variable, but in SPSS-compatible mode only the first
258        MAX_SHORT_STRING bytes of long string variables are
259        included. */
260     int width;
261     struct fmt_spec print;
262   };
263
264 static inline struct var_freqs *
265 get_var_freqs (const struct variable *v)
266 {
267   return var_get_aux (v);
268 }
269
270 static void determine_charts (void);
271
272 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
273
274 static void precalc (const struct ccase *, void *, const struct dataset *);
275 static bool calc (const struct ccase *, void *, const struct dataset *);
276 static bool postcalc (void *, const struct dataset *);
277
278 static void postprocess_freq_tab (const struct variable *);
279 static void dump_full (const struct variable *);
280 static void dump_condensed (const struct variable *);
281 static void dump_statistics (const struct variable *, int show_varname);
282 static void cleanup_freq_tab (const struct variable *);
283
284 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
285 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
286 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
287 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
288
289
290 static void do_piechart(const struct variable *var,
291                         const struct freq_tab *frq_tab);
292
293 gsl_histogram * 
294 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
295
296
297 \f
298 /* Parser and outline. */
299
300 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
301
302 int
303 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
304 {
305   int result;
306
307   int_pool = pool_create ();
308   result = internal_cmd_frequencies (lexer, ds);
309   pool_destroy (int_pool);
310   int_pool=0;
311   pool_destroy (gen_pool);
312   gen_pool=0;
313   free (v_variables);
314   v_variables=0;
315   return result;
316 }
317
318 static int
319 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
320 {
321   int i;
322   bool ok;
323
324   n_percentiles = 0;
325   percentiles = NULL;
326
327   n_variables = 0;
328   v_variables = NULL;
329
330   if (!parse_frequencies (lexer, ds, &cmd, NULL))
331     return CMD_FAILURE;
332
333   if (cmd.onepage_limit == NOT_LONG)
334     cmd.onepage_limit = 50;
335
336   /* Figure out statistics to calculate. */
337   stats = 0;
338   if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
339     stats |= frq_default;
340   if (cmd.a_statistics[FRQ_ST_ALL])
341     stats |= frq_all;
342   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
343     stats &= ~frq_median;
344   for (i = 0; i < frq_n_stats; i++)
345     if (cmd.a_statistics[st_name[i].st_indx])
346       stats |= BIT_INDEX (i);
347   if (stats & frq_kurt)
348     stats |= frq_sekurt;
349   if (stats & frq_skew)
350     stats |= frq_seskew;
351
352   /* Calculate n_stats. */
353   n_stats = 0;
354   for (i = 0; i < frq_n_stats; i++)
355     if ((stats & BIT_INDEX (i)))
356       n_stats++;
357
358   /* Charting. */
359   determine_charts ();
360   if (chart != GFT_NONE || cmd.sbc_ntiles)
361     cmd.sort = FRQ_AVALUE;
362
363   /* Work out what percentiles need to be calculated */
364   if ( cmd.sbc_percentiles ) 
365     {
366       for ( i = 0 ; i < MAXLISTS ; ++i ) 
367         {
368           int pl;
369           subc_list_double *ptl_list = &cmd.dl_percentiles[i];
370           for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
371               add_percentile (subc_list_double_at(ptl_list, pl) / 100.0 );
372         }
373     }
374   if ( cmd.sbc_ntiles ) 
375     {
376       for ( i = 0 ; i < cmd.sbc_ntiles ; ++i ) 
377         {
378           int j;
379           for (j = 0; j <= cmd.n_ntiles[i]; ++j ) 
380               add_percentile (j / (double) cmd.n_ntiles[i]);
381         }
382     }
383   
384
385   /* Do it! */
386   ok = procedure_with_splits (ds, precalc, calc, postcalc, NULL);
387
388   free_frequencies(&cmd);
389
390   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
391 }
392
393 /* Figure out which charts the user requested.  */
394 static void
395 determine_charts (void)
396 {
397   int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) + 
398     (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
399
400   if (!count)
401     {
402       chart = GFT_NONE;
403       return;
404     }
405   else if (count > 1)
406     {
407       chart = GFT_HBAR;
408       msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
409            "given.  HBAR will be assumed.  Argument values will be "
410            "given precedence increasing along the order given."));
411     }
412   else if (cmd.sbc_histogram)
413     chart = GFT_HIST;
414   else if (cmd.sbc_barchart)
415     chart = GFT_BAR;
416   else if (cmd.sbc_piechart)
417     chart = GFT_PIE;
418   else
419     chart = GFT_HBAR;
420
421   min = max = SYSMIS;
422   format = FRQ_FREQ;
423   scale = SYSMIS;
424   incr = SYSMIS;
425   normal = 0;
426
427   if (cmd.sbc_barchart)
428     {
429       if (cmd.ba_min != SYSMIS)
430         min = cmd.ba_min;
431       if (cmd.ba_max != SYSMIS)
432         max = cmd.ba_max;
433       if (cmd.ba_scale == FRQ_FREQ)
434         {
435           format = FRQ_FREQ;
436           scale = cmd.ba_freq;
437         }
438       else if (cmd.ba_scale == FRQ_PERCENT)
439         {
440           format = FRQ_PERCENT;
441           scale = cmd.ba_pcnt;
442         }
443     }
444
445   if (cmd.sbc_histogram)
446     {
447       if (cmd.hi_min != SYSMIS)
448         min = cmd.hi_min;
449       if (cmd.hi_max != SYSMIS)
450         max = cmd.hi_max;
451       if (cmd.hi_scale == FRQ_FREQ)
452         {
453           format = FRQ_FREQ;
454           scale = cmd.hi_freq;
455         }
456       else if (cmd.hi_scale == FRQ_PERCENT)
457         {
458           format = FRQ_PERCENT;
459           scale = cmd.ba_pcnt;
460         }
461       if (cmd.hi_norm != FRQ_NONORMAL )
462         normal = 1;
463       if (cmd.hi_incr == FRQ_INCREMENT)
464         incr = cmd.hi_inc;
465     }
466
467   if (cmd.sbc_hbar)
468     {
469       if (cmd.hb_min != SYSMIS)
470         min = cmd.hb_min;
471       if (cmd.hb_max != SYSMIS)
472         max = cmd.hb_max;
473       if (cmd.hb_scale == FRQ_FREQ)
474         {
475           format = FRQ_FREQ;
476           scale = cmd.hb_freq;
477         }
478       else if (cmd.hb_scale == FRQ_PERCENT)
479         {
480           format = FRQ_PERCENT;
481           scale = cmd.ba_pcnt;
482         }
483       if (cmd.hb_norm)
484         normal = 1;
485       if (cmd.hb_incr == FRQ_INCREMENT)
486         incr = cmd.hb_inc;
487     }
488
489   if (min != SYSMIS && max != SYSMIS && min >= max)
490     {
491       msg (SE, _("MAX must be greater than or equal to MIN, if both are "
492            "specified.  However, MIN was specified as %g and MAX as %g.  "
493            "MIN and MAX will be ignored."), min, max);
494       min = max = SYSMIS;
495     }
496 }
497
498 /* Add data from case C to the frequency table. */
499 static bool
500 calc (const struct ccase *c, void *aux UNUSED, const struct dataset *ds)
501 {
502   double weight;
503   size_t i;
504   bool bad_warn = true;
505
506   weight = dict_get_case_weight (dataset_dict (ds), c, &bad_warn);
507
508   for (i = 0; i < n_variables; i++)
509     {
510       const struct variable *v = v_variables[i];
511       const union value *val = case_data (c, v);
512       struct var_freqs *vf = get_var_freqs (v);
513       struct freq_tab *ft = &vf->tab;
514
515       switch (ft->mode)
516         {
517           case FRQM_GENERAL:
518             {
519               /* General mode. */
520               struct freq target;
521               struct freq **fpp;
522
523               target.value = (union value *) val;
524               fpp = (struct freq **) hsh_probe (ft->data, &target);
525
526               if (*fpp != NULL)
527                 (*fpp)->count += weight;
528               else
529                 {
530                   struct freq *fp = pool_alloc (gen_pool, sizeof *fp);
531                   fp->count = weight;
532                   fp->value = pool_clone (gen_pool,
533                                       val, MAX (MAX_SHORT_STRING, vf->width));
534                   *fpp = fp;
535                 }
536             }
537           break;
538         case FRQM_INTEGER:
539           /* Integer mode. */
540           if (val->f == SYSMIS)
541             ft->sysmis += weight;
542           else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
543             {
544               int i = val->f;
545               if (i >= ft->min && i <= ft->max)
546                 ft->vector[i - ft->min] += weight;
547             }
548           else
549             ft->out_of_range += weight;
550           break;
551         default:
552           NOT_REACHED ();
553         }
554     }
555   return true;
556 }
557
558 /* Prepares each variable that is the target of FREQUENCIES by setting
559    up its hash table. */
560 static void
561 precalc (const struct ccase *first, void *aux UNUSED, const struct dataset *ds)
562 {
563   size_t i;
564
565   output_split_file_values (ds, first);
566
567   pool_destroy (gen_pool);
568   gen_pool = pool_create ();
569   
570   for (i = 0; i < n_variables; i++)
571     {
572       const struct variable *v = v_variables[i];
573       struct freq_tab *ft = &get_var_freqs (v)->tab;
574
575       if (ft->mode == FRQM_GENERAL)
576         {
577           ft->data = hsh_create (16, compare_freq, hash_freq, NULL, v);
578         }
579       else
580         {
581           int j;
582
583           for (j = (ft->max - ft->min); j >= 0; j--)
584             ft->vector[j] = 0.0;
585           ft->out_of_range = 0.0;
586           ft->sysmis = 0.0;
587         }
588     }
589 }
590
591 /* Finishes up with the variables after frequencies have been
592    calculated.  Displays statistics, percentiles, ... */
593 static bool
594 postcalc (void *aux UNUSED, const struct dataset *ds  UNUSED)
595 {
596   size_t i;
597
598   for (i = 0; i < n_variables; i++)
599     {
600       const struct variable *v = v_variables[i];
601       struct var_freqs *vf = get_var_freqs (v);
602       struct freq_tab *ft = &vf->tab;
603       int n_categories;
604       int dumped_freq_tab = 1;
605
606       postprocess_freq_tab (v);
607
608       /* Frequencies tables. */
609       n_categories = ft->n_valid + ft->n_missing;
610       if (cmd.table == FRQ_TABLE
611           || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
612         switch (cmd.cond)
613           {
614           case FRQ_CONDENSE:
615             dump_condensed (v);
616             break;
617           case FRQ_STANDARD:
618             dump_full (v);
619             break;
620           case FRQ_ONEPAGE:
621             if (n_categories > cmd.onepage_limit)
622               dump_condensed (v);
623             else
624               dump_full (v);
625             break;
626           default:
627             NOT_REACHED ();
628           }
629       else
630         dumped_freq_tab = 0;
631
632       /* Statistics. */
633       if (n_stats)
634         dump_statistics (v, !dumped_freq_tab);
635
636
637
638       if ( chart == GFT_HIST) 
639         {
640           double d[frq_n_stats];
641           struct normal_curve norm;
642           gsl_histogram *hist ;
643
644
645           norm.N = vf->tab.valid_cases;
646
647           calc_stats (v, d);
648           norm.mean = d[frq_mean];
649           norm.stddev = d[frq_stddev];
650
651           hist = freq_tab_to_hist(ft,v);
652
653           histogram_plot(hist, var_to_string(v), &norm, normal);
654
655           gsl_histogram_free(hist);
656         }
657
658
659       if ( chart == GFT_PIE) 
660         {
661           do_piechart(v_variables[i], ft);
662         }
663
664
665
666       cleanup_freq_tab (v);
667
668     }
669
670   return true;
671 }
672
673 /* Returns the comparison function that should be used for
674    sorting a frequency table by FRQ_SORT using VAR_TYPE
675    variables. */
676 static hsh_compare_func *
677 get_freq_comparator (int frq_sort, enum var_type var_type) 
678 {
679   bool is_numeric = var_type == VAR_NUMERIC;
680   switch (frq_sort)
681     {
682     case FRQ_AVALUE:
683       return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
684     case FRQ_DVALUE:
685       return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
686     case FRQ_AFREQ:
687       return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
688     case FRQ_DFREQ:
689       return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
690     default:
691       NOT_REACHED ();
692     }
693 }
694
695 /* Returns true iff the value in struct freq F is non-missing
696    for variable V. */
697 static bool
698 not_missing (const void *f_, const void *v_) 
699 {
700   const struct freq *f = f_;
701   const struct variable *v = v_;
702
703   return !var_is_value_missing (v, f->value, MV_ANY);
704 }
705
706 /* Summarizes the frequency table data for variable V. */
707 static void
708 postprocess_freq_tab (const struct variable *v)
709 {
710   hsh_compare_func *compare;
711   struct freq_tab *ft;
712   size_t count;
713   void *const *data;
714   struct freq *freqs, *f;
715   size_t i;
716
717   ft = &get_var_freqs (v)->tab;
718   assert (ft->mode == FRQM_GENERAL);
719   compare = get_freq_comparator (cmd.sort, var_get_type (v));
720
721   /* Extract data from hash table. */
722   count = hsh_count (ft->data);
723   data = hsh_data (ft->data);
724
725   /* Copy dereferenced data into freqs. */
726   freqs = xnmalloc (count, sizeof *freqs);
727   for (i = 0; i < count; i++) 
728     {
729       struct freq *f = data[i];
730       freqs[i] = *f; 
731     }
732
733   /* Put data into ft. */
734   ft->valid = freqs;
735   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
736   ft->missing = freqs + ft->n_valid;
737   ft->n_missing = count - ft->n_valid;
738
739   /* Sort data. */
740   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
741   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
742
743   /* Summary statistics. */
744   ft->valid_cases = 0.0;
745   for(i = 0 ;  i < ft->n_valid ; ++i ) 
746     {
747       f = &ft->valid[i];
748       ft->valid_cases += f->count;
749
750     }
751
752   ft->total_cases = ft->valid_cases ; 
753   for(i = 0 ;  i < ft->n_missing ; ++i ) 
754     {
755       f = &ft->missing[i];
756       ft->total_cases += f->count;
757     }
758
759 }
760
761 /* Frees the frequency table for variable V. */
762 static void
763 cleanup_freq_tab (const struct variable *v)
764 {
765   struct freq_tab *ft = &get_var_freqs (v)->tab;
766   assert (ft->mode == FRQM_GENERAL);
767   free (ft->valid);
768   hsh_destroy (ft->data);
769 }
770
771 /* Parses the VARIABLES subcommand, adding to
772    {n_variables,v_variables}. */
773 static int
774 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
775 {
776   int mode;
777   int min = 0, max = 0;
778
779   size_t old_n_variables = n_variables;
780   size_t i;
781
782   lex_match (lexer, '=');
783   if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
784                          || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
785     return 2;
786
787   if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
788                         PV_APPEND | PV_NO_SCRATCH))
789     return 0;
790
791   if (!lex_match (lexer, '('))
792     mode = FRQM_GENERAL;
793   else
794     {
795       mode = FRQM_INTEGER;
796       if (!lex_force_int (lexer))
797         return 0;
798       min = lex_integer (lexer);
799       lex_get (lexer);
800       if (!lex_force_match (lexer, ','))
801         return 0;
802       if (!lex_force_int (lexer))
803         return 0;
804       max = lex_integer (lexer);
805       lex_get (lexer);
806       if (!lex_force_match (lexer, ')'))
807         return 0;
808       if (max < min)
809         {
810           msg (SE, _("Upper limit of integer mode value range must be "
811                      "greater than lower limit."));
812           return 0;
813         }
814     }
815
816   for (i = old_n_variables; i < n_variables; i++)
817     {
818       const struct variable *v = v_variables[i];
819       struct var_freqs *vf;
820
821       if (var_get_aux (v) != NULL)
822         {
823           msg (SE, _("Variable %s specified multiple times on VARIABLES "
824                      "subcommand."), var_get_name (v));
825           return 0;
826         }
827       if (mode == FRQM_INTEGER && !var_is_numeric (v))
828         {
829           msg (SE, _("Integer mode specified, but %s is not a numeric "
830                      "variable."), var_get_name (v));
831           return 0;
832         }
833
834       vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
835       vf->tab.mode = mode;
836       vf->tab.valid = vf->tab.missing = NULL;
837       if (mode == FRQM_INTEGER)
838         {
839           vf->tab.min = min;
840           vf->tab.max = max;
841           vf->tab.vector = pool_nalloc (int_pool,
842                                         max - min + 1, sizeof *vf->tab.vector);
843         }
844       else 
845         vf->tab.vector = NULL;
846       vf->n_groups = 0;
847       vf->groups = NULL;
848       vf->width = var_get_width (v);
849       vf->print = *var_get_print_format (v);
850       if (vf->width > MAX_SHORT_STRING && get_algorithm () == COMPATIBLE) 
851         {
852           enum fmt_type type = var_get_print_format (v)->type;
853           vf->width = MAX_SHORT_STRING;
854           vf->print.w = MAX_SHORT_STRING * (type == FMT_AHEX ? 2 : 1);
855         }
856     }
857   return 1;
858 }
859
860 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
861    fields of specified variables. */
862 static int
863 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
864 {
865   lex_match (lexer, '=');
866   if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
867       || lex_token (lexer) == T_ID)
868     for (;;)
869       {
870         size_t i;
871
872         /* Max, current size of list; list itself. */
873         int nl, ml;
874         double *dl;
875
876         /* Variable list. */
877         size_t n;
878         const struct variable **v;
879
880         if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
881                               PV_NO_DUPLICATE | PV_NUMERIC))
882           return 0;
883         if (lex_match (lexer, '('))
884           {
885             nl = ml = 0;
886             dl = NULL;
887             while (lex_integer (lexer))
888               {
889                 if (nl >= ml)
890                   {
891                     ml += 16;
892                     dl = pool_nrealloc (int_pool, dl, ml, sizeof *dl);
893                   }
894                 dl[nl++] = lex_tokval (lexer);
895                 lex_get (lexer);
896                 lex_match (lexer, ',');
897               }
898             /* Note that nl might still be 0 and dl might still be
899                NULL.  That's okay. */
900             if (!lex_match (lexer, ')'))
901               {
902                 free (v);
903                 msg (SE, _("`)' expected after GROUPED interval list."));
904                 return 0;
905               }
906           }
907         else 
908           {
909             nl = 0;
910             dl = NULL;
911           }
912
913         for (i = 0; i < n; i++)
914           if (var_get_aux (v[i]) == NULL)
915             msg (SE, _("Variables %s specified on GROUPED but not on "
916                        "VARIABLES."), var_get_name (v[i]));
917           else 
918             {
919               struct var_freqs *vf = get_var_freqs (v[i]);
920                 
921               if (vf->groups != NULL)
922                 msg (SE, _("Variables %s specified multiple times on GROUPED "
923                            "subcommand."), var_get_name (v[i]));
924               else
925                 {
926                   vf->n_groups = nl;
927                   vf->groups = dl;
928                 }
929             }
930         free (v);
931         if (!lex_match (lexer, '/'))
932           break;
933         if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
934             && lex_token (lexer) != T_ALL)
935           {
936             lex_put_back (lexer, '/');
937             break;
938           }
939       }
940
941   return 1;
942 }
943
944 /* Adds X to the list of percentiles, keeping the list in proper
945    order. */
946 static void
947 add_percentile (double x)
948 {
949   int i;
950
951   for (i = 0; i < n_percentiles; i++)
952     {
953       /* Do nothing if it's already in the list */
954       if ( fabs(x - percentiles[i].p) < DBL_EPSILON ) 
955         return;
956
957       if (x < percentiles[i].p)
958         break;
959     }
960
961   if (i >= n_percentiles || x != percentiles[i].p)
962     {
963       percentiles = pool_nrealloc (int_pool, percentiles,
964                                    n_percentiles + 1, sizeof *percentiles);
965
966       if (i < n_percentiles)
967           memmove (&percentiles[i + 1], &percentiles[i],
968                    (n_percentiles - i) * sizeof (struct percentile) );
969
970       percentiles[i].p = x;
971       n_percentiles++;
972     }
973 }
974
975 /* Comparison functions. */
976
977 /* Ascending numeric compare of values. */
978 static int
979 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
980 {
981   const struct freq *a = a_;
982   const struct freq *b = b_;
983
984   if (a->value[0].f > b->value[0].f)
985     return 1;
986   else if (a->value[0].f < b->value[0].f)
987     return -1;
988   else
989     return 0;
990 }
991
992 /* Ascending string compare of values. */
993 static int
994 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
995 {
996   const struct freq *a = a_;
997   const struct freq *b = b_;
998   const struct variable *v = v_;
999   struct var_freqs *vf = get_var_freqs (v);
1000
1001   return memcmp (a->value[0].s, b->value[0].s, vf->width);
1002 }
1003
1004 /* Descending numeric compare of values. */
1005 static int
1006 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
1007 {
1008   return -compare_value_numeric_a (a, b, aux);
1009 }
1010
1011 /* Descending string compare of values. */
1012 static int
1013 compare_value_alpha_d (const void *a, const void *b, const void *v)
1014 {
1015   return -compare_value_alpha_a (a, b, v);
1016 }
1017
1018 /* Ascending numeric compare of frequency;
1019    secondary key on ascending numeric value. */
1020 static int
1021 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
1022 {
1023   const struct freq *a = a_;
1024   const struct freq *b = b_;
1025
1026   if (a->count > b->count)
1027     return 1;
1028   else if (a->count < b->count)
1029     return -1;
1030
1031   if (a->value[0].f > b->value[0].f)
1032     return 1;
1033   else if (a->value[0].f < b->value[0].f)
1034     return -1;
1035   else
1036     return 0;
1037 }
1038
1039 /* Ascending numeric compare of frequency;
1040    secondary key on ascending string value. */
1041 static int
1042 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
1043 {
1044   const struct freq *a = a_;
1045   const struct freq *b = b_;
1046   const struct variable *v = v_;
1047   struct var_freqs *vf = get_var_freqs (v);
1048
1049   if (a->count > b->count)
1050     return 1;
1051   else if (a->count < b->count)
1052     return -1;
1053   else
1054     return memcmp (a->value[0].s, b->value[0].s, vf->width);
1055 }
1056
1057 /* Descending numeric compare of frequency;
1058    secondary key on ascending numeric value. */
1059 static int
1060 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
1061 {
1062   const struct freq *a = a_;
1063   const struct freq *b = b_;
1064
1065   if (a->count > b->count)
1066     return -1;
1067   else if (a->count < b->count)
1068     return 1;
1069
1070   if (a->value[0].f > b->value[0].f)
1071     return 1;
1072   else if (a->value[0].f < b->value[0].f)
1073     return -1;
1074   else
1075     return 0;
1076 }
1077
1078 /* Descending numeric compare of frequency;
1079    secondary key on ascending string value. */
1080 static int
1081 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
1082 {
1083   const struct freq *a = a_;
1084   const struct freq *b = b_;
1085   const struct variable *v = v_;
1086   struct var_freqs *vf = get_var_freqs (v);
1087
1088   if (a->count > b->count)
1089     return -1;
1090   else if (a->count < b->count)
1091     return 1;
1092   else
1093     return memcmp (a->value[0].s, b->value[0].s, vf->width);
1094 }
1095 \f
1096 /* Frequency table display. */
1097
1098 /* Sets the widths of all the columns and heights of all the rows in
1099    table T for driver D. */
1100 static void
1101 full_dim (struct tab_table *t, struct outp_driver *d)
1102 {
1103   int i = 0;
1104   int columns = 5;
1105
1106   if (cmd.labels == FRQ_LABELS)
1107     {
1108     t->w[0] = MIN (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1109       i = 1;
1110       columns ++;
1111     }
1112
1113   for (;i < columns; i++)
1114     t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1115
1116   for (i = 0; i < t->nr; i++)
1117     t->h[i] = d->font_height;
1118 }
1119
1120 /* Displays a full frequency table for variable V. */
1121 static void
1122 dump_full (const struct variable *v)
1123 {
1124   int n_categories;
1125   struct var_freqs *vf;
1126   struct freq_tab *ft;
1127   struct freq *f;
1128   struct tab_table *t;
1129   int r;
1130   double cum_total = 0.0;
1131   double cum_freq = 0.0;
1132
1133   struct init
1134     {
1135       int c, r;
1136       const char *s;
1137     };
1138
1139   const struct init *p;
1140
1141   static const struct init vec[] =
1142   {
1143     {4, 0, N_("Valid")},
1144     {5, 0, N_("Cum")},
1145     {1, 1, N_("Value")},
1146     {2, 1, N_("Frequency")},
1147     {3, 1, N_("Percent")},
1148     {4, 1, N_("Percent")},
1149     {5, 1, N_("Percent")},
1150     {0, 0, NULL},
1151     {1, 0, NULL},
1152     {2, 0, NULL},
1153     {3, 0, NULL},
1154     {-1, -1, NULL},
1155   };
1156
1157   const bool lab = (cmd.labels == FRQ_LABELS);
1158
1159   vf = get_var_freqs (v);
1160   ft = &vf->tab;
1161   n_categories = ft->n_valid + ft->n_missing;
1162   t = tab_create (5 + lab, n_categories + 3, 0);
1163   tab_headers (t, 0, 0, 2, 0);
1164   tab_dim (t, full_dim);
1165
1166   if (lab)
1167     tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1168
1169   for (p = vec; p->s; p++)
1170     tab_text (t, lab ? p->c : p->c - 1, p->r,
1171                   TAB_CENTER | TAT_TITLE, gettext (p->s));
1172
1173   r = 2;
1174   for (f = ft->valid; f < ft->missing; f++)
1175     {
1176       double percent, valid_percent;
1177
1178       cum_freq += f->count;
1179
1180       percent = f->count / ft->total_cases * 100.0;
1181       valid_percent = f->count / ft->valid_cases * 100.0;
1182       cum_total += valid_percent;
1183
1184       if (lab)
1185         {
1186           const char *label = var_lookup_value_label (v, &f->value[0]);
1187           if (label != NULL)
1188             tab_text (t, 0, r, TAB_LEFT, label);
1189         }
1190
1191       tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1192       tab_float (t, 1 + lab, r, TAB_NONE, f->count, 8, 0);
1193       tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1194       tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1195       tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1196       r++;
1197     }
1198   for (; f < &ft->valid[n_categories]; f++)
1199     {
1200       cum_freq += f->count;
1201
1202       if (lab)
1203         {
1204           const char *label = var_lookup_value_label (v, &f->value[0]);
1205           if (label != NULL)
1206             tab_text (t, 0, r, TAB_LEFT, label);
1207         }
1208
1209       tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1210       tab_float (t, 1 + lab, r, TAB_NONE, f->count, 8, 0);
1211       tab_float (t, 2 + lab, r, TAB_NONE,
1212                      f->count / ft->total_cases * 100.0, 5, 1);
1213       tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1214       r++;
1215     }
1216
1217   tab_box (t, TAL_1, TAL_1,
1218            cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1219            0, 0, 4 + lab, r);
1220   tab_hline (t, TAL_2, 0, 4 + lab, 2);
1221   tab_hline (t, TAL_2, 0, 4 + lab, r);
1222   tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1223   tab_vline (t, TAL_0, 1, r, r);
1224   tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1225   tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1226   tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1227
1228   tab_title (t, "%s", var_to_string (v));
1229   tab_submit (t);
1230 }
1231
1232 /* Sets the widths of all the columns and heights of all the rows in
1233    table T for driver D. */
1234 static void
1235 condensed_dim (struct tab_table *t, struct outp_driver *d)
1236 {
1237   int cum_w = MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1238                    MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1239                         outp_string_width (d, "000", OUTP_PROPORTIONAL)));
1240
1241   int i;
1242
1243   for (i = 0; i < 2; i++)
1244     t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1245   for (i = 2; i < 4; i++)
1246     t->w[i] = cum_w;
1247   for (i = 0; i < t->nr; i++)
1248     t->h[i] = d->font_height;
1249 }
1250
1251 /* Display condensed frequency table for variable V. */
1252 static void
1253 dump_condensed (const struct variable *v)
1254 {
1255   int n_categories;
1256   struct var_freqs *vf;
1257   struct freq_tab *ft;
1258   struct freq *f;
1259   struct tab_table *t;
1260   int r;
1261   double cum_total = 0.0;
1262
1263   vf = get_var_freqs (v);
1264   ft = &vf->tab;
1265   n_categories = ft->n_valid + ft->n_missing;
1266   t = tab_create (4, n_categories + 2, 0);
1267
1268   tab_headers (t, 0, 0, 2, 0);
1269   tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1270   tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1271   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1272   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1273   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1274   tab_dim (t, condensed_dim);
1275
1276   r = 2;
1277   for (f = ft->valid; f < ft->missing; f++)
1278     {
1279       double percent;
1280
1281       percent = f->count / ft->total_cases * 100.0;
1282       cum_total += f->count / ft->valid_cases * 100.0;
1283
1284       tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1285       tab_float (t, 1, r, TAB_NONE, f->count, 8, 0);
1286       tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1287       tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1288       r++;
1289     }
1290   for (; f < &ft->valid[n_categories]; f++)
1291     {
1292       tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1293       tab_float (t, 1, r, TAB_NONE, f->count, 8, 0);
1294       tab_float (t, 2, r, TAB_NONE,
1295                  f->count / ft->total_cases * 100.0, 3, 0);
1296       r++;
1297     }
1298
1299   tab_box (t, TAL_1, TAL_1,
1300            cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1301            0, 0, 3, r - 1);
1302   tab_hline (t, TAL_2, 0, 3, 2);
1303   tab_title (t, "%s", var_to_string (v));
1304   tab_columns (t, SOM_COL_DOWN, 1);
1305   tab_submit (t);
1306 }
1307 \f
1308 /* Statistical display. */
1309
1310 /* Calculates all the pertinent statistics for variable V, putting
1311    them in array D[].  FIXME: This could be made much more optimal. */
1312 static void
1313 calc_stats (const struct variable *v, double d[frq_n_stats])
1314 {
1315   struct freq_tab *ft = &get_var_freqs (v)->tab;
1316   double W = ft->valid_cases;
1317   struct moments *m;
1318   struct freq *f=0; 
1319   int most_often;
1320   double X_mode;
1321
1322   double rank;
1323   int i = 0;
1324   int idx;
1325   double *median_value;
1326
1327   /* Calculate percentiles. */
1328
1329   /* If the 50th percentile was not explicitly requested then we must 
1330      calculate it anyway --- it's the median */
1331   median_value = 0 ;
1332   for (i = 0; i < n_percentiles; i++) 
1333     {
1334       if (percentiles[i].p == 0.5)
1335         {
1336           median_value = &percentiles[i].value;
1337           break;
1338         }
1339     }
1340
1341   if ( 0 == median_value )  
1342     {
1343       add_percentile (0.5);
1344       implicit_50th = 1;
1345     }
1346
1347   for (i = 0; i < n_percentiles; i++) 
1348     {
1349       percentiles[i].flag = 0;
1350       percentiles[i].flag2 = 0;
1351     }
1352
1353   rank = 0;
1354   for (idx = 0; idx < ft->n_valid; ++idx)
1355     {
1356       static double prev_value = SYSMIS;
1357       f = &ft->valid[idx]; 
1358       rank += f->count ;
1359       for (i = 0; i < n_percentiles; i++) 
1360         {
1361           double tp;
1362           if ( percentiles[i].flag2  ) continue ; 
1363
1364           if ( get_algorithm() != COMPATIBLE ) 
1365             tp = 
1366               (ft->valid_cases - 1) *  percentiles[i].p;
1367           else
1368             tp = 
1369               (ft->valid_cases + 1) *  percentiles[i].p - 1;
1370
1371           if ( percentiles[i].flag ) 
1372             {
1373               percentiles[i].x2 = f->value[0].f;
1374               percentiles[i].x1 = prev_value;
1375               percentiles[i].flag2 = 1;
1376               continue;
1377             }
1378
1379           if (rank >  tp ) 
1380           {
1381             if ( f->count > 1 && rank - (f->count - 1) > tp ) 
1382               {
1383                 percentiles[i].x2 = percentiles[i].x1 = f->value[0].f;
1384                 percentiles[i].flag2 = 1;
1385               }
1386             else
1387               {
1388                 percentiles[i].flag=1;
1389               }
1390
1391             continue;
1392           }
1393         }
1394       prev_value = f->value[0].f;
1395     }
1396
1397   for (i = 0; i < n_percentiles; i++) 
1398     {
1399       /* Catches the case when p == 100% */
1400       if ( ! percentiles[i].flag2 ) 
1401         percentiles[i].x1 = percentiles[i].x2 = f->value[0].f;
1402
1403       /*
1404       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1405              i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1406       */
1407     }
1408
1409   for (i = 0; i < n_percentiles; i++) 
1410     {
1411       struct freq_tab *ft = &get_var_freqs (v)->tab;
1412       double s;
1413
1414       double dummy;
1415       if ( get_algorithm() != COMPATIBLE ) 
1416         {
1417           s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1418         }
1419       else
1420         {
1421           s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1422         }
1423
1424       percentiles[i].value = percentiles[i].x1 + 
1425         ( percentiles[i].x2 - percentiles[i].x1) * s ; 
1426
1427       if ( percentiles[i].p == 0.50) 
1428         median_value = &percentiles[i].value; 
1429     }
1430
1431
1432   /* Calculate the mode. */
1433   most_often = -1;
1434   X_mode = SYSMIS;
1435   for (f = ft->valid; f < ft->missing; f++)
1436     {
1437       if (most_often < f->count) 
1438         {
1439           most_often = f->count;
1440           X_mode = f->value[0].f;
1441         }
1442       else if (most_often == f->count) 
1443         {
1444           /* A duplicate mode is undefined.
1445              FIXME: keep track of *all* the modes. */
1446           X_mode = SYSMIS;
1447         }
1448     }
1449
1450   /* Calculate moments. */
1451   m = moments_create (MOMENT_KURTOSIS);
1452   for (f = ft->valid; f < ft->missing; f++)
1453     moments_pass_one (m, f->value[0].f, f->count);
1454   for (f = ft->valid; f < ft->missing; f++)
1455     moments_pass_two (m, f->value[0].f, f->count);
1456   moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1457                      &d[frq_skew], &d[frq_kurt]);
1458   moments_destroy (m);
1459                      
1460   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1461   d[frq_min] = ft->valid[0].value[0].f;
1462   d[frq_max] = ft->valid[ft->n_valid - 1].value[0].f;
1463   d[frq_mode] = X_mode;
1464   d[frq_range] = d[frq_max] - d[frq_min];
1465   d[frq_median] = *median_value;
1466   d[frq_sum] = d[frq_mean] * W;
1467   d[frq_stddev] = sqrt (d[frq_variance]);
1468   d[frq_semean] = d[frq_stddev] / sqrt (W);
1469   d[frq_seskew] = calc_seskew (W);
1470   d[frq_sekurt] = calc_sekurt (W);
1471 }
1472
1473 /* Displays a table of all the statistics requested for variable V. */
1474 static void
1475 dump_statistics (const struct variable *v, int show_varname)
1476 {
1477   struct freq_tab *ft;
1478   double stat_value[frq_n_stats];
1479   struct tab_table *t;
1480   int i, r;
1481
1482   int n_explicit_percentiles = n_percentiles;
1483
1484   if ( implicit_50th && n_percentiles > 0 ) 
1485     --n_percentiles;
1486
1487   if (var_is_alpha (v))
1488     return;
1489   ft = &get_var_freqs (v)->tab;
1490   if (ft->n_valid == 0)
1491     {
1492       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1493            var_get_name (v));
1494       return;
1495     }
1496   calc_stats (v, stat_value);
1497
1498   t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1499   tab_dim (t, tab_natural_dimensions);
1500
1501   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1502
1503
1504   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1505   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1506   
1507   r=2; /* N missing and N valid are always dumped */
1508
1509   for (i = 0; i < frq_n_stats; i++)
1510     if (stats & BIT_INDEX (i))
1511       {
1512         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1513                       gettext (st_name[i].s10));
1514         tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1515         r++;
1516       }
1517
1518   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1519   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1520   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1521
1522   tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1523   tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1524
1525
1526   for (i = 0; i < n_explicit_percentiles; i++, r++) 
1527     {
1528       if ( i == 0 ) 
1529         { 
1530           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1531         }
1532
1533       tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1534       tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1535
1536     }
1537
1538   tab_columns (t, SOM_COL_DOWN, 1);
1539   if (show_varname)
1540     tab_title (t, "%s", var_to_string (v));
1541   else
1542     tab_flags (t, SOMF_NO_TITLE);
1543
1544
1545   tab_submit (t);
1546 }
1547
1548
1549 /* Create a gsl_histogram from a freq_tab */
1550 gsl_histogram *
1551 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1552 {
1553   int i;
1554   double x_min = DBL_MAX;
1555   double x_max = -DBL_MAX;
1556
1557   gsl_histogram *hist;
1558   const double bins = 11;
1559
1560   struct hsh_iterator hi;
1561   struct hsh_table *fh = ft->data;
1562   struct freq *frq;
1563
1564   /* Find out the extremes of the x value */
1565   for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) ) 
1566     {
1567       if (var_is_value_missing(var, frq->value, MV_ANY))
1568         continue;
1569
1570       if ( frq->value[0].f < x_min ) x_min = frq->value[0].f ;
1571       if ( frq->value[0].f > x_max ) x_max = frq->value[0].f ;
1572     }
1573
1574   hist = histogram_create(bins, x_min, x_max);
1575
1576   for( i = 0 ; i < ft->n_valid ; ++i ) 
1577     {
1578       frq = &ft->valid[i];
1579       gsl_histogram_accumulate(hist, frq->value[0].f, frq->count);
1580     }
1581
1582   return hist;
1583 }
1584
1585
1586 static struct slice *
1587 freq_tab_to_slice_array(const struct freq_tab *frq_tab, 
1588                         const struct variable *var,
1589                         int *n_slices);
1590
1591
1592 /* Allocate an array of slices and fill them from the data in frq_tab
1593    n_slices will contain the number of slices allocated.
1594    The caller is responsible for freeing slices
1595 */
1596 static struct slice *
1597 freq_tab_to_slice_array(const struct freq_tab *frq_tab, 
1598                         const struct variable *var,
1599                         int *n_slices)
1600 {
1601   int i;
1602   struct slice *slices;
1603
1604   *n_slices = frq_tab->n_valid;
1605   
1606   slices = xnmalloc (*n_slices, sizeof *slices);
1607
1608   for (i = 0 ; i < *n_slices ; ++i ) 
1609     {
1610       const struct freq *frq = &frq_tab->valid[i];
1611
1612       slices[i].label = var_get_value_name (var, frq->value);
1613       slices[i].magnetude = frq->count;
1614     }
1615
1616   return slices;
1617 }
1618
1619
1620
1621
1622 static void
1623 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1624 {
1625   struct slice *slices;
1626   int n_slices;
1627
1628   slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1629
1630   piechart_plot(var_to_string(var), slices, n_slices);
1631
1632   free(slices);
1633 }
1634
1635
1636 /* 
1637    Local Variables:
1638    mode: c
1639    End:
1640 */