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