eb2d226f29341bbe4933f3219f8ca005c98bd941
[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   vfm_source = create_case_source (&matrix_data_without_rowtype_source_class, &nr);
976   
977   ok = procedure (NULL, NULL);
978
979   free (nr.split_values);
980   free (nr.factor_values);
981
982   return ok;
983 }
984
985 /* Mirror data across the diagonal of matrix CP which contains
986    CONTENT type data. */
987 static void
988 fill_matrix (struct matrix_data_pgm *mx, int content, double *cp)
989 {
990   int type = content_type[content];
991
992   if (type == 1 && mx->section != FULL)
993     {
994       if (mx->diag == NODIAGONAL)
995         {
996           const double fill = content == CORR ? 1.0 : SYSMIS;
997           int i;
998
999           for (i = 0; i < mx->n_continuous; i++)
1000             cp[i * (1 + mx->n_continuous)] = fill;
1001         }
1002       
1003       {
1004         int c, r;
1005         
1006         if (mx->section == LOWER)
1007           {
1008             int n_lines = mx->n_continuous;
1009             if (mx->section != FULL && mx->diag == NODIAGONAL)
1010               n_lines--;
1011             
1012             for (r = 1; r < n_lines; r++)
1013               for (c = 0; c < r; c++)
1014                 cp[r + c * mx->n_continuous] = cp[c + r * mx->n_continuous];
1015           }
1016         else 
1017           {
1018             assert (mx->section == UPPER);
1019             for (r = 1; r < mx->n_continuous; r++)
1020               for (c = 0; c < r; c++)
1021                 cp[c + r * mx->n_continuous] = cp[r + c * mx->n_continuous];
1022           }
1023       }
1024     }
1025   else if (type == 2)
1026     {
1027       int c;
1028
1029       for (c = 1; c < mx->n_continuous; c++)
1030         cp[c] = cp[0];
1031     }
1032 }
1033
1034 /* Read data lines for content type CONTENT from the data file.
1035    If PER_FACTOR is nonzero, then factor information is read from
1036    the data file.  Data is for cell number CELL. */
1037 static int
1038 nr_read_data_lines (struct nr_aux_data *nr,
1039                     int per_factor, int cell, int content, int compare)
1040 {
1041   struct matrix_data_pgm *mx = nr->mx;
1042   const int type = content_type[content];               /* Content type. */
1043   int n_lines; /* Number of lines to parse from data file for this type. */
1044   double *cp;                   /* Current position in vector or matrix. */
1045   int i;
1046
1047   if (type != 1)
1048     n_lines = 1;
1049   else
1050     {
1051       n_lines = mx->n_continuous;
1052       if (mx->section != FULL && mx->diag == NODIAGONAL)
1053         n_lines--;
1054     }
1055
1056   cp = nr->data[content][cell];
1057   if (type == 1 && mx->section == LOWER && mx->diag == NODIAGONAL)
1058     cp += mx->n_continuous;
1059
1060   for (i = 0; i < n_lines; i++)
1061     {
1062       int n_cols;
1063       
1064       if (!nr_read_splits (nr, 1))
1065         return 0;
1066       if (per_factor && !nr_read_factors (nr, cell))
1067         return 0;
1068       compare = 1;
1069
1070       switch (type)
1071         {
1072         case 0:
1073           n_cols = mx->n_continuous;
1074           break;
1075         case 1:
1076           switch (mx->section)
1077             {
1078             case LOWER:
1079               n_cols = i + 1;
1080               break;
1081             case UPPER:
1082               cp += i;
1083               n_cols = mx->n_continuous - i;
1084               if (mx->diag == NODIAGONAL)
1085                 {
1086                   n_cols--;
1087                   cp++;
1088                 }
1089               break;
1090             case FULL:
1091               n_cols = mx->n_continuous;
1092               break;
1093             default:
1094               assert (0);
1095               abort ();
1096             }
1097           break;
1098         case 2:
1099           n_cols = 1;
1100           break;
1101         default:
1102           assert (0);
1103           abort ();
1104         }
1105
1106       {
1107         int j;
1108         
1109         for (j = 0; j < n_cols; j++)
1110           {
1111             struct matrix_token token;
1112             if (!mget_token (&token, mx->reader))
1113               return 0;
1114             if (token.type != MNUM)
1115               {
1116                 msg (SE, _("expecting value for %s %s"),
1117                      dict_get_var (default_dict, j)->name,
1118                      context (mx->reader));
1119                 return 0;
1120               }
1121
1122             *cp++ = token.number;
1123           }
1124         if (mx->fmt != FREE
1125             && !force_eol (mx->reader, content_names[content]))
1126           return 0;
1127       }
1128
1129       if (mx->section == LOWER)
1130         cp += mx->n_continuous - n_cols;
1131     }
1132
1133   fill_matrix (mx, content, nr->data[content][cell]);
1134
1135   return 1;
1136 }
1137
1138 /* When ROWTYPE_ does not appear in the data, reads the matrices and
1139    writes them to the output file.
1140    Returns true if successful, false if an I/O error occurred. */
1141 static bool
1142 matrix_data_read_without_rowtype (struct case_source *source,
1143                                   struct ccase *c,
1144                                   write_case_func *write_case,
1145                                   write_case_data wc_data)
1146 {
1147   struct nr_aux_data *nr = source->aux;
1148   struct matrix_data_pgm *mx = nr->mx;
1149
1150   {
1151     int *cp;
1152
1153     nr->data = pool_nalloc (mx->container, PROX + 1, sizeof *nr->data);
1154     
1155     {
1156       int i;
1157
1158       for (i = 0; i <= PROX; i++)
1159         nr->data[i] = NULL;
1160     }
1161     
1162     for (cp = mx->contents; *cp != EOC; cp++)
1163       if (*cp != LPAREN && *cp != RPAREN)
1164         {
1165           int per_factor = mx->is_per_factor[*cp];
1166           int n_entries;
1167           
1168           n_entries = mx->n_continuous;
1169           if (content_type[*cp] == 1)
1170             n_entries *= mx->n_continuous;
1171           
1172           {
1173             int n_vectors = per_factor ? mx->cells : 1;
1174             int i;
1175             
1176             nr->data[*cp] = pool_nalloc (mx->container,
1177                                          n_vectors, sizeof **nr->data);
1178             
1179             for (i = 0; i < n_vectors; i++)
1180               nr->data[*cp][i] = pool_nalloc (mx->container,
1181                                               n_entries, sizeof ***nr->data);
1182           }
1183         }
1184   }
1185   
1186   for (;;)
1187     {
1188       int *bp, *ep, *np;
1189       
1190       if (!nr_read_splits (nr, 0))
1191         return true;
1192       
1193       for (bp = mx->contents; *bp != EOC; bp = np)
1194         {
1195           int per_factor;
1196
1197           /* Trap the CONTENTS that we should parse in this pass
1198              between bp and ep.  Set np to the starting bp for next
1199              iteration. */
1200           if (*bp == LPAREN)
1201             {
1202               ep = ++bp;
1203               while (*ep != RPAREN)
1204                 ep++;
1205               np = &ep[1];
1206               per_factor = 1;
1207             }
1208           else
1209             {
1210               ep = &bp[1];
1211               while (*ep != EOC && *ep != LPAREN)
1212                 ep++;
1213               np = ep;
1214               per_factor = 0;
1215             }
1216           
1217           {
1218             int i;
1219               
1220             for (i = 0; i < (per_factor ? mx->cells : 1); i++)
1221               {
1222                 int *cp;
1223
1224                 for (cp = bp; cp < ep; cp++) 
1225                   if (!nr_read_data_lines (nr, per_factor, i, *cp, cp != bp))
1226                     return true;
1227               }
1228           }
1229         }
1230
1231       if (!nr_output_data (nr, c, write_case, wc_data))
1232         return false;
1233
1234       if (dict_get_split_cnt (default_dict) == 0
1235           || !another_token (mx->reader))
1236         return true;
1237     }
1238 }
1239
1240 /* Read the split file variables.  If COMPARE is 1, compares the
1241    values read to the last values read and returns 1 if they're equal,
1242    0 otherwise. */
1243 static int
1244 nr_read_splits (struct nr_aux_data *nr, int compare)
1245 {
1246   struct matrix_data_pgm *mx = nr->mx;
1247   static int just_read = 0; /* FIXME: WTF? */
1248   size_t split_cnt;
1249   size_t i;
1250
1251   if (compare && just_read)
1252     {
1253       just_read = 0;
1254       return 1;
1255     }
1256   
1257   if (dict_get_split_vars (default_dict) == NULL)
1258     return 1;
1259
1260   if (mx->single_split)
1261     {
1262       if (!compare) 
1263         {
1264           struct mxd_var *mv = dict_get_split_vars (default_dict)[0]->aux;
1265           nr->split_values[0] = ++mv->sub_type; 
1266         }
1267       return 1;
1268     }
1269
1270   if (!compare)
1271     just_read = 1;
1272
1273   split_cnt = dict_get_split_cnt (default_dict);
1274   for (i = 0; i < split_cnt; i++) 
1275     {
1276       struct matrix_token token;
1277       if (!mget_token (&token, mx->reader))
1278         return 0;
1279       if (token.type != MNUM)
1280         {
1281           msg (SE, _("Syntax error expecting SPLIT FILE value %s."),
1282                context (mx->reader));
1283           return 0;
1284         }
1285
1286       if (!compare)
1287         nr->split_values[i] = token.number;
1288       else if (nr->split_values[i] != token.number)
1289         {
1290           msg (SE, _("Expecting value %g for %s."),
1291                nr->split_values[i],
1292                dict_get_split_vars (default_dict)[i]->name);
1293           return 0;
1294         }
1295     }
1296
1297   return 1;
1298 }
1299
1300 /* Read the factors for cell CELL.  If COMPARE is 1, compares the
1301    values read to the last values read and returns 1 if they're equal,
1302    0 otherwise. */
1303 static int
1304 nr_read_factors (struct nr_aux_data *nr, int cell)
1305 {
1306   struct matrix_data_pgm *mx = nr->mx;
1307   int compare;
1308   
1309   if (mx->n_factors == 0)
1310     return 1;
1311
1312   assert (nr->max_cell_idx >= cell);
1313   if (cell != nr->max_cell_idx)
1314     compare = 1;
1315   else
1316     {
1317       compare = 0;
1318       nr->max_cell_idx++;
1319     }
1320       
1321   {
1322     size_t i;
1323     
1324     for (i = 0; i < mx->n_factors; i++)
1325       {
1326         struct matrix_token token;
1327         if (!mget_token (&token, mx->reader))
1328           return 0;
1329         if (token.type != MNUM)
1330           {
1331             msg (SE, _("Syntax error expecting factor value %s."),
1332                  context (mx->reader));
1333             return 0;
1334           }
1335         
1336         if (!compare)
1337           nr->factor_values[i + mx->n_factors * cell] = token.number;
1338         else if (nr->factor_values[i + mx->n_factors * cell] != token.number)
1339           {
1340             msg (SE, _("Syntax error expecting value %g for %s %s."),
1341                  nr->factor_values[i + mx->n_factors * cell],
1342                  mx->factors[i]->name, context (mx->reader));
1343             return 0;
1344           }
1345       }
1346   }
1347
1348   return 1;
1349 }
1350
1351 /* Write the contents of a cell having content type CONTENT and data
1352    CP to the active file.
1353    Returns true if successful, false if an I/O error occurred. */
1354 static bool
1355 dump_cell_content (struct matrix_data_pgm *mx, int content, double *cp,
1356                    struct ccase *c,
1357                    write_case_func *write_case, write_case_data wc_data)
1358 {
1359   int type = content_type[content];
1360
1361   {
1362     buf_copy_str_rpad (case_data_rw (c, mx->rowtype_->fv)->s, 8,
1363                        content_names[content]);
1364     
1365     if (type != 1)
1366       memset (case_data_rw (c, mx->varname_->fv)->s, ' ', 8);
1367   }
1368
1369   {
1370     int n_lines = (type == 1) ? mx->n_continuous : 1;
1371     int i;
1372                 
1373     for (i = 0; i < n_lines; i++)
1374       {
1375         int j;
1376
1377         for (j = 0; j < mx->n_continuous; j++)
1378           {
1379             int fv = dict_get_var (default_dict, mx->first_continuous + j)->fv;
1380             case_data_rw (c, fv)->f = *cp;
1381             cp++;
1382           }
1383         if (type == 1)
1384           buf_copy_str_rpad (case_data_rw (c, mx->varname_->fv)->s, 8,
1385                              dict_get_var (default_dict,
1386                                            mx->first_continuous + i)->name);
1387         if (!write_case (wc_data))
1388           return false;
1389       }
1390   }
1391   return true;
1392 }
1393
1394 /* Finally dump out everything from nr_data[] to the output file. */
1395 static bool
1396 nr_output_data (struct nr_aux_data *nr, struct ccase *c,
1397                 write_case_func *write_case, write_case_data wc_data)
1398 {
1399   struct matrix_data_pgm *mx = nr->mx;
1400   
1401   {
1402     struct variable *const *split;
1403     size_t split_cnt;
1404     size_t i;
1405
1406     split_cnt = dict_get_split_cnt (default_dict);
1407     split = dict_get_split_vars (default_dict);
1408     for (i = 0; i < split_cnt; i++)
1409       case_data_rw (c, split[i]->fv)->f = nr->split_values[i];
1410   }
1411
1412   if (mx->n_factors)
1413     {
1414       int cell;
1415
1416       for (cell = 0; cell < mx->cells; cell++)
1417         {
1418           {
1419             size_t factor;
1420
1421             for (factor = 0; factor < mx->n_factors; factor++)
1422               case_data_rw (c, mx->factors[factor]->fv)->f
1423                 = nr->factor_values[factor + cell * mx->n_factors];
1424           }
1425           
1426           {
1427             int content;
1428             
1429             for (content = 0; content <= PROX; content++)
1430               if (mx->is_per_factor[content])
1431                 {
1432                   assert (nr->data[content] != NULL
1433                           && nr->data[content][cell] != NULL);
1434
1435                   if (!dump_cell_content (mx, content, nr->data[content][cell],
1436                                           c, write_case, wc_data))
1437                     return false;
1438                 }
1439           }
1440         }
1441     }
1442
1443   {
1444     int content;
1445     
1446     {
1447       size_t factor;
1448
1449       for (factor = 0; factor < mx->n_factors; factor++)
1450         case_data_rw (c, mx->factors[factor]->fv)->f = SYSMIS;
1451     }
1452     
1453     for (content = 0; content <= PROX; content++)
1454       if (!mx->is_per_factor[content] && nr->data[content] != NULL) 
1455         {
1456           if (!dump_cell_content (mx, content, nr->data[content][0],
1457                                   c, write_case, wc_data))
1458             return false; 
1459         }
1460   }
1461
1462   return true;
1463 }
1464 \f
1465 /* Back end, with ROWTYPE_. */
1466
1467 /* All the data for one set of factor values. */
1468 struct factor_data
1469   {
1470     double *factors;
1471     int n_rows[PROX + 1];
1472     double *data[PROX + 1];
1473     struct factor_data *next;
1474   };
1475
1476 /* With ROWTYPE_ auxiliary data. */
1477 struct wr_aux_data 
1478   {
1479     struct matrix_data_pgm *mx;         /* MATRIX DATA program. */
1480     int content;                        /* Type of current row. */
1481     double *split_values;               /* SPLIT FILE variable values. */
1482     struct factor_data *data;           /* All the data. */
1483     struct factor_data *current;        /* Current factor. */
1484   };
1485
1486 static int wr_read_splits (struct wr_aux_data *, struct ccase *,
1487                            write_case_func *, write_case_data);
1488 static bool wr_output_data (struct wr_aux_data *, struct ccase *,
1489                            write_case_func *, write_case_data);
1490 static int wr_read_rowtype (struct wr_aux_data *, 
1491                             const struct matrix_token *, struct dfm_reader *);
1492 static int wr_read_factors (struct wr_aux_data *);
1493 static int wr_read_indeps (struct wr_aux_data *);
1494 static bool matrix_data_read_with_rowtype (struct case_source *,
1495                                            struct ccase *,
1496                                            write_case_func *,
1497                                            write_case_data);
1498
1499 /* When ROWTYPE_ appears in the data, reads the matrices and writes
1500    them to the output file.
1501    Returns true if successful, false if an I/O error occurred. */
1502 static bool
1503 read_matrices_with_rowtype (struct matrix_data_pgm *mx)
1504 {
1505   struct wr_aux_data wr;
1506   bool ok;
1507
1508   wr.mx = mx;
1509   wr.content = -1;
1510   wr.split_values = NULL;
1511   wr.data = NULL;
1512   wr.current = NULL;
1513   mx->cells = 0;
1514
1515   vfm_source = create_case_source (&matrix_data_with_rowtype_source_class,
1516                                    &wr);
1517   ok = procedure (NULL, NULL);
1518
1519   free (wr.split_values);
1520   return ok;
1521 }
1522
1523 /* Read from the data file and write it to the active file.
1524    Returns true if successful, false if an I/O error occurred. */
1525 static bool
1526 matrix_data_read_with_rowtype (struct case_source *source,
1527                                struct ccase *c,
1528                                write_case_func *write_case,
1529                                write_case_data wc_data)
1530 {
1531   struct wr_aux_data *wr = source->aux;
1532   struct matrix_data_pgm *mx = wr->mx;
1533
1534   do
1535     {
1536       if (!wr_read_splits (wr, c, write_case, wc_data))
1537         return true;
1538
1539       if (!wr_read_factors (wr))
1540         return true;
1541
1542       if (!wr_read_indeps (wr))
1543         return true;
1544     }
1545   while (another_token (mx->reader));
1546
1547   return wr_output_data (wr, c, write_case, wc_data);
1548 }
1549
1550 /* Read the split file variables.  If they differ from the previous
1551    set of split variables then output the data.  Returns success. */
1552 static int 
1553 wr_read_splits (struct wr_aux_data *wr,
1554                 struct ccase *c,
1555                 write_case_func *write_case, write_case_data wc_data)
1556 {
1557   struct matrix_data_pgm *mx = wr->mx;
1558   int compare;
1559   size_t split_cnt;
1560
1561   split_cnt = dict_get_split_cnt (default_dict);
1562   if (split_cnt == 0)
1563     return 1;
1564
1565   if (wr->split_values)
1566     compare = 1;
1567   else
1568     {
1569       compare = 0;
1570       wr->split_values = xnmalloc (split_cnt, sizeof *wr->split_values);
1571     }
1572   
1573   {
1574     int different = 0;
1575     int i;
1576
1577     for (i = 0; i < split_cnt; i++)
1578       {
1579         struct matrix_token token;
1580         if (!mget_token (&token, mx->reader))
1581           return 0;
1582         if (token.type != MNUM)
1583           {
1584             msg (SE, _("Syntax error %s expecting SPLIT FILE value."),
1585                  context (mx->reader));
1586             return 0;
1587           }
1588
1589         if (compare && wr->split_values[i] != token.number && !different)
1590           {
1591             if (!wr_output_data (wr, c, write_case, wc_data))
1592               return 0;
1593             different = 1;
1594             mx->cells = 0;
1595           }
1596         wr->split_values[i] = token.number;
1597       }
1598   }
1599
1600   return 1;
1601 }
1602
1603 /* Compares doubles A and B, treating SYSMIS as greatest. */
1604 static int
1605 compare_doubles (const void *a_, const void *b_, void *aux UNUSED)
1606 {
1607   const double *a = a_;
1608   const double *b = b_;
1609
1610   if (*a == *b)
1611     return 0;
1612   else if (*a == SYSMIS)
1613     return 1;
1614   else if (*b == SYSMIS)
1615     return -1;
1616   else if (*a > *b)
1617     return 1;
1618   else
1619     return -1;
1620 }
1621
1622 /* Return strcmp()-type comparison of the MX->n_factors factors at _A and
1623    _B.  Sort missing values toward the end. */
1624 static int
1625 compare_factors (const void *a_, const void *b_, void *mx_)
1626 {
1627   struct matrix_data_pgm *mx = mx_;
1628   struct factor_data *const *pa = a_;
1629   struct factor_data *const *pb = b_;
1630   const double *a = (*pa)->factors;
1631   const double *b = (*pb)->factors;
1632
1633   return lexicographical_compare_3way (a, mx->n_factors,
1634                                        b, mx->n_factors,
1635                                        sizeof *a,
1636                                        compare_doubles, NULL);
1637 }
1638
1639 /* Write out the data for the current split file to the active
1640    file.
1641    Returns true if successful, false if an I/O error occurred. */
1642 static bool
1643 wr_output_data (struct wr_aux_data *wr,
1644                 struct ccase *c,
1645                 write_case_func *write_case, write_case_data wc_data)
1646 {
1647   struct matrix_data_pgm *mx = wr->mx;
1648   bool ok = true;
1649
1650   {
1651     struct variable *const *split;
1652     size_t split_cnt;
1653     size_t i;
1654
1655     split_cnt = dict_get_split_cnt (default_dict);
1656     split = dict_get_split_vars (default_dict);
1657     for (i = 0; i < split_cnt; i++)
1658       case_data_rw (c, split[i]->fv)->f = wr->split_values[i];
1659   }
1660
1661   /* Sort the wr->data list. */
1662   {
1663     struct factor_data **factors;
1664     struct factor_data *iter;
1665     int i;
1666
1667     factors = xnmalloc (mx->cells, sizeof *factors);
1668
1669     for (i = 0, iter = wr->data; iter; iter = iter->next, i++)
1670       factors[i] = iter;
1671
1672     sort (factors, mx->cells, sizeof *factors, compare_factors, mx);
1673
1674     wr->data = factors[0];
1675     for (i = 0; i < mx->cells - 1; i++)
1676       factors[i]->next = factors[i + 1];
1677     factors[mx->cells - 1]->next = NULL;
1678
1679     free (factors);
1680   }
1681
1682   /* Write out records for every set of factor values. */
1683   {
1684     struct factor_data *iter;
1685     
1686     for (iter = wr->data; iter; iter = iter->next)
1687       {
1688         {
1689           size_t factor;
1690
1691           for (factor = 0; factor < mx->n_factors; factor++)
1692             case_data_rw (c, mx->factors[factor]->fv)->f
1693               = iter->factors[factor];
1694         }
1695         
1696         {
1697           int content;
1698
1699           for (content = 0; content <= PROX; content++)
1700             {
1701               if (!iter->n_rows[content])
1702                 continue;
1703               
1704               {
1705                 int type = content_type[content];
1706                 int n_lines = (type == 1
1707                                ? (mx->n_continuous
1708                                   - (mx->section != FULL && mx->diag == NODIAGONAL))
1709                                : 1);
1710                 
1711                 if (n_lines != iter->n_rows[content])
1712                   {
1713                     msg (SE, _("Expected %d lines of data for %s content; "
1714                                "actually saw %d lines.  No data will be "
1715                                "output for this content."),
1716                          n_lines, content_names[content],
1717                          iter->n_rows[content]);
1718                     continue;
1719                   }
1720               }
1721
1722               fill_matrix (mx, content, iter->data[content]);
1723
1724               ok = dump_cell_content (mx, content, iter->data[content],
1725                                       c, write_case, wc_data);
1726               if (!ok)
1727                 break;
1728             }
1729         }
1730       }
1731   }
1732   
1733   pool_destroy (mx->container);
1734   mx->container = pool_create ();
1735   
1736   wr->data = wr->current = NULL;
1737   
1738   return ok;
1739 }
1740
1741 /* Sets ROWTYPE_ based on the given TOKEN read from READER.
1742    Return success. */
1743 static int 
1744 wr_read_rowtype (struct wr_aux_data *wr,
1745                  const struct matrix_token *token,
1746                  struct dfm_reader *reader)
1747 {
1748   if (wr->content != -1)
1749     {
1750       msg (SE, _("Multiply specified ROWTYPE_ %s."), context (reader));
1751       return 0;
1752     }
1753   if (token->type != MSTR)
1754     {
1755       msg (SE, _("Syntax error %s expecting ROWTYPE_ string."),
1756            context (reader));
1757       return 0;
1758     }
1759   
1760   {
1761     char s[16];
1762     char *cp;
1763     
1764     memcpy (s, token->string, min (15, token->length));
1765     s[min (15, token->length)] = 0;
1766
1767     for (cp = s; *cp; cp++)
1768       *cp = toupper ((unsigned char) *cp);
1769
1770     wr->content = string_to_content_type (s, NULL);
1771   }
1772
1773   if (wr->content == -1)
1774     {
1775       msg (SE, _("Syntax error %s."), context (reader));
1776       return 0;
1777     }
1778
1779   return 1;
1780 }
1781
1782 /* Read the factors for the current row.  Select a set of factors and
1783    point wr_current to it. */
1784 static int 
1785 wr_read_factors (struct wr_aux_data *wr)
1786 {
1787   struct matrix_data_pgm *mx = wr->mx;
1788   double *factor_values = local_alloc (sizeof *factor_values * mx->n_factors);
1789
1790   wr->content = -1;
1791   {
1792     size_t i;
1793   
1794     for (i = 0; i < mx->n_factors; i++)
1795       {
1796         struct matrix_token token;
1797         if (!mget_token (&token, mx->reader))
1798           goto lossage;
1799         if (token.type == MSTR)
1800           {
1801             if (!wr_read_rowtype (wr, &token, mx->reader))
1802               goto lossage;
1803             if (!mget_token (&token, mx->reader))
1804               goto lossage;
1805           }
1806         if (token.type != MNUM)
1807           {
1808             msg (SE, _("Syntax error expecting factor value %s."),
1809                  context (mx->reader));
1810             goto lossage;
1811           }
1812         
1813         factor_values[i] = token.number;
1814       }
1815   }
1816   if (wr->content == -1)
1817     {
1818       struct matrix_token token;
1819       if (!mget_token (&token, mx->reader))
1820         goto lossage;
1821       if (!wr_read_rowtype (wr, &token, mx->reader))
1822         goto lossage;
1823     }
1824   
1825   /* Try the most recent factor first as a simple caching
1826      mechanism. */
1827   if (wr->current)
1828     {
1829       size_t i;
1830       
1831       for (i = 0; i < mx->n_factors; i++)
1832         if (factor_values[i] != wr->current->factors[i])
1833           goto cache_miss;
1834       goto winnage;
1835     }
1836
1837   /* Linear search through the list. */
1838 cache_miss:
1839   {
1840     struct factor_data *iter;
1841
1842     for (iter = wr->data; iter; iter = iter->next)
1843       {
1844         size_t i;
1845
1846         for (i = 0; i < mx->n_factors; i++)
1847           if (factor_values[i] != iter->factors[i])
1848             goto next_item;
1849         
1850         wr->current = iter;
1851         goto winnage;
1852         
1853       next_item: ;
1854       }
1855   }
1856
1857   /* Not found.  Make a new item. */
1858   {
1859     struct factor_data *new = pool_alloc (mx->container, sizeof *new);
1860
1861     new->factors = pool_nalloc (mx->container,
1862                                 mx->n_factors, sizeof *new->factors);
1863     
1864     {
1865       size_t i;
1866
1867       for (i = 0; i < mx->n_factors; i++)
1868         new->factors[i] = factor_values[i];
1869     }
1870     
1871     {
1872       int i;
1873
1874       for (i = 0; i <= PROX; i++)
1875         {
1876           new->n_rows[i] = 0;
1877           new->data[i] = NULL;
1878         }
1879     }
1880
1881     new->next = wr->data;
1882     wr->data = wr->current = new;
1883     mx->cells++;
1884   }
1885
1886 winnage:
1887   local_free (factor_values);
1888   return 1;
1889
1890 lossage:
1891   local_free (factor_values);
1892   return 0;
1893 }
1894
1895 /* Read the independent variables into wr->current. */
1896 static int 
1897 wr_read_indeps (struct wr_aux_data *wr)
1898 {
1899   struct matrix_data_pgm *mx = wr->mx;
1900   struct factor_data *c = wr->current;
1901   const int type = content_type[wr->content];
1902   const int n_rows = c->n_rows[wr->content];
1903   double *cp;
1904   int n_cols;
1905
1906   /* Allocate room for data if necessary. */
1907   if (c->data[wr->content] == NULL)
1908     {
1909       int n_items = mx->n_continuous;
1910       if (type == 1)
1911         n_items *= mx->n_continuous;
1912       
1913       c->data[wr->content] = pool_nalloc (mx->container,
1914                                           n_items, sizeof **c->data);
1915     }
1916
1917   cp = &c->data[wr->content][n_rows * mx->n_continuous];
1918
1919   /* Figure out how much to read from this line. */
1920   switch (type)
1921     {
1922     case 0:
1923     case 2:
1924       if (n_rows > 0)
1925         {
1926           msg (SE, _("Duplicate specification for %s."),
1927                content_names[wr->content]);
1928           return 0;
1929         }
1930       if (type == 0)
1931         n_cols = mx->n_continuous;
1932       else
1933         n_cols = 1;
1934       break;
1935     case 1:
1936       if (n_rows >= mx->n_continuous - (mx->section != FULL && mx->diag == NODIAGONAL))
1937         {
1938           msg (SE, _("Too many rows of matrix data for %s."),
1939                content_names[wr->content]);
1940           return 0;
1941         }
1942       
1943       switch (mx->section)
1944         {
1945         case LOWER:
1946           n_cols = n_rows + 1;
1947           if (mx->diag == NODIAGONAL)
1948             cp += mx->n_continuous;
1949           break;
1950         case UPPER:
1951           cp += n_rows;
1952           n_cols = mx->n_continuous - n_rows;
1953           if (mx->diag == NODIAGONAL)
1954             {
1955               n_cols--;
1956               cp++;
1957             }
1958           break;
1959         case FULL:
1960           n_cols = mx->n_continuous;
1961           break;
1962         default:
1963           assert (0);
1964           abort ();
1965         }
1966       break;
1967     default:
1968       assert (0);
1969       abort ();
1970     }
1971   c->n_rows[wr->content]++;
1972
1973   /* Read N_COLS items at CP. */
1974   {
1975     int j;
1976         
1977     for (j = 0; j < n_cols; j++)
1978       {
1979         struct matrix_token token;
1980         if (!mget_token (&token, mx->reader))
1981           return 0;
1982         if (token.type != MNUM)
1983           {
1984             msg (SE, _("Syntax error expecting value for %s %s."),
1985                  dict_get_var (default_dict, mx->first_continuous + j)->name,
1986                  context (mx->reader));
1987             return 0;
1988           }
1989
1990         *cp++ = token.number;
1991       }
1992     if (mx->fmt != FREE
1993         && !force_eol (mx->reader, content_names[wr->content]))
1994       return 0;
1995   }
1996
1997   return 1;
1998 }
1999 \f
2000 /* Matrix source. */
2001
2002 static const struct case_source_class matrix_data_with_rowtype_source_class = 
2003   {
2004     "MATRIX DATA",
2005     NULL,
2006     matrix_data_read_with_rowtype,
2007     NULL,
2008   };
2009
2010 static const struct case_source_class 
2011 matrix_data_without_rowtype_source_class =
2012   {
2013     "MATRIX DATA",
2014     NULL,
2015     matrix_data_read_without_rowtype,
2016     NULL,
2017   };
2018