Added the /BARCHART option to CROSSTABS
[pspp] / src / language / stats / frequencies.c
1 /*
2   PSPP - a program for statistical analysis.
3   Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011, 2014, 2015 Free Software Foundation, Inc.
4    
5   This program is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14   
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <config.h>
20 #include <stdlib.h>
21 #include <gsl/gsl_histogram.h>
22
23
24 #include "data/case.h"
25 #include "data/casegrouper.h"
26 #include "data/casereader.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/format.h"
30 #include "data/missing-values.h"
31 #include "data/settings.h"
32 #include "data/value-labels.h"
33 #include "data/variable.h"
34
35 #include "language/dictionary/split-file.h"
36
37 #include "language/command.h"
38 #include "language/lexer/lexer.h"
39 #include "language/lexer/variable-parser.h"
40 #include "language/stats/freq.h"
41
42 #include "libpspp/array.h"
43 #include "libpspp/bit-vector.h"
44 #include "libpspp/compiler.h"
45 #include "libpspp/hmap.h"
46 #include "libpspp/message.h"
47 #include "libpspp/misc.h"
48 #include "libpspp/pool.h"
49
50 #include "math/histogram.h"
51 #include "math/moments.h"
52 #include "math/chart-geometry.h"
53
54
55 #include "output/chart-item.h"
56 #include "output/charts/barchart.h"
57 #include "output/charts/piechart.h"
58 #include "output/charts/plot-hist.h"
59 #include "output/tab.h"
60
61 #include "gl/minmax.h"
62 #include "gl/xalloc.h"
63
64 #include "gettext.h"
65 #define _(msgid) gettext (msgid)
66 #define N_(msgid) msgid
67
68 /* Percentiles to calculate. */
69
70 struct percentile
71 {
72   double p;        /* the %ile to be calculated */
73   double value;    /* the %ile's value */
74   bool show;       /* True to show this percentile in the statistics box. */
75 };
76
77 static int
78 ptile_3way (const void *_p1, const void *_p2)
79 {
80   const struct percentile *p1 = _p1;
81   const struct percentile *p2 = _p2;
82
83   if (p1->p < p2->p)
84     return -1;
85
86   if (p1->p == p2->p)
87     {
88       if (p1->show > p2->show)
89         return -1;
90
91       return (p1->show < p2->show);
92     }
93
94   return (p1->p > p2->p);
95 }
96
97
98 enum
99   {
100     FRQ_NONORMAL,
101     FRQ_NORMAL
102   };
103
104 enum
105   {
106     FRQ_FREQ,
107     FRQ_PERCENT
108   };
109
110 enum sortprops 
111   {
112     FRQ_AFREQ,
113     FRQ_DFREQ,
114     FRQ_AVALUE,
115     FRQ_DVALUE
116   };
117
118 /* Array indices for STATISTICS subcommand. */
119 enum
120   {
121     FRQ_ST_MEAN,
122     FRQ_ST_SEMEAN,
123     FRQ_ST_MEDIAN,
124     FRQ_ST_MODE,
125     FRQ_ST_STDDEV,
126     FRQ_ST_VARIANCE,
127     FRQ_ST_KURTOSIS,
128     FRQ_ST_SEKURTOSIS,
129     FRQ_ST_SKEWNESS,
130     FRQ_ST_SESKEWNESS,
131     FRQ_ST_RANGE,
132     FRQ_ST_MINIMUM,
133     FRQ_ST_MAXIMUM,
134     FRQ_ST_SUM,
135     FRQ_ST_count
136   };
137
138 /* Description of statistics. */
139 static const char *st_name[FRQ_ST_count] =
140 {
141    N_("Mean"),
142    N_("S.E. Mean"),
143    N_("Median"),
144    N_("Mode"),
145    N_("Std Dev"),
146    N_("Variance"),
147    N_("Kurtosis"),
148    N_("S.E. Kurt"),
149    N_("Skewness"),
150    N_("S.E. Skew"),
151    N_("Range"),
152    N_("Minimum"),
153    N_("Maximum"),
154    N_("Sum")
155 };
156
157 struct freq_tab
158   {
159     struct hmap data;           /* Hash table for accumulating counts. */
160     struct freq *valid;         /* Valid freqs. */
161     int n_valid;                /* Number of total freqs. */
162     const struct dictionary *dict; /* Source of entries in the table. */
163
164     struct freq *missing;       /* Missing freqs. */
165     int n_missing;              /* Number of missing freqs. */
166
167     /* Statistics. */
168     double total_cases;         /* Sum of weights of all cases. */
169     double valid_cases;         /* Sum of weights of valid cases. */
170   };
171
172 struct frq_chart
173   {
174     double x_min;               /* X axis minimum value. */
175     double x_max;               /* X axis maximum value. */
176     int y_scale;                /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
177
178     /* Histograms only. */
179     double y_max;               /* Y axis maximum value. */
180     bool draw_normal;           /* Whether to draw normal curve. */
181
182     /* Pie charts only. */
183     bool include_missing;       /* Whether to include missing values. */
184   };
185
186 /* Per-variable frequency data. */
187 struct var_freqs
188   {
189     const struct variable *var;
190
191     /* Freqency table. */
192     struct freq_tab tab;        /* Frequencies table to use. */
193
194     /* Percentiles. */
195     int n_groups;               /* Number of groups. */
196     double *groups;             /* Groups. */
197
198     /* Statistics. */
199     double stat[FRQ_ST_count];
200
201     /* Variable attributes. */
202     int width;
203   };
204
205 struct frq_proc
206   {
207     struct pool *pool;
208
209     struct var_freqs *vars;
210     size_t n_vars;
211
212     /* Percentiles to calculate and possibly display. */
213     struct percentile *percentiles;
214     int n_percentiles, n_show_percentiles;
215
216     /* Frequency table display. */
217     int max_categories;         /* Maximum categories to show. */
218     int sort;                   /* FRQ_AVALUE or FRQ_DVALUE
219                                    or FRQ_AFREQ or FRQ_DFREQ. */
220
221     /* Statistics; number of statistics. */
222     unsigned long stats;
223     int n_stats;
224
225     /* Histogram and pie chart settings. */
226     struct frq_chart *hist, *pie, *bar;
227   };
228
229
230 struct freq_compare_aux
231   {
232     bool by_freq;
233     bool ascending_freq;
234
235     int width;
236     bool ascending_value;
237   };
238
239 static void calc_stats (const struct var_freqs *vf, double d[FRQ_ST_count]);
240
241 static void do_piechart(const struct frq_chart *pie, 
242                         const struct variable *var,
243                         const struct freq_tab *frq_tab);
244
245 static void do_barchart(const struct frq_chart *bar,
246                         const struct variable **var,
247                         const struct freq_tab *frq_tab);
248
249 static void dump_statistics (const struct frq_proc *frq, 
250                              const struct var_freqs *vf,
251                              const struct variable *wv);
252
253 static int
254 compare_freq (const void *a_, const void *b_, const void *aux_)
255 {
256   const struct freq_compare_aux *aux = aux_;
257   const struct freq *a = a_;
258   const struct freq *b = b_;
259
260   if (aux->by_freq && a->count != b->count)
261     {
262       int cmp = a->count > b->count ? 1 : -1;
263       return aux->ascending_freq ? cmp : -cmp;
264     }
265   else
266     {
267       int cmp = value_compare_3way (a->values, b->values, aux->width);
268       return aux->ascending_value ? cmp : -cmp;
269     }
270 }
271
272 /* Create a gsl_histogram from a freq_tab */
273 static struct histogram *
274 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
275                   const struct variable *var);
276
277
278 /* Displays a full frequency table for variable V. */
279 static void
280 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
281 {
282   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
283   const struct freq_tab *ft = &vf->tab;
284   int n_categories;
285   struct freq *f;
286   struct tab_table *t;
287   int r, x;
288   double cum_total = 0.0;
289   double cum_freq = 0.0;
290
291   static const char *headings[] = {
292     N_("Value Label"),
293     N_("Value"),
294     N_("Frequency"),
295     N_("Percent"),
296     N_("Valid Percent"),
297     N_("Cum Percent")
298   };
299
300   n_categories = ft->n_valid + ft->n_missing;
301   t = tab_create (6, n_categories + 2);
302   tab_set_format (t, RC_WEIGHT, wfmt);
303   tab_headers (t, 0, 0, 1, 0);
304
305   for (x = 0; x < 6; x++)
306     tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
307
308   r = 1;
309   for (f = ft->valid; f < ft->missing; f++)
310     {
311       const char *label;
312       double percent, valid_percent;
313
314       cum_freq += f->count;
315
316       percent = f->count / ft->total_cases * 100.0;
317       valid_percent = f->count / ft->valid_cases * 100.0;
318       cum_total += valid_percent;
319
320       label = var_lookup_value_label (vf->var, f->values);
321       if (label != NULL)
322         tab_text (t, 0, r, TAB_LEFT, label);
323
324       tab_value (t, 1, r, TAB_NONE, f->values, vf->var, NULL);
325       tab_double (t, 2, r, TAB_NONE, f->count, NULL, RC_WEIGHT);
326       tab_double (t, 3, r, TAB_NONE, percent, NULL, RC_OTHER);
327       tab_double (t, 4, r, TAB_NONE, valid_percent, NULL, RC_OTHER);
328       tab_double (t, 5, r, TAB_NONE, cum_total, NULL, RC_OTHER);
329       r++;
330     }
331   for (; f < &ft->valid[n_categories]; f++)
332     {
333       const char *label;
334
335       cum_freq += f->count;
336
337       label = var_lookup_value_label (vf->var, f->values);
338       if (label != NULL)
339         tab_text (t, 0, r, TAB_LEFT, label);
340
341       tab_value (t, 1, r, TAB_NONE, f->values, vf->var, NULL);
342       tab_double (t, 2, r, TAB_NONE, f->count, NULL, RC_WEIGHT);
343       tab_double (t, 3, r, TAB_NONE,
344                   f->count / ft->total_cases * 100.0, NULL, RC_OTHER);
345       tab_text (t, 4, r, TAB_NONE, _("Missing"));
346       r++;
347     }
348
349   tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
350   tab_hline (t, TAL_2, 0, 5, 1);
351   tab_hline (t, TAL_2, 0, 5, r);
352   tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
353   tab_vline (t, TAL_0, 1, r, r);
354   tab_double (t, 2, r, TAB_NONE, cum_freq, NULL, RC_WEIGHT);
355   tab_double (t, 3, r, TAB_NONE, 100.0, &F_5_1, RC_OTHER);
356   tab_double (t, 4, r, TAB_NONE, 100.0, &F_5_1, RC_OTHER);
357
358   tab_title (t, "%s", var_to_string (vf->var));
359   tab_submit (t);
360 }
361 \f
362 /* Statistical display. */
363
364 static double
365 calc_percentile (double p, double valid_cases, double x1, double x2)
366 {
367   double s, dummy;
368
369   s = (settings_get_algorithm () != COMPATIBLE
370        ? modf ((valid_cases - 1) * p, &dummy)
371        : modf ((valid_cases + 1) * p - 1, &dummy));
372
373   return x1 + (x2 - x1) * s;
374 }
375
376 /* Calculates all of the percentiles for VF within FRQ. */
377 static void
378 calc_percentiles (const struct frq_proc *frq, const struct var_freqs *vf)
379 {
380   const struct freq_tab *ft = &vf->tab;
381   double W = ft->valid_cases;
382   const struct freq *f;
383   int percentile_idx = 0;
384   double  rank = 0;
385
386   for (f = ft->valid; f < ft->missing; f++)
387     {
388       rank += f->count;
389       for (; percentile_idx < frq->n_percentiles; percentile_idx++)
390         {
391           struct percentile *pc = &frq->percentiles[percentile_idx];
392           double tp;
393
394           tp = (settings_get_algorithm () == ENHANCED
395                 ? (W - 1) * pc->p
396                 : (W + 1) * pc->p - 1);
397
398           if (rank <= tp)
399             break;
400
401           if (tp + 1 < rank || f + 1 >= ft->missing)
402             pc->value = f->values[0].f;
403           else
404             pc->value = calc_percentile (pc->p, W, f->values[0].f, f[1].values[0].f);
405         }
406     }
407   for (; percentile_idx < frq->n_percentiles; percentile_idx++)
408     {
409       struct percentile *pc = &frq->percentiles[percentile_idx];
410       pc->value = ft->valid[ft->n_valid - 1].values[0].f;
411     }
412 }
413
414 /* Returns true iff the value in struct freq F is non-missing
415    for variable V. */
416 static bool
417 not_missing (const void *f_, const void *v_)
418 {
419   const struct freq *f = f_;
420   const struct variable *v = v_;
421
422   return !var_is_value_missing (v, f->values, MV_ANY);
423 }
424
425
426 /* Summarizes the frequency table data for variable V. */
427 static void
428 postprocess_freq_tab (const struct frq_proc *frq, struct var_freqs *vf)
429 {
430   struct freq_tab *ft = &vf->tab;
431   struct freq_compare_aux aux;
432   size_t count;
433   struct freq *freqs, *f;
434   size_t i;
435
436   /* Extract data from hash table. */
437   count = hmap_count (&ft->data);
438   freqs = freq_hmap_extract (&ft->data);
439
440   /* Put data into ft. */
441   ft->valid = freqs;
442   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, vf->var);
443   ft->missing = freqs + ft->n_valid;
444   ft->n_missing = count - ft->n_valid;
445
446   /* Sort data. */
447   aux.by_freq = frq->sort == FRQ_AFREQ || frq->sort == FRQ_DFREQ;
448   aux.ascending_freq = frq->sort != FRQ_DFREQ;
449   aux.width = vf->width;
450   aux.ascending_value = frq->sort != FRQ_DVALUE;
451   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare_freq, &aux);
452   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare_freq, &aux);
453
454   /* Summary statistics. */
455   ft->valid_cases = 0.0;
456   for(i = 0 ;  i < ft->n_valid ; ++i )
457     {
458       f = &ft->valid[i];
459       ft->valid_cases += f->count;
460
461     }
462
463   ft->total_cases = ft->valid_cases ;
464   for(i = 0 ;  i < ft->n_missing ; ++i )
465     {
466       f = &ft->missing[i];
467       ft->total_cases += f->count;
468     }
469
470 }
471
472 /* Frees the frequency table for variable V. */
473 static void
474 cleanup_freq_tab (struct var_freqs *vf)
475 {
476   free (vf->tab.valid);
477   freq_hmap_destroy (&vf->tab.data, vf->width);
478 }
479
480 /* Add data from case C to the frequency table. */
481 static void
482 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
483 {
484   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
485   size_t i;
486
487   for (i = 0; i < frq->n_vars; i++)
488     {
489       struct var_freqs *vf = &frq->vars[i];
490       const union value *value = case_data (c, vf->var);
491       size_t hash = value_hash (value, vf->width, 0);
492       struct freq *f;
493
494       f = freq_hmap_search (&vf->tab.data, value, vf->width, hash);
495       if (f == NULL)
496         f = freq_hmap_insert (&vf->tab.data, value, vf->width, hash);
497
498       f->count += weight;
499     }
500 }
501
502 /* Prepares each variable that is the target of FREQUENCIES by setting
503    up its hash table. */
504 static void
505 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
506 {
507   struct ccase *c;
508   size_t i;
509
510   c = casereader_peek (input, 0);
511   if (c != NULL)
512     {
513       output_split_file_values (ds, c);
514       case_unref (c);
515     }
516
517   for (i = 0; i < frq->n_vars; i++)
518     hmap_init (&frq->vars[i].tab.data);
519 }
520
521 /* Finishes up with the variables after frequencies have been
522    calculated.  Displays statistics, percentiles, ... */
523 static void
524 postcalc (struct frq_proc *frq, const struct dataset *ds)
525 {
526   const struct dictionary *dict = dataset_dict (ds);
527   const struct variable *wv = dict_get_weight (dict);
528   size_t i;
529
530   for (i = 0; i < frq->n_vars; i++)
531     {
532       struct var_freqs *vf = &frq->vars[i];
533
534       postprocess_freq_tab (frq, vf);
535
536       /* Frequencies tables. */
537       if (vf->tab.n_valid + vf->tab.n_missing <= frq->max_categories)
538         dump_freq_table (vf, wv);
539
540       calc_percentiles (frq, vf);
541
542       /* Statistics. */
543       if (frq->n_stats)
544         dump_statistics (frq, vf, wv);
545
546       if (frq->hist && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
547         {
548           double d[FRQ_ST_count];
549           struct histogram *histogram;
550
551           calc_stats (vf, d);
552
553           histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
554
555           if ( histogram)
556             {
557               chart_item_submit (histogram_chart_create (
558                                histogram->gsl_hist, var_to_string(vf->var),
559                                vf->tab.valid_cases,
560                                d[FRQ_ST_MEAN],
561                                d[FRQ_ST_STDDEV],
562                                frq->hist->draw_normal));
563
564               statistic_destroy (&histogram->parent);
565             }
566         }
567
568       if (frq->pie)
569         do_piechart(frq->pie, vf->var, &vf->tab);
570
571       if (frq->bar)
572         do_barchart(frq->bar, &vf->var, &vf->tab);
573
574       cleanup_freq_tab (vf);
575     }
576 }
577
578 int
579 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
580 {
581   int i;
582   struct frq_proc frq;
583   const struct variable **vars;
584
585   bool sbc_barchart = false;
586   bool sbc_piechart = false;
587   bool sbc_histogram = false;
588
589   double pie_min = -DBL_MAX;
590   double pie_max = DBL_MAX;
591   bool pie_missing = true;
592
593   double bar_min = -DBL_MAX;
594   double bar_max = DBL_MAX;
595   bool bar_freq = true;
596
597   double hi_min = -DBL_MAX;
598   double hi_max = DBL_MAX;
599   int hi_scale = FRQ_FREQ;
600   int hi_freq = INT_MIN;
601   int hi_pcnt = INT_MIN;
602   int hi_norm = FRQ_NONORMAL;
603
604   frq.pool = pool_create ();
605   frq.sort = FRQ_AVALUE;
606
607   frq.vars = NULL;
608   frq.n_vars = 0;
609   
610   frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
611     | BIT_INDEX (FRQ_ST_STDDEV) 
612     | BIT_INDEX (FRQ_ST_MINIMUM)
613     | BIT_INDEX (FRQ_ST_MAXIMUM);
614
615   frq.n_stats = 4;
616
617   frq.max_categories = INT_MAX;
618
619   frq.percentiles = NULL;
620   frq.n_percentiles = 0;
621   frq.n_show_percentiles = 0;
622
623   frq.hist = NULL;
624   frq.pie = NULL;
625   frq.bar = NULL;
626
627
628   /* Accept an optional, completely pointless "/VARIABLES=" */
629   lex_match (lexer, T_SLASH);
630   if (lex_match_id  (lexer, "VARIABLES"))
631     {
632       if (! lex_force_match (lexer, T_EQUALS) )
633         goto error;
634     }
635
636   if (!parse_variables_const (lexer, dataset_dict (ds),
637                               &vars,
638                               &frq.n_vars,
639                               PV_NO_DUPLICATE))
640     goto error;
641
642   frq.vars = xzalloc (frq.n_vars * sizeof (*frq.vars));
643   for (i = 0; i < frq.n_vars; ++i)
644     {
645       frq.vars[i].var = vars[i];
646       frq.vars[i].width = var_get_width (vars[i]);
647     }
648
649   while (lex_token (lexer) != T_ENDCMD)
650     {
651       lex_match (lexer, T_SLASH);
652
653       if (lex_match_id (lexer, "STATISTICS"))
654         {
655           frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
656             | BIT_INDEX (FRQ_ST_STDDEV) 
657             | BIT_INDEX (FRQ_ST_MINIMUM)
658             | BIT_INDEX (FRQ_ST_MAXIMUM);
659           
660           frq.n_stats = 4;
661
662           if (lex_match (lexer, T_EQUALS))
663             {
664               frq.n_stats = 0;
665               frq.stats = 0;
666             }
667
668           while (lex_token (lexer) != T_ENDCMD
669                  && lex_token (lexer) != T_SLASH)
670             {
671               if (lex_match_id (lexer, "DEFAULT"))
672                 {
673                   frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
674                     | BIT_INDEX (FRQ_ST_STDDEV) 
675                     | BIT_INDEX (FRQ_ST_MINIMUM)
676                     | BIT_INDEX (FRQ_ST_MAXIMUM);
677
678                   frq.n_stats = 4;
679                 }
680               else if (lex_match_id (lexer, "MEAN"))
681                 {
682                   frq.stats |= BIT_INDEX (FRQ_ST_MEAN);
683                   frq.n_stats++;
684                 }
685               else if (lex_match_id (lexer, "SEMEAN"))
686                 {
687                   frq.stats |= BIT_INDEX (FRQ_ST_SEMEAN);
688                   frq.n_stats++;
689                 }
690               else if (lex_match_id (lexer, "MEDIAN"))
691                 {
692                   frq.stats |= BIT_INDEX (FRQ_ST_MEDIAN);
693                   frq.n_stats++;
694                 }
695               else if (lex_match_id (lexer, "MODE"))
696                 {
697                   frq.stats |= BIT_INDEX (FRQ_ST_MODE);
698                   frq.n_stats++;
699                 }
700               else if (lex_match_id (lexer, "STDDEV"))
701                 {
702                   frq.stats |= BIT_INDEX (FRQ_ST_STDDEV);
703                   frq.n_stats++;
704                 }
705               else if (lex_match_id (lexer, "VARIANCE"))
706                 {
707                   frq.stats |= BIT_INDEX (FRQ_ST_MEAN);
708                   frq.n_stats++;
709                 }
710               else if (lex_match_id (lexer, "KURTOSIS"))
711                 {
712                   frq.stats |= BIT_INDEX (FRQ_ST_KURTOSIS);
713                   frq.n_stats++;
714                 }
715               else if (lex_match_id (lexer, "SKEWNESS"))
716                 {
717                   frq.stats |= BIT_INDEX (FRQ_ST_SKEWNESS);
718                   frq.n_stats++;
719                 }
720               else if (lex_match_id (lexer, "RANGE"))
721                 {
722                   frq.stats |= BIT_INDEX (FRQ_ST_RANGE);
723                   frq.n_stats++;
724                 }
725               else if (lex_match_id (lexer, "MINIMUM"))
726                 {
727                   frq.stats |= BIT_INDEX (FRQ_ST_MINIMUM);
728                   frq.n_stats++;
729                 }
730               else if (lex_match_id (lexer, "MAXIMUM"))
731                 {
732                   frq.stats |= BIT_INDEX (FRQ_ST_MAXIMUM);
733                   frq.n_stats++;
734                 }
735               else if (lex_match_id (lexer, "SUM"))
736                 {
737                   frq.stats |= BIT_INDEX (FRQ_ST_SUM);
738                   frq.n_stats++;
739                 }
740               else if (lex_match_id (lexer, "SESKEWNESS"))
741                 {
742                   frq.stats |= BIT_INDEX (FRQ_ST_SESKEWNESS);
743                   frq.n_stats++;
744                 }
745               else if (lex_match_id (lexer, "SEKURTOSIS"))
746                 {
747                   frq.stats |= BIT_INDEX (FRQ_ST_SEKURTOSIS);
748                   frq.n_stats++;
749                 }
750               else if (lex_match_id (lexer, "NONE"))
751                 {
752                   frq.stats = 0;
753                   frq.n_stats = 0;
754                 }
755               else if (lex_match (lexer, T_ALL))
756                 {
757                   frq.stats = ~0;
758                   frq.n_stats = FRQ_ST_count;
759                 }
760               else
761                 {
762                   lex_error (lexer, NULL);
763                   goto error;
764                 }
765             }
766         }
767       else if (lex_match_id (lexer, "PERCENTILES"))
768         {
769           lex_match (lexer, T_EQUALS);
770           while (lex_token (lexer) != T_ENDCMD
771                  && lex_token (lexer) != T_SLASH)
772             {
773               if (lex_force_num (lexer))
774                 {
775                   frq.percentiles =
776                     xrealloc (frq.percentiles, 
777                               (frq.n_percentiles + 1)
778                               * sizeof (*frq.percentiles));
779                   frq.percentiles[frq.n_percentiles].p = lex_number (lexer)  / 100.0;
780                   frq.percentiles[frq.n_percentiles].show = true;
781                   lex_get (lexer);
782                   frq.n_percentiles++;
783                   frq.n_show_percentiles++;
784                 }
785               else
786                 {
787                   lex_error (lexer, NULL);
788                   goto error;
789                 }
790               lex_match (lexer, T_COMMA);
791             }
792         }
793       else if (lex_match_id (lexer, "FORMAT"))
794         {
795           lex_match (lexer, T_EQUALS);
796           while (lex_token (lexer) != T_ENDCMD
797                  && lex_token (lexer) != T_SLASH)
798             {
799               if (lex_match_id (lexer, "TABLE"))
800                 {
801                 }
802               else if (lex_match_id (lexer, "NOTABLE"))
803                 {
804                   frq.max_categories = 0;
805                 }
806               else if (lex_match_id (lexer, "AVALUE"))
807                 {
808                   frq.sort = FRQ_AVALUE;
809                 }
810               else if (lex_match_id (lexer, "DVALUE"))
811                 {
812                   frq.sort = FRQ_DVALUE;
813                 }
814               else if (lex_match_id (lexer, "AFREQ"))
815                 {
816                   frq.sort = FRQ_AFREQ;
817                 }
818               else if (lex_match_id (lexer, "DFREQ"))
819                 {
820                   frq.sort = FRQ_DFREQ;
821                 }
822               else
823                 {
824                   lex_error (lexer, NULL);
825                   goto error;
826                 }
827             }
828         }
829       else if (lex_match_id (lexer, "NTILES"))
830         {
831           lex_match (lexer, T_EQUALS);
832
833           if (lex_force_int (lexer))
834             {
835               int i;
836               int n = lex_integer (lexer);
837               lex_get (lexer);
838               for (i = 0; i < n + 1; ++i)
839                 {
840                   frq.percentiles =
841                     xrealloc (frq.percentiles, 
842                               (frq.n_percentiles + 1)
843                               * sizeof (*frq.percentiles));
844                   frq.percentiles[frq.n_percentiles].p =
845                     i / (double) n ;
846                   frq.percentiles[frq.n_percentiles].show = true;
847
848                   frq.n_percentiles++;
849                   frq.n_show_percentiles++;
850                 }
851             }
852           else
853             {
854               lex_error (lexer, NULL);
855               goto error;
856             }
857         }
858       else if (lex_match_id (lexer, "ALGORITHM"))
859         {
860           lex_match (lexer, T_EQUALS);
861
862           if (lex_match_id (lexer, "COMPATIBLE"))
863             {
864               settings_set_cmd_algorithm (COMPATIBLE);
865             }
866           else if (lex_match_id (lexer, "ENHANCED"))
867             {
868               settings_set_cmd_algorithm (ENHANCED);
869             }
870           else
871             {
872               lex_error (lexer, NULL);
873               goto error;
874             }
875         }
876       else if (lex_match_id (lexer, "HISTOGRAM"))
877         {
878           lex_match (lexer, T_EQUALS);
879           sbc_histogram = true;
880
881           while (lex_token (lexer) != T_ENDCMD
882                  && lex_token (lexer) != T_SLASH)
883             {
884               if (lex_match_id (lexer, "NORMAL"))
885                 {
886                   hi_norm = FRQ_NORMAL;
887                 }
888               else if (lex_match_id (lexer, "NONORMAL"))
889                 {
890                   hi_norm = FRQ_NONORMAL;
891                 }
892               else if (lex_match_id (lexer, "FREQ"))
893                 {
894                   hi_scale = FRQ_FREQ;
895                   if (lex_match (lexer, T_LPAREN))
896                     {
897                       if (lex_force_int (lexer))
898                         {
899                           hi_freq = lex_integer (lexer);
900                           if (hi_freq <= 0)
901                             {
902                               lex_error (lexer, _("Histogram frequency must be greater than zero."));
903                             }
904                           lex_get (lexer);
905                           lex_force_match (lexer, T_RPAREN);
906                         }
907                     }
908                 }
909               else if (lex_match_id (lexer, "PERCENT"))
910                 {
911                   hi_scale = FRQ_PERCENT;
912                   if (lex_match (lexer, T_LPAREN))
913                     {
914                       if (lex_force_int (lexer))
915                         {
916                           hi_pcnt = lex_integer (lexer);
917                           if (hi_pcnt <= 0)
918                             {
919                               lex_error (lexer, _("Histogram percentage must be greater than zero."));
920                             }
921                           lex_get (lexer);
922                           lex_force_match (lexer, T_RPAREN);
923                         }
924                     }
925                 }
926               else if (lex_match_id (lexer, "MINIMUM"))
927                 {
928                   lex_force_match (lexer, T_LPAREN);
929                   if (lex_force_num (lexer))
930                     {
931                       hi_min = lex_number (lexer);
932                       lex_get (lexer);
933                     }
934                   lex_force_match (lexer, T_RPAREN);
935                 }
936               else if (lex_match_id (lexer, "MAXIMUM"))
937                 {
938                   lex_force_match (lexer, T_LPAREN);
939                   if (lex_force_num (lexer))
940                     {
941                       hi_max = lex_number (lexer);
942                       lex_get (lexer);
943                     }
944                   lex_force_match (lexer, T_RPAREN);
945                 }
946               else
947                 {
948                   lex_error (lexer, NULL);
949                   goto error;
950                 }
951             }
952         }
953       else if (lex_match_id (lexer, "PIECHART"))
954         {
955           lex_match (lexer, T_EQUALS);
956           while (lex_token (lexer) != T_ENDCMD
957                  && lex_token (lexer) != T_SLASH)
958             {
959               if (lex_match_id (lexer, "MINIMUM"))
960                 {
961                   lex_force_match (lexer, T_LPAREN);
962                   if (lex_force_num (lexer))
963                     {
964                       pie_min = lex_number (lexer);
965                       lex_get (lexer);
966                     }
967                   lex_force_match (lexer, T_RPAREN);
968                 }
969               else if (lex_match_id (lexer, "MAXIMUM"))
970                 {
971                   lex_force_match (lexer, T_LPAREN);
972                   if (lex_force_num (lexer))
973                     {
974                       pie_max = lex_number (lexer);
975                       lex_get (lexer);
976                     }
977                   lex_force_match (lexer, T_RPAREN);
978                 }
979               else if (lex_match_id (lexer, "MISSING"))
980                 {
981                   pie_missing = true;
982                 }
983               else if (lex_match_id (lexer, "NOMISSING"))
984                 {
985                   pie_missing = false;
986                 }
987               else
988                 {
989                   lex_error (lexer, NULL);
990                   goto error;
991                 }
992             }
993           sbc_piechart = true;
994         }
995       else if (lex_match_id (lexer, "BARCHART"))
996         {
997           lex_match (lexer, T_EQUALS);
998           while (lex_token (lexer) != T_ENDCMD
999                  && lex_token (lexer) != T_SLASH)
1000             {
1001               if (lex_match_id (lexer, "MINIMUM"))
1002                 {
1003                   lex_force_match (lexer, T_LPAREN);
1004                   if (lex_force_num (lexer))
1005                     {
1006                       bar_min = lex_number (lexer);
1007                       lex_get (lexer);
1008                     }
1009                   lex_force_match (lexer, T_RPAREN);
1010                 }
1011               else if (lex_match_id (lexer, "MAXIMUM"))
1012                 {
1013                   lex_force_match (lexer, T_LPAREN);
1014                   if (lex_force_num (lexer))
1015                     {
1016                       bar_max = lex_number (lexer);
1017                       lex_get (lexer);
1018                     }
1019                   lex_force_match (lexer, T_RPAREN);
1020                 }
1021               else if (lex_match_id (lexer, "FREQ"))
1022                 {
1023                   if ( lex_match (lexer, T_LPAREN))
1024                     {
1025                       if (lex_force_num (lexer))
1026                         {
1027                           lex_number (lexer);
1028                           lex_get (lexer);
1029                         }
1030                       lex_force_match (lexer, T_RPAREN);
1031                     }
1032                   bar_freq = true;
1033                 }
1034               else if (lex_match_id (lexer, "PERCENT"))
1035                 {
1036                   if ( lex_match (lexer, T_LPAREN))
1037                     {
1038                       if (lex_force_num (lexer))
1039                         {
1040                           lex_number (lexer);
1041                           lex_get (lexer);
1042                         }
1043                       lex_force_match (lexer, T_RPAREN);
1044                     }
1045                   bar_freq = false;
1046                 }
1047               else
1048                 {
1049                   lex_error (lexer, NULL);
1050                   goto error;
1051                 }
1052             }
1053           sbc_barchart = true;
1054         }
1055       else if (lex_match_id (lexer, "MISSING"))
1056         {
1057           lex_match (lexer, T_EQUALS);
1058
1059           while (lex_token (lexer) != T_ENDCMD
1060                  && lex_token (lexer) != T_SLASH)
1061             {
1062               if (lex_match_id (lexer, "EXCLUDE"))
1063                 {
1064                 }
1065               else if (lex_match_id (lexer, "INCLUDE"))
1066                 {
1067                 }
1068               else
1069                 {
1070                   lex_error (lexer, NULL);
1071                   goto error;
1072                 }
1073             }
1074         }
1075       else
1076         {
1077           lex_error (lexer, NULL);
1078           goto error;
1079         }
1080     }
1081
1082   if (frq.stats & BIT_INDEX (FRQ_ST_MEDIAN))
1083     {
1084         frq.percentiles =
1085           xrealloc (frq.percentiles, 
1086                     (frq.n_percentiles + 1)
1087                     * sizeof (*frq.percentiles));
1088         
1089         frq.percentiles[frq.n_percentiles].p = 0.50;
1090         frq.percentiles[frq.n_percentiles].show = true;
1091
1092         frq.n_percentiles++;
1093     }
1094
1095
1096 /* Figure out which charts the user requested.  */
1097
1098   {
1099     if (sbc_histogram)
1100       {
1101         struct frq_chart *hist;
1102
1103         hist = frq.hist = xmalloc (sizeof *frq.hist);
1104         hist->x_min = hi_min;
1105         hist->x_max = hi_max;
1106         hist->y_scale = hi_scale;
1107         hist->y_max = hi_scale == FRQ_FREQ ? hi_freq : hi_pcnt;
1108         hist->draw_normal = hi_norm != FRQ_NONORMAL;
1109         hist->include_missing = false;
1110
1111         if (hist->x_min != SYSMIS && hist->x_max != SYSMIS
1112             && hist->x_min >= hist->x_max)
1113           {
1114             msg (SE, _("%s for histogram must be greater than or equal to %s, "
1115                        "but %s was specified as %.15g and %s as %.15g.  "
1116                        "%s and %s will be ignored."),
1117                  "MAX", "MIN", 
1118                  "MIN", hist->x_min, 
1119                  "MAX", hist->x_max,
1120                  "MIN", "MAX");
1121             hist->x_min = hist->x_max = SYSMIS;
1122           }
1123
1124         frq.percentiles =
1125           xrealloc (frq.percentiles, 
1126                     (frq.n_percentiles + 2)
1127                     * sizeof (*frq.percentiles));
1128         
1129         frq.percentiles[frq.n_percentiles].p = 0.25;
1130         frq.percentiles[frq.n_percentiles].show = false;
1131
1132         frq.percentiles[frq.n_percentiles + 1].p = 0.75;
1133         frq.percentiles[frq.n_percentiles + 1].show = false;
1134         
1135         frq.n_percentiles+=2;
1136       }
1137
1138     if (sbc_barchart)
1139       {
1140         frq.bar = xmalloc (sizeof *frq.bar);
1141         frq.bar->x_min = bar_min;
1142         frq.bar->x_max = bar_max;
1143         frq.bar->include_missing = false;
1144         frq.bar->y_scale = bar_freq ? FRQ_FREQ : FRQ_PERCENT;
1145       }
1146
1147     if (sbc_piechart)
1148       {
1149         struct frq_chart *pie;
1150
1151         pie = frq.pie = xmalloc (sizeof *frq.pie);
1152         pie->x_min = pie_min;
1153         pie->x_max = pie_max;
1154         pie->include_missing = pie_missing;
1155
1156         if (pie->x_min != SYSMIS && pie->x_max != SYSMIS
1157             && pie->x_min >= pie->x_max)
1158           {
1159             msg (SE, _("%s for pie chart must be greater than or equal to %s, "
1160                        "but %s was specified as %.15g and %s as %.15g.  "
1161                        "%s and %s will be ignored."), 
1162                  "MAX", "MIN", 
1163                  "MIN", pie->x_min,
1164                  "MAX", pie->x_max,
1165                  "MIN", "MAX");
1166             pie->x_min = pie->x_max = SYSMIS;
1167           }
1168       }
1169   }
1170
1171   {
1172     int i,o;
1173     double previous_p = -1;
1174     qsort (frq.percentiles, frq.n_percentiles,
1175            sizeof (*frq.percentiles), 
1176            ptile_3way);
1177
1178     frq.n_show_percentiles = 0;
1179     for (i = o = 0; i < frq.n_percentiles; ++i)
1180       {
1181         frq.percentiles[o].p = frq.percentiles[i].p;
1182
1183         if (frq.percentiles[i].show)
1184           frq.percentiles[o].show = true;
1185
1186         if (frq.percentiles[i].p != previous_p)
1187           {
1188             if (frq.percentiles[i].show)
1189               frq.n_show_percentiles++;
1190
1191             o++;
1192           }
1193
1194         previous_p = frq.percentiles[i].p;
1195       }
1196
1197     frq.n_percentiles = o;
1198   }
1199
1200   {
1201     struct casegrouper *grouper;
1202     struct casereader *group;
1203     bool ok;
1204
1205     grouper = casegrouper_create_splits (proc_open (ds), dataset_dict (ds));
1206     while (casegrouper_get_next_group (grouper, &group))
1207       {
1208         struct ccase *c;
1209         precalc (&frq, group, ds);
1210         for (; (c = casereader_read (group)) != NULL; case_unref (c))
1211           calc (&frq, c, ds);
1212         postcalc (&frq, ds);
1213       }
1214     ok = casegrouper_destroy (grouper);
1215     ok = proc_commit (ds) && ok;
1216   }
1217
1218
1219   return CMD_SUCCESS;
1220
1221  error:
1222
1223   return CMD_FAILURE;
1224 }
1225
1226 static double
1227 calculate_iqr (const struct frq_proc *frq)
1228 {
1229   double q1 = SYSMIS;
1230   double q3 = SYSMIS;
1231   int i;
1232
1233   /* This cannot work unless the 25th and 75th percentile are calculated */
1234   assert (frq->n_percentiles >= 2);
1235   for (i = 0; i < frq->n_percentiles; i++)
1236     {
1237       struct percentile *pc = &frq->percentiles[i];
1238
1239       if (fabs (0.25 - pc->p) < DBL_EPSILON)
1240         q1 = pc->value;
1241       else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1242         q3 = pc->value;
1243     }
1244
1245   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1246 }
1247
1248 static bool
1249 chart_includes_value (const struct frq_chart *chart,
1250                       const struct variable *var,
1251                       const union value *value)
1252 {
1253   if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1254     return false;
1255
1256   if (var_is_numeric (var)
1257       && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1258           || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1259     return false;
1260
1261   return true;
1262 }
1263
1264 /* Create a gsl_histogram from a freq_tab */
1265 static struct histogram *
1266 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1267                   const struct variable *var)
1268 {
1269   double x_min, x_max, valid_freq;
1270   int i;
1271   double bin_width;
1272   struct histogram *histogram;
1273   double iqr;
1274
1275   /* Find out the extremes of the x value, within the range to be included in
1276      the histogram, and sum the total frequency of those values. */
1277   x_min = DBL_MAX;
1278   x_max = -DBL_MAX;
1279   valid_freq = 0;
1280   for (i = 0; i < ft->n_valid; i++)
1281     {
1282       const struct freq *f = &ft->valid[i];
1283       if (chart_includes_value (frq->hist, var, f->values))
1284         {
1285           x_min = MIN (x_min, f->values[0].f);
1286           x_max = MAX (x_max, f->values[0].f);
1287           valid_freq += f->count;
1288         }
1289     }
1290
1291
1292   iqr = calculate_iqr (frq);
1293
1294   if (iqr > 0)
1295     /* Freedman-Diaconis' choice of bin width. */
1296     bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1297
1298   else
1299     /* Sturges Rule */
1300     bin_width = (x_max - x_min) / (1 + log2 (valid_freq));
1301
1302   histogram = histogram_create (bin_width, x_min, x_max);
1303
1304   if ( histogram == NULL)
1305     return NULL;
1306
1307   for (i = 0; i < ft->n_valid; i++)
1308     {
1309       const struct freq *f = &ft->valid[i];
1310       if (chart_includes_value (frq->hist, var, f->values))
1311         histogram_add (histogram, f->values[0].f, f->count);
1312     }
1313
1314   return histogram;
1315 }
1316
1317
1318 /* Allocate an array of struct freqs and fill them from the data in FRQ_TAB,
1319    according to the parameters of CATCHART
1320    N_SLICES will contain the number of slices allocated.
1321    The caller is responsible for freeing slices
1322 */
1323 static struct freq *
1324 pick_cat_counts (const struct frq_chart *catchart,
1325                  const struct freq_tab *frq_tab,
1326                  int *n_slicesp)
1327 {
1328   int n_slices = 0;
1329   int i;
1330   struct freq *slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1331   
1332   for (i = 0; i < frq_tab->n_valid; i++)
1333     {
1334       const struct freq *f = &frq_tab->valid[i];
1335       if (f->count > catchart->x_max)
1336         continue;
1337
1338       if (f->count < catchart->x_min)
1339         continue;
1340       
1341       slices[n_slices] = *f;
1342       
1343       n_slices++;
1344     }
1345
1346   if (catchart->include_missing)
1347     {
1348       for (i = 0; i < frq_tab->n_missing; i++)
1349         {
1350           const struct freq *f = &frq_tab->missing[i];
1351           slices[n_slices].count += f->count;
1352           
1353           if (i == 0)
1354             slices[n_slices].values[0] = f->values[0];
1355         }
1356       
1357       if (frq_tab->n_missing > 0)
1358         n_slices++;
1359     }
1360
1361   *n_slicesp = n_slices;
1362   return slices;
1363 }
1364
1365
1366 /* Allocate an array of struct freqs and fill them from the data in FRQ_TAB,
1367    according to the parameters of CATCHART
1368    N_SLICES will contain the number of slices allocated.
1369    The caller is responsible for freeing slices
1370 */
1371 static struct freq **
1372 pick_cat_counts_ptr (const struct frq_chart *catchart,
1373                      const struct freq_tab *frq_tab,
1374                      int *n_slicesp)
1375 {
1376   int n_slices = 0;
1377   int i;
1378   struct freq **slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1379   
1380   for (i = 0; i < frq_tab->n_valid; i++)
1381     {
1382       struct freq *f = &frq_tab->valid[i];
1383       if (f->count > catchart->x_max)
1384         continue;
1385
1386       if (f->count < catchart->x_min)
1387         continue;
1388       
1389       slices[n_slices] = f;
1390       
1391       n_slices++;
1392     }
1393
1394   if (catchart->include_missing)
1395     {
1396       for (i = 0; i < frq_tab->n_missing; i++)
1397         {
1398           const struct freq *f = &frq_tab->missing[i];
1399           if (i == 0)
1400             {
1401               slices[n_slices] = xmalloc (sizeof (struct freq));
1402               slices[n_slices]->values[0] = f->values[0];
1403             }
1404
1405           slices[n_slices]->count += f->count;
1406           
1407         }
1408     }
1409
1410   *n_slicesp = n_slices;
1411   return slices;
1412 }
1413
1414
1415
1416 static void
1417 do_piechart(const struct frq_chart *pie, const struct variable *var,
1418             const struct freq_tab *frq_tab)
1419 {
1420   int n_slices;
1421   struct freq *slices = pick_cat_counts (pie, frq_tab, &n_slices);
1422
1423   if (n_slices < 2)
1424     msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1425          var_get_name (var), n_slices);
1426   else if (n_slices > 50)
1427     msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1428          var_get_name (var));
1429   else
1430     chart_item_submit (piechart_create (var, slices, n_slices));
1431
1432   free (slices);
1433 }
1434
1435
1436 static void
1437 do_barchart(const struct frq_chart *bar, const struct variable **var,
1438             const struct freq_tab *frq_tab)
1439 {
1440   int n_slices;
1441   struct freq **slices = pick_cat_counts_ptr (bar, frq_tab, &n_slices);
1442
1443   chart_item_submit (barchart_create (var, 1,
1444                                       (bar->y_scale == FRQ_FREQ) ? _("Count") : _("Percent"),
1445                                       slices, n_slices));
1446   free (slices);
1447 }
1448
1449
1450 /* Calculates all the pertinent statistics for VF, putting them in array
1451    D[]. */
1452 static void
1453 calc_stats (const struct var_freqs *vf, double d[FRQ_ST_count])
1454 {
1455   const struct freq_tab *ft = &vf->tab;
1456   double W = ft->valid_cases;
1457   const struct freq *f;
1458   struct moments *m;
1459   int most_often = -1;
1460   double X_mode = SYSMIS;
1461
1462   /* Calculate the mode. */
1463   for (f = ft->valid; f < ft->missing; f++)
1464     {
1465       if (most_often < f->count)
1466         {
1467           most_often = f->count;
1468           X_mode = f->values[0].f;
1469         }
1470       else if (most_often == f->count)
1471         {
1472           /* A duplicate mode is undefined.
1473              FIXME: keep track of *all* the modes. */
1474           X_mode = SYSMIS;
1475         }
1476     }
1477
1478   /* Calculate moments. */
1479   m = moments_create (MOMENT_KURTOSIS);
1480   for (f = ft->valid; f < ft->missing; f++)
1481     moments_pass_one (m, f->values[0].f, f->count);
1482   for (f = ft->valid; f < ft->missing; f++)
1483     moments_pass_two (m, f->values[0].f, f->count);
1484   moments_calculate (m, NULL, &d[FRQ_ST_MEAN], &d[FRQ_ST_VARIANCE],
1485                      &d[FRQ_ST_SKEWNESS], &d[FRQ_ST_KURTOSIS]);
1486   moments_destroy (m);
1487
1488   /* Formulae below are taken from _SPSS Statistical Algorithms_. */
1489   d[FRQ_ST_MINIMUM] = ft->valid[0].values[0].f;
1490   d[FRQ_ST_MAXIMUM] = ft->valid[ft->n_valid - 1].values[0].f;
1491   d[FRQ_ST_MODE] = X_mode;
1492   d[FRQ_ST_RANGE] = d[FRQ_ST_MAXIMUM] - d[FRQ_ST_MINIMUM];
1493   d[FRQ_ST_SUM] = d[FRQ_ST_MEAN] * W;
1494   d[FRQ_ST_STDDEV] = sqrt (d[FRQ_ST_VARIANCE]);
1495   d[FRQ_ST_SEMEAN] = d[FRQ_ST_STDDEV] / sqrt (W);
1496   d[FRQ_ST_SESKEWNESS] = calc_seskew (W);
1497   d[FRQ_ST_SEKURTOSIS] = calc_sekurt (W);
1498 }
1499
1500 /* Displays a table of all the statistics requested for variable V. */
1501 static void
1502 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
1503                  const struct variable *wv)
1504 {
1505   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1506   const struct freq_tab *ft = &vf->tab;
1507   double stat_value[FRQ_ST_count];
1508   struct tab_table *t;
1509   int i, r = 2; /* N missing and N valid are always dumped */
1510
1511   if (var_is_alpha (vf->var))
1512     return;
1513
1514   calc_stats (vf, stat_value);
1515
1516   t = tab_create (3, ((frq->stats & BIT_INDEX (FRQ_ST_MEDIAN)) ? frq->n_stats - 1 : frq->n_stats)
1517                                 + frq->n_show_percentiles + 2);
1518
1519   tab_set_format (t, RC_WEIGHT, wfmt);
1520   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1521
1522   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1523   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1524
1525   for (i = 0; i < FRQ_ST_count; i++)
1526     {
1527       if (FRQ_ST_MEDIAN == i)
1528         continue;
1529
1530       if (frq->stats & BIT_INDEX (i))
1531       {
1532         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1533                       gettext (st_name[i]));
1534
1535         if (vf->tab.n_valid <= 0 && r >= 2)
1536           tab_text (t, 2, r, 0,   ".");
1537         else
1538           tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL, RC_OTHER);
1539         r++;
1540       }
1541     }
1542
1543   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1544   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1545   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1546
1547   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, NULL, RC_WEIGHT);
1548   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, NULL, RC_WEIGHT);
1549
1550   for (i = 0; i < frq->n_percentiles; i++)
1551     {
1552       const struct percentile *pc = &frq->percentiles[i];
1553
1554       if (!pc->show)
1555         continue;
1556
1557       if ( i == 0 )
1558         {
1559           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1560         }
1561
1562       if (vf->tab.n_valid <= 0)
1563         {
1564           tab_text (t, 2, r, 0,   ".");
1565           ++r;
1566           continue;
1567         }
1568
1569       if (pc->p == 0.5)
1570         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1571       else
1572         tab_double (t, 1, r, TAB_LEFT, pc->p * 100, NULL, RC_INTEGER);
1573       tab_double (t, 2, r, TAB_NONE, pc->value,
1574                   var_get_print_format (vf->var), RC_OTHER);
1575
1576       ++r;
1577     }
1578
1579   tab_title (t, "%s", var_to_string (vf->var));
1580
1581   tab_submit (t);
1582 }
1583