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