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