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