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