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