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