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