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