Make the expression code a little nicer and fix bugs found
[pspp-builds.git] / src / matrix-data.c
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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include "error.h"
22 #include <stdlib.h>
23 #include <ctype.h>
24 #include <float.h>
25 #include "algorithm.h"
26 #include "alloc.h"
27 #include "command.h"
28 #include "data-in.h"
29 #include "dfm.h"
30 #include "error.h"
31 #include "file-handle.h"
32 #include "lexer.h"
33 #include "misc.h"
34 #include "pool.h"
35 #include "str.h"
36 #include "var.h"
37 #include "vfm.h"
38
39 #include "debug-print.h"
40
41 /* FIXME: /N subcommand not implemented.  It should be pretty simple,
42    too. */
43
44 /* Format type enums. */
45 enum format_type
46   {
47     LIST,
48     FREE
49   };
50
51 /* Matrix section enums. */
52 enum matrix_section
53   {
54     LOWER,
55     UPPER,
56     FULL
57   };
58
59 /* Diagonal inclusion enums. */
60 enum include_diagonal
61   {
62     DIAGONAL,
63     NODIAGONAL
64   };
65
66 /* CONTENTS types. */
67 enum content_type
68   {
69     N_VECTOR,
70     N_SCALAR,
71     N_MATRIX,
72     MEAN,
73     STDDEV,
74     COUNT,
75     MSE,
76     DFE,
77     MAT,
78     COV,
79     CORR,
80     PROX,
81     
82     LPAREN,
83     RPAREN,
84     EOC
85   };
86
87 /* 0=vector, 1=matrix, 2=scalar. */
88 static const int content_type[PROX + 1] = 
89   {
90     0, 2, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1,
91   };
92
93 /* Name of each content type. */
94 static const char *content_names[PROX + 1] =
95   {
96     "N", "N", "N_MATRIX", "MEAN", "STDDEV", "COUNT", "MSE",
97     "DFE", "MAT", "COV", "CORR", "PROX",
98   };
99
100 /* A MATRIX DATA input program. */
101 struct matrix_data_pgm 
102   {
103     struct pool *container;     /* Arena used for all allocations. */
104     struct file_handle *data_file; /* The data file to be read. */
105
106     /* Format. */
107     enum format_type fmt;       /* LIST or FREE. */
108     enum matrix_section section;/* LOWER or UPPER or FULL. */
109     enum include_diagonal diag; /* DIAGONAL or NODIAGONAL. */
110
111     int explicit_rowtype;       /* ROWTYPE_ specified explicitly in data? */
112     struct variable *rowtype_, *varname_; /* ROWTYPE_, VARNAME_ variables. */
113     
114     struct variable *single_split; /* Single SPLIT FILE variable. */
115
116     /* Factor variables.  */
117     int n_factors;              /* Number of factor variables. */
118     struct variable **factors;  /* Factor variables. */
119     int is_per_factor[PROX + 1]; /* Is there per-factor data? */
120
121     int cells;                  /* Number of cells, or -1 if none. */
122
123     int pop_n;                  /* Population N specified by user. */
124
125     /* CONTENTS subcommand. */
126     int contents[EOC * 3 + 1];  /* Contents. */
127     int n_contents;             /* Number of entries. */
128
129     /* Continuous variables. */
130     int n_continuous;           /* Number of continuous variables. */
131     int first_continuous;       /* Index into default_dict.var of
132                                    first continuous variable. */
133   };
134
135 static const struct case_source_class matrix_data_with_rowtype_source_class;
136 static const struct case_source_class matrix_data_without_rowtype_source_class;
137
138 static int compare_variables_by_mxd_vartype (const void *pa,
139                                              const void *pb);
140 static void read_matrices_without_rowtype (struct matrix_data_pgm *);
141 static void read_matrices_with_rowtype (struct matrix_data_pgm *);
142 static int string_to_content_type (char *, int *);
143
144 #if DEBUGGING
145 static void debug_print (void);
146 #endif
147
148 int
149 cmd_matrix_data (void)
150 {
151   struct pool *pool;
152   struct matrix_data_pgm *mx;
153   
154   unsigned seen = 0;
155   
156   discard_variables ();
157
158   pool = pool_create ();
159   mx = pool_alloc (pool, sizeof *mx);
160   mx->container = pool;
161   mx->data_file = inline_file;
162   mx->fmt = LIST;
163   mx->section = LOWER;
164   mx->diag = DIAGONAL;
165   mx->explicit_rowtype = 0;
166   mx->rowtype_ = NULL;
167   mx->varname_ = NULL;
168   mx->single_split = NULL;
169   mx->n_factors = 0;
170   mx->factors = NULL;
171   memset (mx->is_per_factor, 0, sizeof mx->is_per_factor);
172   mx->cells = -1;
173   mx->pop_n = -1;
174   mx->n_contents = 0;
175   mx->n_continuous = 0;
176   mx->first_continuous = 0;
177   while (token != '.')
178     {
179       lex_match ('/');
180
181       if (lex_match_id ("VARIABLES"))
182         {
183           char **v;
184           int nv;
185
186           if (seen & 1)
187             {
188               msg (SE, _("VARIABLES subcommand multiply specified."));
189               goto lossage;
190             }
191           seen |= 1;
192           
193           lex_match ('=');
194           if (!parse_DATA_LIST_vars (&v, &nv, PV_NO_DUPLICATE))
195             goto lossage;
196           
197           {
198             int i;
199
200             for (i = 0; i < nv; i++)
201               if (!strcmp (v[i], "VARNAME_"))
202                 {
203                   msg (SE, _("VARNAME_ cannot be explicitly specified on "
204                              "VARIABLES."));
205                   for (i = 0; i < nv; i++)
206                     free (v[i]);
207                   free (v);
208                   goto lossage;
209                 }
210           }
211           
212           {
213             int i;
214
215             for (i = 0; i < nv; i++)
216               {
217                 struct variable *new_var;
218                 
219                 if (strcmp (v[i], "ROWTYPE_"))
220                   {
221                     new_var = dict_create_var_assert (default_dict, v[i], 0);
222                     new_var->p.mxd.vartype = MXD_CONTINUOUS;
223                     new_var->p.mxd.subtype = i;
224                   }
225                 else
226                   mx->explicit_rowtype = 1;
227                 free (v[i]);
228               }
229             free (v);
230           }
231           
232           {
233             mx->rowtype_ = dict_create_var_assert (default_dict,
234                                                    "ROWTYPE_", 8);
235             mx->rowtype_->p.mxd.vartype = MXD_ROWTYPE;
236             mx->rowtype_->p.mxd.subtype = 0;
237           }
238         }
239       else if (lex_match_id ("FILE"))
240         {
241           lex_match ('=');
242           mx->data_file = fh_parse_file_handle ();
243           if (mx->data_file == NULL)
244             goto lossage;
245         }
246       else if (lex_match_id ("FORMAT"))
247         {
248           lex_match ('=');
249
250           while (token == T_ID)
251             {
252               if (lex_match_id ("LIST"))
253                 mx->fmt = LIST;
254               else if (lex_match_id ("FREE"))
255                 mx->fmt = FREE;
256               else if (lex_match_id ("LOWER"))
257                 mx->section = LOWER;
258               else if (lex_match_id ("UPPER"))
259                 mx->section = UPPER;
260               else if (lex_match_id ("FULL"))
261                 mx->section = FULL;
262               else if (lex_match_id ("DIAGONAL"))
263                 mx->diag = DIAGONAL;
264               else if (lex_match_id ("NODIAGONAL"))
265                 mx->diag = NODIAGONAL;
266               else 
267                 {
268                   lex_error (_("in FORMAT subcommand"));
269                   goto lossage;
270                 }
271             }
272         }
273       else if (lex_match_id ("SPLIT"))
274         {
275           lex_match ('=');
276
277           if (seen & 2)
278             {
279               msg (SE, _("SPLIT subcommand multiply specified."));
280               goto lossage;
281             }
282           seen |= 2;
283           
284           if (token != T_ID)
285             {
286               lex_error (_("in SPLIT subcommand"));
287               goto lossage;
288             }
289           
290           if (dict_lookup_var (default_dict, tokid) == NULL
291               && (lex_look_ahead () == '.' || lex_look_ahead () == '/'))
292             {
293               if (!strcmp (tokid, "ROWTYPE_") || !strcmp (tokid, "VARNAME_"))
294                 {
295                   msg (SE, _("Split variable may not be named ROWTYPE_ "
296                              "or VARNAME_."));
297                   goto lossage;
298                 }
299
300               mx->single_split = dict_create_var_assert (default_dict,
301                                                          tokid, 0);
302               lex_get ();
303
304               mx->single_split->p.mxd.vartype = MXD_CONTINUOUS;
305
306               dict_set_split_vars (default_dict, &mx->single_split, 1);
307             }
308           else
309             {
310               struct variable **split;
311               int n;
312
313               if (!parse_variables (default_dict, &split, &n, PV_NO_DUPLICATE))
314                 goto lossage;
315
316               dict_set_split_vars (default_dict, split, n);
317             }
318           
319           {
320             struct variable *const *split = dict_get_split_vars (default_dict);
321             size_t split_cnt = dict_get_split_cnt (default_dict);
322             int i;
323
324             for (i = 0; i < split_cnt; i++)
325               {
326                 if (split[i]->p.mxd.vartype != MXD_CONTINUOUS)
327                   {
328                     msg (SE, _("Split variable %s is already another type."),
329                          tokid);
330                     goto lossage;
331                   }
332                 split[i]->p.mxd.vartype = MXD_SPLIT;
333                 split[i]->p.mxd.subtype = i;
334               }
335           }
336         }
337       else if (lex_match_id ("FACTORS"))
338         {
339           lex_match ('=');
340           
341           if (seen & 4)
342             {
343               msg (SE, _("FACTORS subcommand multiply specified."));
344               goto lossage;
345             }
346           seen |= 4;
347
348           if (!parse_variables (default_dict, &mx->factors, &mx->n_factors, PV_NONE))
349             goto lossage;
350           
351           {
352             int i;
353             
354             for (i = 0; i < mx->n_factors; i++)
355               {
356                 if (mx->factors[i]->p.mxd.vartype != MXD_CONTINUOUS)
357                   {
358                     msg (SE, _("Factor variable %s is already another type."),
359                          tokid);
360                     goto lossage;
361                   }
362                 mx->factors[i]->p.mxd.vartype = MXD_FACTOR;
363                 mx->factors[i]->p.mxd.subtype = i;
364               }
365           }
366         }
367       else if (lex_match_id ("CELLS"))
368         {
369           lex_match ('=');
370           
371           if (mx->cells != -1)
372             {
373               msg (SE, _("CELLS subcommand multiply specified."));
374               goto lossage;
375             }
376
377           if (!lex_integer_p () || lex_integer () < 1)
378             {
379               lex_error (_("expecting positive integer"));
380               goto lossage;
381             }
382
383           mx->cells = lex_integer ();
384           lex_get ();
385         }
386       else if (lex_match_id ("N"))
387         {
388           lex_match ('=');
389
390           if (mx->pop_n != -1)
391             {
392               msg (SE, _("N subcommand multiply specified."));
393               goto lossage;
394             }
395
396           if (!lex_integer_p () || lex_integer () < 1)
397             {
398               lex_error (_("expecting positive integer"));
399               goto lossage;
400             }
401
402           mx->pop_n = lex_integer ();
403           lex_get ();
404         }
405       else if (lex_match_id ("CONTENTS"))
406         {
407           int inside_parens = 0;
408           unsigned collide = 0;
409           int item;
410           
411           if (seen & 8)
412             {
413               msg (SE, _("CONTENTS subcommand multiply specified."));
414               goto lossage;
415             }
416           seen |= 8;
417
418           lex_match ('=');
419           
420           {
421             int i;
422             
423             for (i = 0; i <= PROX; i++)
424               mx->is_per_factor[i] = 0;
425           }
426
427           for (;;)
428             {
429               if (lex_match ('('))
430                 {
431                   if (inside_parens)
432                     {
433                       msg (SE, _("Nested parentheses not allowed."));
434                       goto lossage;
435                     }
436                   inside_parens = 1;
437                   item = LPAREN;
438                 }
439               else if (lex_match (')'))
440                 {
441                   if (!inside_parens)
442                     {
443                       msg (SE, _("Mismatched right parenthesis (`(')."));
444                       goto lossage;
445                     }
446                   if (mx->contents[mx->n_contents - 1] == LPAREN)
447                     {
448                       msg (SE, _("Empty parentheses not allowed."));
449                       goto lossage;
450                     }
451                   inside_parens = 0;
452                   item = RPAREN;
453                 }
454               else 
455                 {
456                   int content_type;
457                   int collide_index;
458                   
459                   if (token != T_ID)
460                     {
461                       lex_error (_("in CONTENTS subcommand"));
462                       goto lossage;
463                     }
464
465                   content_type = string_to_content_type (tokid,
466                                                          &collide_index);
467                   if (content_type == -1)
468                     {
469                       lex_error (_("in CONTENTS subcommand"));
470                       goto lossage;
471                     }
472                   lex_get ();
473
474                   if (collide & (1 << collide_index))
475                     {
476                       msg (SE, _("Content multiply specified for %s."),
477                            content_names[content_type]);
478                       goto lossage;
479                     }
480                   collide |= (1 << collide_index);
481                   
482                   item = content_type;
483                   mx->is_per_factor[item] = inside_parens;
484                 }
485               mx->contents[mx->n_contents++] = item;
486
487               if (token == '/' || token == '.')
488                 break;
489             }
490
491           if (inside_parens)
492             {
493               msg (SE, _("Missing right parenthesis."));
494               goto lossage;
495             }
496           mx->contents[mx->n_contents] = EOC;
497         }
498       else 
499         {
500           lex_error (NULL);
501           goto lossage;
502         }
503     }
504   
505   if (token != '.')
506     {
507       lex_error (_("expecting end of command"));
508       goto lossage;
509     }
510   
511   if (!(seen & 1))
512     {
513       msg (SE, _("Missing VARIABLES subcommand."));
514       goto lossage;
515     }
516   
517   if (!mx->n_contents && !mx->explicit_rowtype)
518     {
519       msg (SW, _("CONTENTS subcommand not specified: assuming file "
520                  "contains only CORR matrix."));
521
522       mx->contents[0] = CORR;
523       mx->contents[1] = EOC;
524       mx->n_contents = 0;
525     }
526
527   if (mx->n_factors && !mx->explicit_rowtype && mx->cells == -1)
528     {
529       msg (SE, _("Missing CELLS subcommand.  CELLS is required "
530                  "when ROWTYPE_ is not given in the data and "
531                  "factors are present."));
532       goto lossage;
533     }
534
535   if (mx->explicit_rowtype && mx->single_split)
536     {
537       msg (SE, _("Split file values must be present in the data when "
538                  "ROWTYPE_ is present."));
539       goto lossage;
540     }
541       
542   /* Create VARNAME_. */
543   {
544     mx->varname_ = dict_create_var_assert (default_dict, "VARNAME_", 8);
545     mx->varname_->p.mxd.vartype = MXD_VARNAME;
546     mx->varname_->p.mxd.subtype = 0;
547   }
548   
549   /* Sort the dictionary variables into the desired order for the
550      system file output. */
551   {
552     struct variable **v;
553     size_t nv;
554
555     dict_get_vars (default_dict, &v, &nv, 0);
556     qsort (v, nv, sizeof *v, compare_variables_by_mxd_vartype);
557     dict_reorder_vars (default_dict, v, nv);
558     free (v);
559   }
560
561   /* Set formats. */
562   {
563     static const struct fmt_spec fmt_tab[MXD_COUNT] =
564       {
565         {FMT_F, 4, 0},
566         {FMT_A, 8, 0},
567         {FMT_F, 4, 0},
568         {FMT_A, 8, 0},
569         {FMT_F, 10, 4},
570       };
571     
572     int i;
573
574     mx->first_continuous = -1;
575     for (i = 0; i < dict_get_var_cnt (default_dict); i++)
576       {
577         struct variable *v = dict_get_var (default_dict, i);
578         int type = v->p.mxd.vartype;
579         
580         assert (type >= 0 && type < MXD_COUNT);
581         v->print = v->write = fmt_tab[type];
582
583         if (type == MXD_CONTINUOUS)
584           mx->n_continuous++;
585         if (mx->first_continuous == -1 && type == MXD_CONTINUOUS)
586           mx->first_continuous = i;
587       }
588   }
589
590   if (mx->n_continuous == 0)
591     {
592       msg (SE, _("No continuous variables specified."));
593       goto lossage;
594     }
595
596 #if DEBUGGING
597   debug_print ();
598 #endif
599
600   if (!dfm_open_for_reading (mx->data_file))
601     goto lossage;
602
603   if (mx->explicit_rowtype)
604     read_matrices_with_rowtype (mx);
605   else
606     read_matrices_without_rowtype (mx);
607
608   pool_destroy (mx->container);
609
610   return CMD_SUCCESS;
611
612 lossage:
613   discard_variables ();
614   free (mx->factors);
615   pool_destroy (mx->container);
616   return CMD_FAILURE;
617 }
618
619 /* Look up string S as a content-type name and return the
620    corresponding enumerated value, or -1 if there is no match.  If
621    COLLIDE is non-NULL then *COLLIDE returns a value (suitable for use
622    as a bit-index) which can be used for determining whether a related
623    statistic has already been used. */
624 static int
625 string_to_content_type (char *s, int *collide)
626 {
627   static const struct
628     {
629       int value;
630       int collide;
631       const char *string;
632     }
633   *tp,
634   tab[] = 
635     {
636       {N_VECTOR, 0, "N_VECTOR"},
637       {N_VECTOR, 0, "N"},
638       {N_SCALAR, 0, "N_SCALAR"},
639       {N_MATRIX, 1, "N_MATRIX"},
640       {MEAN, 2, "MEAN"},
641       {STDDEV, 3, "STDDEV"},
642       {STDDEV, 3, "SD"},
643       {COUNT, 4, "COUNT"},
644       {MSE, 5, "MSE"},
645       {DFE, 6, "DFE"},
646       {MAT, 7, "MAT"},
647       {COV, 8, "COV"},
648       {CORR, 9, "CORR"},
649       {PROX, 10, "PROX"},
650       {-1, -1, NULL},
651     };
652
653   for (tp = tab; tp->value != -1; tp++)
654     if (!strcmp (s, tp->string))
655       {
656         if (collide)
657           *collide = tp->collide;
658         
659         return tp->value;
660       }
661   return -1;
662 }
663
664 /* Compare two variables using p.mxd.vartype and p.mxd.subtype
665    fields. */
666 static int
667 compare_variables_by_mxd_vartype (const void *a_, const void *b_)
668 {
669   struct variable *const *pa = a_;
670   struct variable *const *pb = b_;
671   const struct matrix_data_proc *a = &(*pa)->p.mxd;
672   const struct matrix_data_proc *b = &(*pb)->p.mxd;
673
674   if (a->vartype != b->vartype)
675     return a->vartype > b->vartype ? 1 : -1;
676   else
677     return a->subtype < b->subtype ? -1 : a->subtype > b->subtype;
678 }
679
680 #if DEBUGGING
681 /* Print out the command as input. */
682 static void
683 debug_print (void)
684 {
685   printf ("MATRIX DATA\n\t/VARIABLES=");
686   
687   {
688     int i;
689     
690     for (i = 0; i < default_dict.nvar; i++)
691       printf ("%s ", default_dict.var[i]->name);
692   }
693   printf ("\n");
694
695   printf ("\t/FORMAT=");
696   if (fmt == LIST)
697     printf ("LIST");
698   else if (fmt == FREE)
699     printf ("FREE");
700   else
701     assert (0);
702   if (section == LOWER)
703     printf (" LOWER");
704   else if (section == UPPER)
705     printf (" UPPER");
706   else if (section == FULL)
707     printf (" FULL");
708   else
709     assert (0);
710   if (diag == DIAGONAL)
711     printf (" DIAGONAL\n");
712   else if (diag == NODIAGONAL)
713     printf (" NODIAGONAL\n");
714   else
715     assert (0);
716
717   if (dict_get_split_cnt (default_dict) != 0)
718     {
719       int i;
720
721       printf ("\t/SPLIT=");
722       for (i = 0; i < dict_get_split_cnt (default_dict); i++)
723         printf ("%s ", dict_get_split_vars (default_dict)[i]->name);
724       if (single_split)
725         printf ("\t/* single split");
726       printf ("\n");
727     }
728   
729   if (n_factors)
730     {
731       int i;
732
733       printf ("\t/FACTORS=");
734       for (i = 0; i < n_factors; i++)
735         printf ("%s ", factors[i]->name);
736       printf ("\n");
737     }
738
739   if (cells != -1)
740     printf ("\t/CELLS=%d\n", cells);
741
742   if (mx->pop_n != -1)
743     printf ("\t/N=%d\n", mx->pop_n);
744
745   if (mx->n_contents)
746     {
747       int i;
748       int space = 0;
749       
750       printf ("\t/CONTENTS=");
751       for (i = 0; i < mx->n_contents; i++)
752         {
753           if (mx->contents[i] == LPAREN)
754             {
755               if (space)
756                 printf (" ");
757               printf ("(");
758               space = 0;
759             }
760           else if (mx->contents[i] == RPAREN)
761             {
762               printf (")");
763               space = 1;
764             }
765           else 
766             {
767
768               assert (mx->contents[i] >= 0 && mx->contents[i] <= PROX);
769               if (space)
770                 printf (" ");
771               printf ("%s", content_names[mx->contents[i]]);
772               space = 1;
773             }
774         }
775       printf ("\n");
776     }
777 }
778 #endif /* DEBUGGING */
779 \f
780 /* Matrix tokenizer. */
781
782 /* Matrix token types. */
783 enum matrix_token_type
784   {
785     MNUM,               /* Number. */
786     MSTR                /* String. */
787   };
788
789 /* A MATRIX DATA parsing token. */
790 struct matrix_token
791   {
792     enum matrix_token_type type; 
793     double number;       /* MNUM: token value. */
794     char *string;        /* MSTR: token string; not null-terminated. */
795     int length;          /* MSTR: tokstr length. */
796   };
797
798 static int mget_token (struct matrix_token *, struct file_handle *);
799
800 #if DEBUGGING
801 #define mget_token(TOKEN, HANDLE) mget_token_dump(TOKEN, HANDLE)
802
803 static void
804 mdump_token (const struct matrix_token *token)
805 {
806   switch (token->type)
807     {
808     case MNUM:
809       printf (" #%g", token->number);
810       break;
811     case MSTR:
812       printf (" '%.*s'", token->length, token->string);
813       break;
814     default:
815       assert (0);
816     }
817   fflush (stdout);
818 }
819
820 static int
821 mget_token_dump (struct matrix_token *token, struct file_handle *data_file)
822 {
823   int result = (mget_token) (token, data_file);
824   mdump_token (token);
825   return result;
826 }
827 #endif
828
829 /* Return the current position in DATA_FILE. */
830 static const char *
831 context (struct file_handle *data_file)
832 {
833   static char buf[32];
834   int len;
835   char *p = dfm_get_record (data_file, &len);
836   
837   if (!p || !len)
838     strcpy (buf, "at end of line");
839   else
840     {
841       char *cp = buf;
842       int n_copy = min (10, len);
843       cp = stpcpy (buf, "before `");
844       while (n_copy && isspace ((unsigned char) *p))
845         p++, n_copy++;
846       while (n_copy && !isspace ((unsigned char) *p))
847         *cp++ = *p++, n_copy--;
848       *cp++ = '\'';
849       *cp = 0;
850     }
851   
852   return buf;
853 }
854
855 /* Is there at least one token left in the data file? */
856 static int
857 another_token (struct file_handle *data_file)
858 {
859   char *cp, *ep;
860   int len;
861
862   for (;;)
863     {
864       cp = dfm_get_record (data_file, &len);
865       if (!cp)
866         return 0;
867
868       ep = cp + len;
869       while (isspace ((unsigned char) *cp) && cp < ep)
870         cp++;
871
872       if (cp < ep)
873         break;
874
875       dfm_fwd_record (data_file);
876     }
877   
878   dfm_set_record (data_file, cp);
879
880   return 1;
881 }
882
883 /* Parse a MATRIX DATA token from mx->data_file into TOKEN. */
884 static int
885 (mget_token) (struct matrix_token *token, struct file_handle *data_file)
886 {
887   char *cp, *ep;
888   int len;
889   int first_column;
890     
891   for (;;)
892     {
893       cp = dfm_get_record (data_file, &len);
894       if (!cp)
895         return 0;
896
897       ep = cp + len;
898       while (isspace ((unsigned char) *cp) && cp < ep)
899         cp++;
900
901       if (cp < ep)
902         break;
903
904       dfm_fwd_record (data_file);
905     }
906   
907   dfm_set_record (data_file, cp);
908   first_column = dfm_get_cur_col (data_file) + 1;
909
910   /* Three types of fields: quoted with ', quoted with ", unquoted. */
911   if (*cp == '\'' || *cp == '"')
912     {
913       int quote = *cp;
914
915       token->type = MSTR;
916       token->string = ++cp;
917       while (cp < ep && *cp != quote)
918         cp++;
919       token->length = cp - token->string;
920       if (cp < ep)
921         cp++;
922       else
923         msg (SW, _("Scope of string exceeds line."));
924     }
925   else
926     {
927       int is_num = isdigit ((unsigned char) *cp) || *cp == '.';
928
929       token->string = cp++;
930       while (cp < ep && !isspace ((unsigned char) *cp) && *cp != ','
931              && *cp != '-' && *cp != '+')
932         {
933           if (isdigit ((unsigned char) *cp))
934             is_num = 1;
935           
936           if ((tolower ((unsigned char) *cp) == 'd'
937                || tolower ((unsigned char) *cp) == 'e')
938               && (cp[1] == '+' || cp[1] == '-'))
939             cp += 2;
940           else
941             cp++;
942         }
943       
944       token->length = cp - token->string;
945       assert (token->length);
946
947       if (is_num)
948         {
949           struct data_in di;
950
951           di.s = token->string;
952           di.e = token->string + token->length;
953           di.v = (union value *) &token->number;
954           di.f1 = first_column;
955           di.format.type = FMT_F;
956           di.format.w = token->length;
957           di.format.d = 0;
958
959           if (!data_in (&di))
960             return 0;
961         }
962       else
963         token->type = MSTR;
964     }
965
966   dfm_set_record (data_file, cp);
967     
968   return 1;
969 }
970
971 /* Forcibly skip the end of a line for content type CONTENT in
972    DATA_FILE. */
973 static int
974 force_eol (struct file_handle *data_file, const char *content)
975 {
976   char *cp;
977   int len;
978   
979   cp = dfm_get_record (data_file, &len);
980   if (!cp)
981     return 0;
982   while (len && isspace (*cp))
983     cp++, len--;
984   
985   if (len)
986     {
987       msg (SE, _("End of line expected %s while reading %s."),
988            context (data_file), content);
989       return 0;
990     }
991   
992   dfm_fwd_record (data_file);
993   
994   return 1;
995 }
996 \f
997 /* Back end, omitting ROWTYPE_. */
998
999 struct nr_aux_data 
1000   {
1001     struct matrix_data_pgm *mx; /* MATRIX DATA program. */
1002     double ***data;             /* MATRIX DATA data. */
1003     double *factor_values;      /* Factor values. */
1004     int max_cell_idx;           /* Max-numbered cell that we have
1005                                    read so far, plus one. */
1006     double *split_values;       /* SPLIT FILE variable values. */
1007   };
1008
1009 static int nr_read_splits (struct nr_aux_data *, int compare);
1010 static int nr_read_factors (struct nr_aux_data *, int cell);
1011 static void nr_output_data (struct nr_aux_data *, struct ccase *,
1012                             write_case_func *, write_case_data);
1013 static void matrix_data_read_without_rowtype (struct case_source *source,
1014                                               struct ccase *,
1015                                               write_case_func *,
1016                                               write_case_data);
1017
1018 /* Read from the data file and write it to the active file. */
1019 static void
1020 read_matrices_without_rowtype (struct matrix_data_pgm *mx)
1021 {
1022   struct nr_aux_data nr;
1023   
1024   if (mx->cells == -1)
1025     mx->cells = 1;
1026
1027   nr.mx = mx;
1028   nr.data = NULL;
1029   nr.factor_values = xmalloc (sizeof *nr.factor_values * mx->n_factors * mx->cells);
1030   nr.max_cell_idx = 0;
1031   nr.split_values = xmalloc (sizeof *nr.split_values
1032                              * dict_get_split_cnt (default_dict));
1033
1034   vfm_source = create_case_source (&matrix_data_without_rowtype_source_class,
1035                                    default_dict, &nr);
1036   
1037   procedure (NULL, &nr);
1038
1039   free (nr.split_values);
1040   free (nr.factor_values);
1041
1042   fh_close_handle (mx->data_file);
1043 }
1044
1045 /* Mirror data across the diagonal of matrix CP which contains
1046    CONTENT type data. */
1047 static void
1048 fill_matrix (struct matrix_data_pgm *mx, int content, double *cp)
1049 {
1050   int type = content_type[content];
1051
1052   if (type == 1 && mx->section != FULL)
1053     {
1054       if (mx->diag == NODIAGONAL)
1055         {
1056           const double fill = content == CORR ? 1.0 : SYSMIS;
1057           int i;
1058
1059           for (i = 0; i < mx->n_continuous; i++)
1060             cp[i * (1 + mx->n_continuous)] = fill;
1061         }
1062       
1063       {
1064         int c, r;
1065         
1066         if (mx->section == LOWER)
1067           {
1068             int n_lines = mx->n_continuous;
1069             if (mx->section != FULL && mx->diag == NODIAGONAL)
1070               n_lines--;
1071             
1072             for (r = 1; r < n_lines; r++)
1073               for (c = 0; c < r; c++)
1074                 cp[r + c * mx->n_continuous] = cp[c + r * mx->n_continuous];
1075           }
1076         else 
1077           {
1078             assert (mx->section == UPPER);
1079             for (r = 1; r < mx->n_continuous; r++)
1080               for (c = 0; c < r; c++)
1081                 cp[c + r * mx->n_continuous] = cp[r + c * mx->n_continuous];
1082           }
1083       }
1084     }
1085   else if (type == 2)
1086     {
1087       int c;
1088
1089       for (c = 1; c < mx->n_continuous; c++)
1090         cp[c] = cp[0];
1091     }
1092 }
1093
1094 /* Read data lines for content type CONTENT from the data file.
1095    If PER_FACTOR is nonzero, then factor information is read from
1096    the data file.  Data is for cell number CELL. */
1097 static int
1098 nr_read_data_lines (struct nr_aux_data *nr,
1099                     int per_factor, int cell, int content, int compare)
1100 {
1101   struct matrix_data_pgm *mx = nr->mx;
1102   const int type = content_type[content];               /* Content type. */
1103   int n_lines; /* Number of lines to parse from data file for this type. */
1104   double *cp;                   /* Current position in vector or matrix. */
1105   int i;
1106
1107   if (type != 1)
1108     n_lines = 1;
1109   else
1110     {
1111       n_lines = mx->n_continuous;
1112       if (mx->section != FULL && mx->diag == NODIAGONAL)
1113         n_lines--;
1114     }
1115
1116   cp = nr->data[content][cell];
1117   if (type == 1 && mx->section == LOWER && mx->diag == NODIAGONAL)
1118     cp += mx->n_continuous;
1119
1120   for (i = 0; i < n_lines; i++)
1121     {
1122       int n_cols;
1123       
1124       if (!nr_read_splits (nr, 1))
1125         return 0;
1126       if (per_factor && !nr_read_factors (nr, cell))
1127         return 0;
1128       compare = 1;
1129
1130       switch (type)
1131         {
1132         case 0:
1133           n_cols = mx->n_continuous;
1134           break;
1135         case 1:
1136           switch (mx->section)
1137             {
1138             case LOWER:
1139               n_cols = i + 1;
1140               break;
1141             case UPPER:
1142               cp += i;
1143               n_cols = mx->n_continuous - i;
1144               if (mx->diag == NODIAGONAL)
1145                 {
1146                   n_cols--;
1147                   cp++;
1148                 }
1149               break;
1150             case FULL:
1151               n_cols = mx->n_continuous;
1152               break;
1153             default:
1154               assert (0);
1155               abort ();
1156             }
1157           break;
1158         case 2:
1159           n_cols = 1;
1160           break;
1161         default:
1162           assert (0);
1163           abort ();
1164         }
1165
1166       {
1167         int j;
1168         
1169         for (j = 0; j < n_cols; j++)
1170           {
1171             struct matrix_token token;
1172             if (!mget_token (&token, mx->data_file))
1173               return 0;
1174             if (token.type != MNUM)
1175               {
1176                 msg (SE, _("expecting value for %s %s"),
1177                      dict_get_var (default_dict, j)->name,
1178                      context (mx->data_file));
1179                 return 0;
1180               }
1181
1182             *cp++ = token.number;
1183           }
1184         if (mx->fmt != FREE
1185             && !force_eol (mx->data_file, content_names[content]))
1186           return 0;
1187         debug_printf (("\n"));
1188       }
1189
1190       if (mx->section == LOWER)
1191         cp += mx->n_continuous - n_cols;
1192     }
1193
1194   fill_matrix (mx, content, nr->data[content][cell]);
1195
1196   return 1;
1197 }
1198
1199 /* When ROWTYPE_ does not appear in the data, reads the matrices and
1200    writes them to the output file.  Returns success. */
1201 static void
1202 matrix_data_read_without_rowtype (struct case_source *source,
1203                                   struct ccase *c,
1204                                   write_case_func *write_case,
1205                                   write_case_data wc_data)
1206 {
1207   struct nr_aux_data *nr = source->aux;
1208   struct matrix_data_pgm *mx = nr->mx;
1209
1210   {
1211     int *cp;
1212
1213     nr->data = pool_alloc (mx->container, (PROX + 1) * sizeof *nr->data);
1214     
1215     {
1216       int i;
1217
1218       for (i = 0; i <= PROX; i++)
1219         nr->data[i] = NULL;
1220     }
1221     
1222     for (cp = mx->contents; *cp != EOC; cp++)
1223       if (*cp != LPAREN && *cp != RPAREN)
1224         {
1225           int per_factor = mx->is_per_factor[*cp];
1226           int n_entries;
1227           
1228           n_entries = mx->n_continuous;
1229           if (content_type[*cp] == 1)
1230             n_entries *= mx->n_continuous;
1231           
1232           {
1233             int n_vectors = per_factor ? mx->cells : 1;
1234             int i;
1235             
1236             nr->data[*cp] = pool_alloc (mx->container,
1237                                        n_vectors * sizeof **nr->data);
1238             
1239             for (i = 0; i < n_vectors; i++)
1240               nr->data[*cp][i] = pool_alloc (mx->container,
1241                                             n_entries * sizeof ***nr->data);
1242           }
1243         }
1244   }
1245   
1246   for (;;)
1247     {
1248       int *bp, *ep, *np;
1249       
1250       if (!nr_read_splits (nr, 0))
1251         return;
1252       
1253       for (bp = mx->contents; *bp != EOC; bp = np)
1254         {
1255           int per_factor;
1256
1257           /* Trap the CONTENTS that we should parse in this pass
1258              between bp and ep.  Set np to the starting bp for next
1259              iteration. */
1260           if (*bp == LPAREN)
1261             {
1262               ep = ++bp;
1263               while (*ep != RPAREN)
1264                 ep++;
1265               np = &ep[1];
1266               per_factor = 1;
1267             }
1268           else
1269             {
1270               ep = &bp[1];
1271               while (*ep != EOC && *ep != LPAREN)
1272                 ep++;
1273               np = ep;
1274               per_factor = 0;
1275             }
1276           
1277           {
1278             int i;
1279               
1280             for (i = 0; i < (per_factor ? mx->cells : 1); i++)
1281               {
1282                 int *cp;
1283
1284                 for (cp = bp; cp < ep; cp++) 
1285                   if (!nr_read_data_lines (nr, per_factor, i, *cp, cp != bp))
1286                     return;
1287               }
1288           }
1289         }
1290
1291       nr_output_data (nr, c, write_case, wc_data);
1292
1293       if (dict_get_split_cnt (default_dict) == 0
1294           || !another_token (mx->data_file))
1295         return;
1296     }
1297 }
1298
1299 /* Read the split file variables.  If COMPARE is 1, compares the
1300    values read to the last values read and returns 1 if they're equal,
1301    0 otherwise. */
1302 static int
1303 nr_read_splits (struct nr_aux_data *nr, int compare)
1304 {
1305   struct matrix_data_pgm *mx = nr->mx;
1306   static int just_read = 0; /* FIXME: WTF? */
1307   size_t split_cnt;
1308   size_t i;
1309
1310   if (compare && just_read)
1311     {
1312       just_read = 0;
1313       return 1;
1314     }
1315   
1316   if (dict_get_split_vars (default_dict) == NULL)
1317     return 1;
1318
1319   if (mx->single_split)
1320     {
1321       if (!compare)
1322         nr->split_values[0]
1323           = ++dict_get_split_vars (default_dict)[0]->p.mxd.subtype;
1324       return 1;
1325     }
1326
1327   if (!compare)
1328     just_read = 1;
1329
1330   split_cnt = dict_get_split_cnt (default_dict);
1331   for (i = 0; i < split_cnt; i++) 
1332     {
1333       struct matrix_token token;
1334       if (!mget_token (&token, mx->data_file))
1335         return 0;
1336       if (token.type != MNUM)
1337         {
1338           msg (SE, _("Syntax error expecting SPLIT FILE value %s."),
1339                context (mx->data_file));
1340           return 0;
1341         }
1342
1343       if (!compare)
1344         nr->split_values[i] = token.number;
1345       else if (nr->split_values[i] != token.number)
1346         {
1347           msg (SE, _("Expecting value %g for %s."),
1348                nr->split_values[i],
1349                dict_get_split_vars (default_dict)[i]->name);
1350           return 0;
1351         }
1352     }
1353
1354   return 1;
1355 }
1356
1357 /* Read the factors for cell CELL.  If COMPARE is 1, compares the
1358    values read to the last values read and returns 1 if they're equal,
1359    0 otherwise. */
1360 static int
1361 nr_read_factors (struct nr_aux_data *nr, int cell)
1362 {
1363   struct matrix_data_pgm *mx = nr->mx;
1364   int compare;
1365   
1366   if (mx->n_factors == 0)
1367     return 1;
1368
1369   assert (nr->max_cell_idx >= cell);
1370   if (cell != nr->max_cell_idx)
1371     compare = 1;
1372   else
1373     {
1374       compare = 0;
1375       nr->max_cell_idx++;
1376     }
1377       
1378   {
1379     int i;
1380     
1381     for (i = 0; i < mx->n_factors; i++)
1382       {
1383         struct matrix_token token;
1384         if (!mget_token (&token, mx->data_file))
1385           return 0;
1386         if (token.type != MNUM)
1387           {
1388             msg (SE, _("Syntax error expecting factor value %s."),
1389                  context (mx->data_file));
1390             return 0;
1391           }
1392         
1393         if (!compare)
1394           nr->factor_values[i + mx->n_factors * cell] = token.number;
1395         else if (nr->factor_values[i + mx->n_factors * cell] != token.number)
1396           {
1397             msg (SE, _("Syntax error expecting value %g for %s %s."),
1398                  nr->factor_values[i + mx->n_factors * cell],
1399                  mx->factors[i]->name, context (mx->data_file));
1400             return 0;
1401           }
1402       }
1403   }
1404
1405   return 1;
1406 }
1407
1408 /* Write the contents of a cell having content type CONTENT and data
1409    CP to the active file. */
1410 static void
1411 dump_cell_content (struct matrix_data_pgm *mx, int content, double *cp,
1412                    struct ccase *c,
1413                    write_case_func *write_case, write_case_data wc_data)
1414 {
1415   int type = content_type[content];
1416
1417   {
1418     st_bare_pad_copy (c->data[mx->rowtype_->fv].s,
1419                       content_names[content], 8);
1420     
1421     if (type != 1)
1422       memset (&c->data[mx->varname_->fv].s, ' ', 8);
1423   }
1424
1425   {
1426     int n_lines = (type == 1) ? mx->n_continuous : 1;
1427     int i;
1428                 
1429     for (i = 0; i < n_lines; i++)
1430       {
1431         int j;
1432
1433         for (j = 0; j < mx->n_continuous; j++)
1434           {
1435             int fv = dict_get_var (default_dict, mx->first_continuous + j)->fv;
1436             c->data[fv].f = *cp;
1437             cp++;
1438           }
1439         if (type == 1)
1440           st_bare_pad_copy (c->data[mx->varname_->fv].s,
1441                             dict_get_var (default_dict,
1442                                           mx->first_continuous + i)->name,
1443                             8);
1444         write_case (wc_data);
1445       }
1446   }
1447 }
1448
1449 /* Finally dump out everything from nr_data[] to the output file. */
1450 static void
1451 nr_output_data (struct nr_aux_data *nr, struct ccase *c,
1452                 write_case_func *write_case, write_case_data wc_data)
1453 {
1454   struct matrix_data_pgm *mx = nr->mx;
1455   
1456   {
1457     struct variable *const *split;
1458     size_t split_cnt;
1459     size_t i;
1460
1461     split_cnt = dict_get_split_cnt (default_dict);
1462     split = dict_get_split_vars (default_dict);
1463     for (i = 0; i < split_cnt; i++)
1464       c->data[split[i]->fv].f = nr->split_values[i];
1465   }
1466
1467   if (mx->n_factors)
1468     {
1469       int cell;
1470
1471       for (cell = 0; cell < mx->cells; cell++)
1472         {
1473           {
1474             int factor;
1475
1476             for (factor = 0; factor < mx->n_factors; factor++)
1477               {
1478                 c->data[mx->factors[factor]->fv].f
1479                   = nr->factor_values[factor + cell * mx->n_factors];
1480                 debug_printf (("f:%s ", mx->factors[factor]->name));
1481               }
1482           }
1483           
1484           {
1485             int content;
1486             
1487             for (content = 0; content <= PROX; content++)
1488               if (mx->is_per_factor[content])
1489                 {
1490                   assert (nr->data[content] != NULL
1491                           && nr->data[content][cell] != NULL);
1492
1493                   dump_cell_content (mx, content, nr->data[content][cell],
1494                                      c, write_case, wc_data);
1495                 }
1496           }
1497         }
1498     }
1499
1500   {
1501     int content;
1502     
1503     {
1504       int factor;
1505
1506       for (factor = 0; factor < mx->n_factors; factor++)
1507         c->data[mx->factors[factor]->fv].f = SYSMIS;
1508     }
1509     
1510     for (content = 0; content <= PROX; content++)
1511       if (!mx->is_per_factor[content] && nr->data[content] != NULL)
1512         dump_cell_content (mx, content, nr->data[content][0],
1513                            c, write_case, wc_data);
1514   }
1515 }
1516 \f
1517 /* Back end, with ROWTYPE_. */
1518
1519 /* All the data for one set of factor values. */
1520 struct factor_data
1521   {
1522     double *factors;
1523     int n_rows[PROX + 1];
1524     double *data[PROX + 1];
1525     struct factor_data *next;
1526   };
1527
1528 /* With ROWTYPE_ auxiliary data. */
1529 struct wr_aux_data 
1530   {
1531     struct matrix_data_pgm *mx;         /* MATRIX DATA program. */
1532     int content;                        /* Type of current row. */
1533     double *split_values;               /* SPLIT FILE variable values. */
1534     struct factor_data *data;           /* All the data. */
1535     struct factor_data *current;        /* Current factor. */
1536   };
1537
1538 static int wr_read_splits (struct wr_aux_data *, struct ccase *,
1539                            write_case_func *, write_case_data);
1540 static int wr_output_data (struct wr_aux_data *, struct ccase *,
1541                            write_case_func *, write_case_data);
1542 static int wr_read_rowtype (struct wr_aux_data *, 
1543                             const struct matrix_token *, struct file_handle *);
1544 static int wr_read_factors (struct wr_aux_data *);
1545 static int wr_read_indeps (struct wr_aux_data *);
1546 static void matrix_data_read_with_rowtype (struct case_source *,
1547                                            struct ccase *,
1548                                            write_case_func *,
1549                                            write_case_data);
1550
1551 /* When ROWTYPE_ appears in the data, reads the matrices and writes
1552    them to the output file. */
1553 static void
1554 read_matrices_with_rowtype (struct matrix_data_pgm *mx)
1555 {
1556   struct wr_aux_data wr;
1557
1558   wr.mx = mx;
1559   wr.content = -1;
1560   wr.split_values = NULL;
1561   wr.data = NULL;
1562   wr.current = NULL;
1563   mx->cells = 0;
1564
1565   vfm_source = create_case_source (&matrix_data_with_rowtype_source_class,
1566                                    default_dict, &wr);
1567   procedure (NULL, &wr);
1568
1569   free (wr.split_values);
1570   fh_close_handle (mx->data_file);
1571 }
1572
1573 /* Read from the data file and write it to the active file. */
1574 static void
1575 matrix_data_read_with_rowtype (struct case_source *source,
1576                                struct ccase *c,
1577                                write_case_func *write_case,
1578                                write_case_data wc_data)
1579 {
1580   struct wr_aux_data *wr = source->aux;
1581   struct matrix_data_pgm *mx = wr->mx;
1582
1583   do
1584     {
1585       if (!wr_read_splits (wr, c, write_case, wc_data))
1586         return;
1587
1588       if (!wr_read_factors (wr))
1589         return;
1590
1591       if (!wr_read_indeps (wr))
1592         return;
1593     }
1594   while (another_token (mx->data_file));
1595
1596   wr_output_data (wr, c, write_case, wc_data);
1597 }
1598
1599 /* Read the split file variables.  If they differ from the previous
1600    set of split variables then output the data.  Returns success. */
1601 static int 
1602 wr_read_splits (struct wr_aux_data *wr,
1603                 struct ccase *c,
1604                 write_case_func *write_case, write_case_data wc_data)
1605 {
1606   struct matrix_data_pgm *mx = wr->mx;
1607   int compare;
1608   size_t split_cnt;
1609
1610   split_cnt = dict_get_split_cnt (default_dict);
1611   if (split_cnt == 0)
1612     return 1;
1613
1614   if (wr->split_values)
1615     compare = 1;
1616   else
1617     {
1618       compare = 0;
1619       wr->split_values = xmalloc (split_cnt * sizeof *wr->split_values);
1620     }
1621   
1622   {
1623     int different = 0;
1624     int i;
1625
1626     for (i = 0; i < split_cnt; i++)
1627       {
1628         struct matrix_token token;
1629         if (!mget_token (&token, mx->data_file))
1630           return 0;
1631         if (token.type != MNUM)
1632           {
1633             msg (SE, _("Syntax error %s expecting SPLIT FILE value."),
1634                  context (mx->data_file));
1635             return 0;
1636           }
1637
1638         if (compare && wr->split_values[i] != token.number && !different)
1639           {
1640             if (!wr_output_data (wr, c, write_case, wc_data))
1641               return 0;
1642             different = 1;
1643             mx->cells = 0;
1644           }
1645         wr->split_values[i] = token.number;
1646       }
1647   }
1648
1649   return 1;
1650 }
1651
1652 /* Compares doubles A and B, treating SYSMIS as greatest. */
1653 static int
1654 compare_doubles (const void *a_, const void *b_, void *aux UNUSED)
1655 {
1656   const double *a = a_;
1657   const double *b = b_;
1658
1659   if (*a == *b)
1660     return 0;
1661   else if (*a == SYSMIS)
1662     return 1;
1663   else if (*b == SYSMIS)
1664     return -1;
1665   else if (*a > *b)
1666     return 1;
1667   else
1668     return -1;
1669 }
1670
1671 /* Return strcmp()-type comparison of the MX->n_factors factors at _A and
1672    _B.  Sort missing values toward the end. */
1673 static int
1674 compare_factors (const void *a_, const void *b_, void *mx_)
1675 {
1676   struct matrix_data_pgm *mx = mx_;
1677   struct factor_data *const *pa = a_;
1678   struct factor_data *const *pb = b_;
1679   const double *a = (*pa)->factors;
1680   const double *b = (*pb)->factors;
1681
1682   return lexicographical_compare_3way (a, mx->n_factors,
1683                                        b, mx->n_factors,
1684                                        sizeof *a,
1685                                        compare_doubles, NULL);
1686 }
1687
1688 /* Write out the data for the current split file to the active
1689    file. */
1690 static int 
1691 wr_output_data (struct wr_aux_data *wr,
1692                 struct ccase *c,
1693                 write_case_func *write_case, write_case_data wc_data)
1694 {
1695   struct matrix_data_pgm *mx = wr->mx;
1696
1697   {
1698     struct variable *const *split;
1699     size_t split_cnt;
1700     size_t i;
1701
1702     split_cnt = dict_get_split_cnt (default_dict);
1703     split = dict_get_split_vars (default_dict);
1704     for (i = 0; i < split_cnt; i++)
1705       c->data[split[i]->fv].f = wr->split_values[i];
1706   }
1707
1708   /* Sort the wr->data list. */
1709   {
1710     struct factor_data **factors;
1711     struct factor_data *iter;
1712     int i;
1713
1714     factors = xmalloc (sizeof *factors * mx->cells);
1715
1716     for (i = 0, iter = wr->data; iter; iter = iter->next, i++)
1717       factors[i] = iter;
1718
1719     sort (factors, mx->cells, sizeof *factors, compare_factors, mx);
1720
1721     wr->data = factors[0];
1722     for (i = 0; i < mx->cells - 1; i++)
1723       factors[i]->next = factors[i + 1];
1724     factors[mx->cells - 1]->next = NULL;
1725
1726     free (factors);
1727   }
1728
1729   /* Write out records for every set of factor values. */
1730   {
1731     struct factor_data *iter;
1732     
1733     for (iter = wr->data; iter; iter = iter->next)
1734       {
1735         {
1736           int factor;
1737
1738           for (factor = 0; factor < mx->n_factors; factor++)
1739             {
1740               c->data[mx->factors[factor]->fv].f
1741                 = iter->factors[factor];
1742               debug_printf (("f:%s ", factors[factor]->name));
1743             }
1744         }
1745         
1746         {
1747           int content;
1748
1749           for (content = 0; content <= PROX; content++)
1750             {
1751               if (!iter->n_rows[content])
1752                 continue;
1753               
1754               {
1755                 int type = content_type[content];
1756                 int n_lines = (type == 1
1757                                ? (mx->n_continuous
1758                                   - (mx->section != FULL && mx->diag == NODIAGONAL))
1759                                : 1);
1760                 
1761                 if (n_lines != iter->n_rows[content])
1762                   {
1763                     msg (SE, _("Expected %d lines of data for %s content; "
1764                                "actually saw %d lines.  No data will be "
1765                                "output for this content."),
1766                          n_lines, content_names[content],
1767                          iter->n_rows[content]);
1768                     continue;
1769                   }
1770               }
1771
1772               fill_matrix (mx, content, iter->data[content]);
1773
1774               dump_cell_content (mx, content, iter->data[content],
1775                                  c, write_case, wc_data);
1776             }
1777         }
1778       }
1779   }
1780   
1781   pool_destroy (mx->container);
1782   mx->container = pool_create ();
1783   
1784   wr->data = wr->current = NULL;
1785   
1786   return 1;
1787 }
1788
1789 /* Sets ROWTYPE_ based on the given TOKEN read from DATA_FILE.
1790    Return success. */
1791 static int 
1792 wr_read_rowtype (struct wr_aux_data *wr,
1793                  const struct matrix_token *token,
1794                  struct file_handle *data_file)
1795 {
1796   if (wr->content != -1)
1797     {
1798       msg (SE, _("Multiply specified ROWTYPE_ %s."), context (data_file));
1799       return 0;
1800     }
1801   if (token->type != MSTR)
1802     {
1803       msg (SE, _("Syntax error %s expecting ROWTYPE_ string."),
1804            context (data_file));
1805       return 0;
1806     }
1807   
1808   {
1809     char s[16];
1810     char *cp;
1811     
1812     memcpy (s, token->string, min (15, token->length));
1813     s[min (15, token->length)] = 0;
1814
1815     for (cp = s; *cp; cp++)
1816       *cp = toupper ((unsigned char) *cp);
1817
1818     wr->content = string_to_content_type (s, NULL);
1819   }
1820
1821   if (wr->content == -1)
1822     {
1823       msg (SE, _("Syntax error %s."), context (data_file));
1824       return 0;
1825     }
1826
1827   return 1;
1828 }
1829
1830 /* Read the factors for the current row.  Select a set of factors and
1831    point wr_current to it. */
1832 static int 
1833 wr_read_factors (struct wr_aux_data *wr)
1834 {
1835   struct matrix_data_pgm *mx = wr->mx;
1836   double *factor_values = local_alloc (sizeof *factor_values * mx->n_factors);
1837
1838   wr->content = -1;
1839   {
1840     int i;
1841   
1842     for (i = 0; i < mx->n_factors; i++)
1843       {
1844         struct matrix_token token;
1845         if (!mget_token (&token, mx->data_file))
1846           goto lossage;
1847         if (token.type == MSTR)
1848           {
1849             if (!wr_read_rowtype (wr, &token, mx->data_file))
1850               goto lossage;
1851             if (!mget_token (&token, mx->data_file))
1852               goto lossage;
1853           }
1854         if (token.type != MNUM)
1855           {
1856             msg (SE, _("Syntax error expecting factor value %s."),
1857                  context (mx->data_file));
1858             goto lossage;
1859           }
1860         
1861         factor_values[i] = token.number;
1862       }
1863   }
1864   if (wr->content == -1)
1865     {
1866       struct matrix_token token;
1867       if (!mget_token (&token, mx->data_file))
1868         goto lossage;
1869       if (!wr_read_rowtype (wr, &token, mx->data_file))
1870         goto lossage;
1871     }
1872   
1873   /* Try the most recent factor first as a simple caching
1874      mechanism. */
1875   if (wr->current)
1876     {
1877       int i;
1878       
1879       for (i = 0; i < mx->n_factors; i++)
1880         if (factor_values[i] != wr->current->factors[i])
1881           goto cache_miss;
1882       goto winnage;
1883     }
1884
1885   /* Linear search through the list. */
1886 cache_miss:
1887   {
1888     struct factor_data *iter;
1889
1890     for (iter = wr->data; iter; iter = iter->next)
1891       {
1892         int i;
1893
1894         for (i = 0; i < mx->n_factors; i++)
1895           if (factor_values[i] != iter->factors[i])
1896             goto next_item;
1897         
1898         wr->current = iter;
1899         goto winnage;
1900         
1901       next_item: ;
1902       }
1903   }
1904
1905   /* Not found.  Make a new item. */
1906   {
1907     struct factor_data *new = pool_alloc (mx->container, sizeof *new);
1908
1909     new->factors = pool_alloc (mx->container, sizeof *new->factors * mx->n_factors);
1910     
1911     {
1912       int i;
1913
1914       for (i = 0; i < mx->n_factors; i++)
1915         new->factors[i] = factor_values[i];
1916     }
1917     
1918     {
1919       int i;
1920
1921       for (i = 0; i <= PROX; i++)
1922         {
1923           new->n_rows[i] = 0;
1924           new->data[i] = NULL;
1925         }
1926     }
1927
1928     new->next = wr->data;
1929     wr->data = wr->current = new;
1930     mx->cells++;
1931   }
1932
1933 winnage:
1934   local_free (factor_values);
1935   return 1;
1936
1937 lossage:
1938   local_free (factor_values);
1939   return 0;
1940 }
1941
1942 /* Read the independent variables into wr->current. */
1943 static int 
1944 wr_read_indeps (struct wr_aux_data *wr)
1945 {
1946   struct matrix_data_pgm *mx = wr->mx;
1947   struct factor_data *c = wr->current;
1948   const int type = content_type[wr->content];
1949   const int n_rows = c->n_rows[wr->content];
1950   double *cp;
1951   int n_cols;
1952
1953   /* Allocate room for data if necessary. */
1954   if (c->data[wr->content] == NULL)
1955     {
1956       int n_items = mx->n_continuous;
1957       if (type == 1)
1958         n_items *= mx->n_continuous;
1959       
1960       c->data[wr->content] = pool_alloc (mx->container,
1961                                         sizeof **c->data * n_items);
1962     }
1963
1964   cp = &c->data[wr->content][n_rows * mx->n_continuous];
1965
1966   /* Figure out how much to read from this line. */
1967   switch (type)
1968     {
1969     case 0:
1970     case 2:
1971       if (n_rows > 0)
1972         {
1973           msg (SE, _("Duplicate specification for %s."),
1974                content_names[wr->content]);
1975           return 0;
1976         }
1977       if (type == 0)
1978         n_cols = mx->n_continuous;
1979       else
1980         n_cols = 1;
1981       break;
1982     case 1:
1983       if (n_rows >= mx->n_continuous - (mx->section != FULL && mx->diag == NODIAGONAL))
1984         {
1985           msg (SE, _("Too many rows of matrix data for %s."),
1986                content_names[wr->content]);
1987           return 0;
1988         }
1989       
1990       switch (mx->section)
1991         {
1992         case LOWER:
1993           n_cols = n_rows + 1;
1994           if (mx->diag == NODIAGONAL)
1995             cp += mx->n_continuous;
1996           break;
1997         case UPPER:
1998           cp += n_rows;
1999           n_cols = mx->n_continuous - n_rows;
2000           if (mx->diag == NODIAGONAL)
2001             {
2002               n_cols--;
2003               cp++;
2004             }
2005           break;
2006         case FULL:
2007           n_cols = mx->n_continuous;
2008           break;
2009         default:
2010           assert (0);
2011           abort ();
2012         }
2013       break;
2014     default:
2015       assert (0);
2016       abort ();
2017     }
2018   c->n_rows[wr->content]++;
2019
2020   debug_printf ((" (c=%p,r=%d,n=%d)", c, n_rows + 1, n_cols));
2021
2022   /* Read N_COLS items at CP. */
2023   {
2024     int j;
2025         
2026     for (j = 0; j < n_cols; j++)
2027       {
2028         struct matrix_token token;
2029         if (!mget_token (&token, mx->data_file))
2030           return 0;
2031         if (token.type != MNUM)
2032           {
2033             msg (SE, _("Syntax error expecting value for %s %s."),
2034                  dict_get_var (default_dict, mx->first_continuous + j)->name,
2035                  context (mx->data_file));
2036             return 0;
2037           }
2038
2039         *cp++ = token.number;
2040       }
2041     if (mx->fmt != FREE
2042         && !force_eol (mx->data_file, content_names[wr->content]))
2043       return 0;
2044     debug_printf (("\n"));
2045   }
2046
2047   return 1;
2048 }
2049 \f
2050 /* Matrix source. */
2051
2052 static const struct case_source_class matrix_data_with_rowtype_source_class = 
2053   {
2054     "MATRIX DATA",
2055     NULL,
2056     matrix_data_read_with_rowtype,
2057     NULL,
2058   };
2059
2060 static const struct case_source_class 
2061 matrix_data_without_rowtype_source_class =
2062   {
2063     "MATRIX DATA",
2064     NULL,
2065     matrix_data_read_without_rowtype,
2066     NULL,
2067   };