Added new files resulting from directory restructuring.
[pspp-builds.git] / src / language / data-io / print.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 /* FIXME: seems like a lot of code duplication with data-list.c. */
21
22 #include <config.h>
23 #include "message.h"
24 #include <stdlib.h>
25 #include "alloc.h"
26 #include "case.h"
27 #include "command.h"
28 #include "data-writer.h"
29 #include "message.h"
30 #include "expressions/public.h"
31 #include "file-handle.h"
32 #include "lexer.h"
33 #include "misc.h"
34 #include "manager.h"
35 #include "table.h"
36 #include "variable.h"
37
38 #include "gettext.h"
39 #define _(msgid) gettext (msgid)
40
41 /* Describes what to do when an output field is encountered. */
42 enum
43   {
44     PRT_ERROR,                  /* Invalid value. */
45     PRT_NEWLINE,                /* Newline. */
46     PRT_CONST,                  /* Constant string. */
47     PRT_VAR,                    /* Variable. */
48     PRT_SPACE                   /* A single space. */
49   };
50
51 /* Describes how to output one field. */
52 struct prt_out_spec
53   {
54     struct prt_out_spec *next;
55     int type;                   /* PRT_* constant. */
56     int fc;                     /* 0-based first column. */
57     union
58       {
59         char *c;                /* PRT_CONST: Associated string. */
60         struct
61           {
62             struct variable *v; /* PRT_VAR: Associated variable. */
63             struct fmt_spec f;  /* PRT_VAR: Output spec. */
64           }
65         v;
66       }
67     u;
68   };
69
70 /* Enums for use with print_trns's `options' field. */
71 enum
72   {
73     PRT_CMD_MASK = 1,           /* Command type mask. */
74     PRT_PRINT = 0,              /* PRINT transformation identifier. */
75     PRT_WRITE = 1,              /* WRITE transformation identifier. */
76     PRT_EJECT = 002,            /* Can be combined with CMD_PRINT only. */
77     PRT_BINARY = 004            /* File is binary, omit newlines. */
78   };
79
80 /* PRINT, PRINT EJECT, WRITE private data structure. */
81 struct print_trns
82   {
83     struct dfm_writer *writer;  /* Output file, NULL=listing file. */
84     int options;                /* PRT_* bitmapped field. */
85     struct prt_out_spec *spec;  /* Output specifications. */
86     int max_width;              /* Maximum line width including null. */
87     char *line;                 /* Buffer for sticking lines in. */
88   };
89
90 /* PRT_PRINT or PRT_WRITE. */
91 int which_cmd;
92
93 /* Holds information on parsing the data file. */
94 static struct print_trns prt;
95
96 /* Last prt_out_spec in the chain.  Used for building the linked-list. */
97 static struct prt_out_spec *next;
98
99 /* Number of records. */
100 static int nrec;
101
102 static int internal_cmd_print (int flags);
103 static trns_proc_func print_trns_proc;
104 static trns_free_func print_trns_free;
105 static int parse_specs (void);
106 static void dump_table (const struct file_handle *);
107 static void append_var_spec (struct prt_out_spec *);
108 static void alloc_line (void);
109 \f
110 /* Basic parsing. */
111
112 /* Parses PRINT command. */
113 int
114 cmd_print (void)
115 {
116   return internal_cmd_print (PRT_PRINT);
117 }
118
119 /* Parses PRINT EJECT command. */
120 int
121 cmd_print_eject (void)
122 {
123   return internal_cmd_print (PRT_PRINT | PRT_EJECT);
124 }
125
126 /* Parses WRITE command. */
127 int
128 cmd_write (void)
129 {
130   return internal_cmd_print (PRT_WRITE);
131 }
132
133 /* Parses the output commands.  F is PRT_PRINT, PRT_WRITE, or
134    PRT_PRINT|PRT_EJECT. */
135 static int
136 internal_cmd_print (int f)
137 {
138   int table = 0;                /* Print table? */
139   struct print_trns *trns;      /* malloc()'d transformation. */
140   struct file_handle *fh = NULL;
141
142   /* Fill in prt to facilitate error-handling. */
143   prt.writer = NULL;
144   prt.options = f;
145   prt.spec = NULL;
146   prt.line = NULL;
147   next = NULL;
148   nrec = 0;
149
150   which_cmd = f & PRT_CMD_MASK;
151
152   /* Parse the command options. */
153   while (!lex_match ('/'))
154     {
155       if (lex_match_id ("OUTFILE"))
156         {
157           lex_match ('=');
158
159           fh = fh_parse (FH_REF_FILE);
160           if (fh == NULL)
161             goto error;
162         }
163       else if (lex_match_id ("RECORDS"))
164         {
165           lex_match ('=');
166           lex_match ('(');
167           if (!lex_force_int ())
168             goto error;
169           nrec = lex_integer ();
170           lex_get ();
171           lex_match (')');
172         }
173       else if (lex_match_id ("TABLE"))
174         table = 1;
175       else if (lex_match_id ("NOTABLE"))
176         table = 0;
177       else
178         {
179           lex_error (_("expecting a valid subcommand"));
180           goto error;
181         }
182     }
183
184   /* Parse variables and strings. */
185   if (!parse_specs ())
186     goto error;
187
188   if (fh != NULL)
189     {
190       prt.writer = dfm_open_writer (fh);
191       if (prt.writer == NULL)
192         goto error;
193
194       if (fh_get_mode (fh) == FH_MODE_BINARY)
195         prt.options |= PRT_BINARY;
196     }
197
198   /* Output the variable table if requested. */
199   if (table)
200     dump_table (fh);
201
202   /* Count the maximum line width.  Allocate linebuffer if
203      applicable. */
204   alloc_line ();
205
206   /* Put the transformation in the queue. */
207   trns = xmalloc (sizeof *trns);
208   memcpy (trns, &prt, sizeof *trns);
209   add_transformation (print_trns_proc, print_trns_free, trns);
210
211   return CMD_SUCCESS;
212
213  error:
214   print_trns_free (&prt);
215   return CMD_FAILURE;
216 }
217
218 /* Appends the field output specification SPEC to the list maintained
219    in prt. */
220 static void
221 append_var_spec (struct prt_out_spec *spec)
222 {
223   if (next == 0)
224     prt.spec = next = xmalloc (sizeof *spec);
225   else
226     next = next->next = xmalloc (sizeof *spec);
227
228   memcpy (next, spec, sizeof *spec);
229   next->next = NULL;
230 }
231 \f
232 /* Field parsing.  Mostly stolen from data-list.c. */
233
234 /* Used for chaining together fortran-like format specifiers. */
235 struct fmt_list
236 {
237   struct fmt_list *next;
238   int count;
239   struct fmt_spec f;
240   struct fmt_list *down;
241 };
242
243 /* Used as "local" variables among the fixed-format parsing funcs.  If
244    it were guaranteed that PSPP were going to be compiled by gcc,
245    I'd make all these functions a single set of nested functions. */
246 static struct
247   {
248     struct variable **v;                /* variable list */
249     size_t nv;                  /* number of variables in list */
250     size_t cv;                  /* number of variables from list used up so far
251                                    by the FORTRAN-like format specifiers */
252
253     int recno;                  /* current 1-based record number */
254     int sc;                     /* 1-based starting column for next variable */
255
256     struct prt_out_spec spec;           /* next format spec to append to list */
257     int fc, lc;                 /* first, last 1-based column number of current
258                                    var */
259
260     int level;                  /* recursion level for FORTRAN-like format
261                                    specifiers */
262   }
263 fx;
264
265 static int fixed_parse_compatible (void);
266 static struct fmt_list *fixed_parse_fortran (void);
267
268 static int parse_string_argument (void);
269 static int parse_variable_argument (void);
270
271 /* Parses all the variable and string specifications on a single
272    PRINT, PRINT EJECT, or WRITE command into the prt structure.
273    Returns success. */
274 static int
275 parse_specs (void)
276 {
277   /* Return code from called function. */
278   int code;
279
280   fx.recno = 1;
281   fx.sc = 1;
282
283   while (token != '.')
284     {
285       while (lex_match ('/'))
286         {
287           int prev_recno = fx.recno;
288
289           fx.recno++;
290           if (lex_is_number ())
291             {
292               if (!lex_force_int ())
293                 return 0;
294               if (lex_integer () < fx.recno)
295                 {
296                   msg (SE, _("The record number specified, %ld, is "
297                              "before the previous record, %d.  Data "
298                              "fields must be listed in order of "
299                              "increasing record number."),
300                        lex_integer (), fx.recno - 1);
301                   return 0;
302                 }
303               fx.recno = lex_integer ();
304               lex_get ();
305             }
306
307           fx.spec.type = PRT_NEWLINE;
308           while (prev_recno++ < fx.recno)
309             append_var_spec (&fx.spec);
310
311           fx.sc = 1;
312         }
313
314       if (token == T_STRING)
315         code = parse_string_argument ();
316       else
317         code = parse_variable_argument ();
318       if (!code)
319         return 0;
320     }
321   fx.spec.type = PRT_NEWLINE;
322   append_var_spec (&fx.spec);
323
324   if (!nrec)
325     nrec = fx.recno;
326   else if (fx.recno > nrec)
327     {
328       msg (SE, _("Variables are specified on records that "
329                  "should not exist according to RECORDS subcommand."));
330       return 0;
331     }
332       
333   if (token != '.')
334     {
335       lex_error (_("expecting end of command"));
336       return 0;
337     }
338   
339   return 1;
340 }
341
342 /* Parses a string argument to the PRINT commands.  Returns success. */
343 static int
344 parse_string_argument (void)
345 {
346   fx.spec.type = PRT_CONST;
347   fx.spec.fc = fx.sc - 1;
348   fx.spec.u.c = xstrdup (ds_c_str (&tokstr));
349   lex_get ();
350
351   /* Parse the included column range. */
352   if (lex_is_number ())
353     {
354       /* Width of column range in characters. */
355       int c_len;
356
357       /* Width of constant string in characters. */
358       int s_len;
359
360       /* 1-based index of last column in range. */
361       int lc;
362
363       if (!lex_is_integer () || lex_integer () <= 0)
364         {
365           msg (SE, _("%g is not a valid column location."), tokval);
366           goto fail;
367         }
368       fx.spec.fc = lex_integer () - 1;
369
370       lex_get ();
371       lex_negative_to_dash ();
372       if (lex_match ('-'))
373         {
374           if (!lex_is_integer ())
375             {
376               msg (SE, _("Column location expected following `%d-'."),
377                    fx.spec.fc + 1);
378               goto fail;
379             }
380           if (lex_integer () <= 0)
381             {
382               msg (SE, _("%g is not a valid column location."), tokval);
383               goto fail;
384             }
385           if (lex_integer () < fx.spec.fc + 1)
386             {
387               msg (SE, _("%d-%ld is not a valid column range.  The second "
388                    "column must be greater than or equal to the first."),
389                    fx.spec.fc + 1, lex_integer ());
390               goto fail;
391             }
392           lc = lex_integer () - 1;
393
394           lex_get ();
395         }
396       else
397         /* If only a starting location is specified then the field is
398            the width of the provided string. */
399         lc = fx.spec.fc + strlen (fx.spec.u.c) - 1;
400
401       /* Apply the range. */
402       c_len = lc - fx.spec.fc + 1;
403       s_len = strlen (fx.spec.u.c);
404       if (s_len > c_len)
405         fx.spec.u.c[c_len] = 0;
406       else if (s_len < c_len)
407         {
408           fx.spec.u.c = xrealloc (fx.spec.u.c, c_len + 1);
409           memset (&fx.spec.u.c[s_len], ' ', c_len - s_len);
410           fx.spec.u.c[c_len] = 0;
411         }
412
413       fx.sc = lc + 1;
414     }
415   else
416     /* If nothing is provided then the field is the width of the
417        provided string. */
418     fx.sc += strlen (fx.spec.u.c);
419
420   append_var_spec (&fx.spec);
421   return 1;
422
423 fail:
424   free (fx.spec.u.c);
425   return 0;
426 }
427
428 /* Parses a variable argument to the PRINT commands by passing it off
429    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
430    Returns success. */
431 static int
432 parse_variable_argument (void)
433 {
434   if (!parse_variables (default_dict, &fx.v, &fx.nv, PV_DUPLICATE))
435     return 0;
436
437   if (lex_is_number ())
438     {
439       if (!fixed_parse_compatible ())
440         goto fail;
441     }
442   else if (token == '(')
443     {
444       fx.level = 0;
445       fx.cv = 0;
446       if (!fixed_parse_fortran ())
447         goto fail;
448     }
449   else
450     {
451       /* User wants dictionary format specifiers. */
452       size_t i;
453
454       lex_match ('*');
455       for (i = 0; i < fx.nv; i++)
456         {
457           /* Variable. */
458           fx.spec.type = PRT_VAR;
459           fx.spec.fc = fx.sc - 1;
460           fx.spec.u.v.v = fx.v[i];
461           fx.spec.u.v.f = fx.v[i]->print;
462           append_var_spec (&fx.spec);
463           fx.sc += fx.v[i]->print.w;
464
465           /* Space. */
466           fx.spec.type = PRT_SPACE;
467           fx.spec.fc = fx.sc - 1;
468           append_var_spec (&fx.spec);
469           fx.sc++;
470         }
471     }
472
473   free (fx.v);
474   return 1;
475
476 fail:
477   free (fx.v);
478   return 0;
479 }
480
481 /* Verifies that FORMAT doesn't need a variable wider than WIDTH.
482    Returns true iff that is the case. */
483 static bool
484 check_string_width (const struct fmt_spec *format, const struct variable *v) 
485 {
486   if (get_format_var_width (format) > v->width)
487     {
488       msg (SE, _("Variable %s has width %d so it cannot be output "
489                  "as format %s."),
490            v->name, v->width, fmt_to_string (format));
491       return false;
492     }
493   return true;
494 }
495
496 /* Parses a column specification for parse_specs(). */
497 static int
498 fixed_parse_compatible (void)
499 {
500   int individual_var_width;
501   int type;
502   size_t i;
503
504   type = fx.v[0]->type;
505   for (i = 1; i < fx.nv; i++)
506     if (type != fx.v[i]->type)
507       {
508         msg (SE, _("%s is not of the same type as %s.  To specify "
509                    "variables of different types in the same variable "
510                    "list, use a FORTRAN-like format specifier."),
511              fx.v[i]->name, fx.v[0]->name);
512         return 0;
513       }
514
515   if (!lex_force_int ())
516     return 0;
517   fx.fc = lex_integer () - 1;
518   if (fx.fc < 0)
519     {
520       msg (SE, _("Column positions for fields must be positive."));
521       return 0;
522     }
523   lex_get ();
524
525   lex_negative_to_dash ();
526   if (lex_match ('-'))
527     {
528       if (!lex_force_int ())
529         return 0;
530       fx.lc = lex_integer () - 1;
531       if (fx.lc < 0)
532         {
533           msg (SE, _("Column positions for fields must be positive."));
534           return 0;
535         }
536       else if (fx.lc < fx.fc)
537         {
538           msg (SE, _("The ending column for a field must not "
539                      "be less than the starting column."));
540           return 0;
541         }
542       lex_get ();
543     }
544   else
545     fx.lc = fx.fc;
546
547   fx.spec.u.v.f.w = fx.lc - fx.fc + 1;
548   if (lex_match ('('))
549     {
550       struct fmt_desc *fdp;
551
552       if (token == T_ID)
553         {
554           const char *cp;
555
556           fx.spec.u.v.f.type = parse_format_specifier_name (&cp, 0);
557           if (fx.spec.u.v.f.type == -1)
558             return 0;
559           if (*cp)
560             {
561               msg (SE, _("A format specifier on this line "
562                          "has extra characters on the end."));
563               return 0;
564             }
565           lex_get ();
566           lex_match (',');
567         }
568       else
569         fx.spec.u.v.f.type = FMT_F;
570
571       if (lex_is_number ())
572         {
573           if (!lex_force_int ())
574             return 0;
575           if (lex_integer () < 1)
576             {
577               msg (SE, _("The value for number of decimal places "
578                          "must be at least 1."));
579               return 0;
580             }
581           fx.spec.u.v.f.d = lex_integer ();
582           lex_get ();
583         }
584       else
585         fx.spec.u.v.f.d = 0;
586
587       fdp = &formats[fx.spec.u.v.f.type];
588       if (fdp->n_args < 2 && fx.spec.u.v.f.d)
589         {
590           msg (SE, _("Input format %s doesn't accept decimal places."),
591                fdp->name);
592           return 0;
593         }
594       if (fx.spec.u.v.f.d > 16)
595         fx.spec.u.v.f.d = 16;
596
597       if (!lex_force_match (')'))
598         return 0;
599     }
600   else
601     {
602       fx.spec.u.v.f.type = FMT_F;
603       fx.spec.u.v.f.d = 0;
604     }
605
606   fx.sc = fx.lc + 1;
607
608   if ((fx.lc - fx.fc + 1) % fx.nv)
609     {
610       msg (SE, _("The %d columns %d-%d can't be evenly divided into %u "
611                  "fields."),
612            fx.lc - fx.fc + 1, fx.fc + 1, fx.lc + 1, (unsigned) fx.nv);
613       return 0;
614     }
615
616   individual_var_width = (fx.lc - fx.fc + 1) / fx.nv;
617   fx.spec.u.v.f.w = individual_var_width;
618   if (!check_output_specifier (&fx.spec.u.v.f, true)
619       || !check_specifier_type (&fx.spec.u.v.f, type, true))
620     return 0;
621   if (type == ALPHA)
622     {
623       for (i = 0; i < fx.nv; i++)
624         if (!check_string_width (&fx.spec.u.v.f, fx.v[i]))
625           return false;
626     }
627
628   fx.spec.type = PRT_VAR;
629   for (i = 0; i < fx.nv; i++)
630     {
631       fx.spec.fc = fx.fc + individual_var_width * i;
632       fx.spec.u.v.v = fx.v[i];
633       append_var_spec (&fx.spec);
634     }
635   return 1;
636 }
637
638 /* Destroy a format list and, optionally, all its sublists. */
639 static void
640 destroy_fmt_list (struct fmt_list *f, int recurse)
641 {
642   struct fmt_list *next;
643
644   for (; f; f = next)
645     {
646       next = f->next;
647       if (recurse && f->f.type == FMT_DESCEND)
648         destroy_fmt_list (f->down, 1);
649       free (f);
650     }
651 }
652
653 /* Recursively puts the format list F (which represents a set of
654    FORTRAN-like format specifications, like 4(F10,2X)) into the
655    structure prt. */
656 static int
657 dump_fmt_list (struct fmt_list *f)
658 {
659   int i;
660
661   for (; f; f = f->next)
662     if (f->f.type == FMT_X)
663       fx.sc += f->count;
664     else if (f->f.type == FMT_T)
665       fx.sc = f->f.w;
666     else if (f->f.type == FMT_NEWREC)
667       {
668         fx.recno += f->count;
669         fx.sc = 1;
670         fx.spec.type = PRT_NEWLINE;
671         for (i = 0; i < f->count; i++)
672           append_var_spec (&fx.spec);
673       }
674     else
675       for (i = 0; i < f->count; i++)
676         if (f->f.type == FMT_DESCEND)
677           {
678             if (!dump_fmt_list (f->down))
679               return 0;
680           }
681         else
682           {
683             struct variable *v;
684
685             if (fx.cv >= fx.nv)
686               {
687                 msg (SE, _("The number of format "
688                            "specifications exceeds the number of variable "
689                            "names given."));
690                 return 0;
691               }
692
693             v = fx.v[fx.cv++];
694             if (!check_output_specifier (&f->f, true)
695                 || !check_specifier_type (&f->f, v->type, true)
696                 || !check_string_width (&f->f, v))
697               return false;
698
699             fx.spec.type = PRT_VAR;
700             fx.spec.u.v.v = v;
701             fx.spec.u.v.f = f->f;
702             fx.spec.fc = fx.sc - 1;
703             append_var_spec (&fx.spec);
704
705             fx.sc += f->f.w;
706           }
707   return 1;
708 }
709
710 /* Recursively parses a list of FORTRAN-like format specifiers.  Calls
711    itself to parse nested levels of parentheses.  Returns to its
712    original caller NULL, to indicate error, non-NULL, but nothing
713    useful, to indicate success (it returns a free()'d block). */
714 static struct fmt_list *
715 fixed_parse_fortran (void)
716 {
717   struct fmt_list *head = NULL;
718   struct fmt_list *fl = NULL;
719
720   lex_get ();                   /* skip opening parenthesis */
721   while (token != ')')
722     {
723       if (fl)
724         fl = fl->next = xmalloc (sizeof *fl);
725       else
726         head = fl = xmalloc (sizeof *fl);
727
728       if (lex_is_number ())
729         {
730           if (!lex_is_integer ())
731             goto fail;
732           fl->count = lex_integer ();
733           lex_get ();
734         }
735       else
736         fl->count = 1;
737
738       if (token == '(')
739         {
740           fl->f.type = FMT_DESCEND;
741           fx.level++;
742           fl->down = fixed_parse_fortran ();
743           fx.level--;
744           if (!fl->down)
745             goto fail;
746         }
747       else if (lex_match ('/'))
748         fl->f.type = FMT_NEWREC;
749       else if (!parse_format_specifier (&fl->f, FMTP_ALLOW_XT)
750                || !check_output_specifier (&fl->f, 1))
751         goto fail;
752
753       lex_match (',');
754     }
755   fl->next = NULL;
756   lex_get ();
757
758   if (fx.level)
759     return head;
760
761   fl->next = NULL;
762   dump_fmt_list (head);
763   destroy_fmt_list (head, 1);
764   if (fx.cv < fx.nv)
765     {
766       msg (SE, _("There aren't enough format specifications "
767            "to match the number of variable names given."));
768       goto fail;
769     }
770   return head;
771
772 fail:
773   fl->next = NULL;
774   destroy_fmt_list (head, 0);
775
776   return NULL;
777 }
778
779 /* Prints the table produced by the TABLE subcommand to the listing
780    file. */
781 static void
782 dump_table (const struct file_handle *fh)
783 {
784   struct prt_out_spec *spec;
785   struct tab_table *t;
786   int recno;
787   int nspec;
788
789   for (nspec = 0, spec = prt.spec; spec; spec = spec->next)
790     if (spec->type == PRT_CONST || spec->type == PRT_VAR)
791       nspec++;
792   t = tab_create (4, nspec + 1, 0);
793   tab_columns (t, TAB_COL_DOWN, 1);
794   tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, nspec);
795   tab_hline (t, TAL_2, 0, 3, 1);
796   tab_headers (t, 0, 0, 1, 0);
797   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
798   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
799   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
800   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
801   tab_dim (t, tab_natural_dimensions);
802   for (nspec = recno = 0, spec = prt.spec; spec; spec = spec->next)
803     switch (spec->type)
804       {
805       case PRT_NEWLINE:
806         recno++;
807         break;
808       case PRT_CONST:
809         {
810           int len = strlen (spec->u.c);
811           nspec++;
812           tab_text (t, 0, nspec, TAB_LEFT | TAT_FIX | TAT_PRINTF,
813                         "\"%s\"", spec->u.c);
814           tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
815           tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
816                         spec->fc + 1, spec->fc + len);
817           tab_text (t, 3, nspec, TAB_LEFT | TAT_FIX | TAT_PRINTF,
818                         "A%d", len);
819           break;
820         }
821       case PRT_VAR:
822         {
823           nspec++;
824           tab_text (t, 0, nspec, TAB_LEFT, spec->u.v.v->name);
825           tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
826           tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
827                         spec->fc + 1, spec->fc + spec->u.v.f.w);
828           tab_text (t, 3, nspec, TAB_LEFT | TAT_FIX,
829                         fmt_to_string (&spec->u.v.f));
830           break;
831         }
832       case PRT_SPACE:
833         break;
834       case PRT_ERROR:
835         assert (0);
836       }
837
838   if (fh != NULL)
839     tab_title (t, 1, ngettext ("Writing %d record to %s.",
840                                "Writing %d records to %s.", recno),
841                recno, fh_get_name (fh));
842   else
843     tab_title (t, 1, ngettext ("Writing %d record.",
844                                "Writing %d records.", recno), recno);
845   tab_submit (t);
846 }
847
848 /* PORTME: The number of characters in a line terminator. */
849 #ifdef __MSDOS__ 
850 #define LINE_END_WIDTH 2        /* \r\n */
851 #else
852 #define LINE_END_WIDTH 1        /* \n */
853 #endif
854
855 /* Calculates the maximum possible line width and allocates a buffer
856    big enough to contain it */
857 static void
858 alloc_line (void)
859 {
860   /* Cumulative maximum line width (excluding null terminator) so far. */
861   int w = 0;
862
863   /* Width required by current this prt_out_spec. */
864   int pot_w;                    /* Potential w. */
865
866   /* Iterator. */
867   struct prt_out_spec *i;
868
869   for (i = prt.spec; i; i = i->next)
870     {
871       switch (i->type)
872         {
873         case PRT_NEWLINE:
874           pot_w = 0;
875           break;
876         case PRT_CONST:
877           pot_w = i->fc + strlen (i->u.c);
878           break;
879         case PRT_VAR:
880           pot_w = i->fc + i->u.v.f.w;
881           break;
882         case PRT_SPACE:
883           pot_w = i->fc + 1;
884           break;
885         case PRT_ERROR:
886         default:
887           assert (0);
888           abort ();
889         }
890       if (pot_w > w)
891         w = pot_w;
892     }
893   prt.max_width = w + LINE_END_WIDTH + 1;
894   prt.line = xmalloc (prt.max_width);
895 }
896 \f
897 /* Transformation. */
898
899 /* Performs the transformation inside print_trns T on case C. */
900 static int
901 print_trns_proc (void *trns_, struct ccase *c, int case_num UNUSED)
902 {
903   /* Transformation. */
904   struct print_trns *t = trns_;
905
906   /* Iterator. */
907   struct prt_out_spec *i;
908
909   /* Line buffer. */
910   char *buf = t->line;
911
912   /* Length of the line in buf. */
913   int len = 0;
914   memset (buf, ' ', t->max_width);
915
916   if (t->options & PRT_EJECT)
917     som_eject_page ();
918
919   /* Note that a field written to a place where a field has
920      already been written truncates the record.  `PRINT /A B
921      (T10,F8,T1,F8).' only outputs B.  */
922   for (i = t->spec; i; i = i->next)
923     switch (i->type)
924       {
925       case PRT_NEWLINE:
926         if (t->writer == NULL)
927           {
928             buf[len] = 0;
929             tab_output_text (TAT_FIX | TAT_NOWRAP, buf);
930           }
931         else
932           {
933             if ((t->options & PRT_CMD_MASK) == PRT_PRINT
934                 || !(t->options & PRT_BINARY))
935               {
936                 /* PORTME: Line ends. */
937 #ifdef __MSDOS__
938                 buf[len++] = '\r';
939 #endif
940                 buf[len++] = '\n';
941               }
942
943             dfm_put_record (t->writer, buf, len);
944           }
945
946         memset (buf, ' ', t->max_width);
947         len = 0;
948         break;
949
950       case PRT_CONST:
951         /* FIXME: Should be revised to keep track of the string's
952            length outside the loop, probably in i->u.c[0]. */
953         memcpy (&buf[i->fc], i->u.c, strlen (i->u.c));
954         len = i->fc + strlen (i->u.c);
955         break;
956
957       case PRT_VAR:
958         data_out (&buf[i->fc], &i->u.v.f, case_data (c, i->u.v.v->fv));
959         len = i->fc + i->u.v.f.w;
960         break;
961
962       case PRT_SPACE:
963         /* PRT_SPACE always immediately follows PRT_VAR. */
964         buf[len++] = ' ';
965         break;
966
967       case PRT_ERROR:
968         assert (0);
969         break;
970       }
971
972   if (t->writer != NULL && dfm_write_error (t->writer))
973     return TRNS_ERROR;
974   return TRNS_CONTINUE;
975 }
976
977 /* Frees all the data inside print_trns T.  Does not free T. */
978 static bool
979 print_trns_free (void *prt_)
980 {
981   struct print_trns *prt = prt_;
982   struct prt_out_spec *i, *n;
983   bool ok = true;
984
985   for (i = prt->spec; i; i = n)
986     {
987       switch (i->type)
988         {
989         case PRT_CONST:
990           free (i->u.c);
991           /* fall through */
992         case PRT_NEWLINE:
993         case PRT_VAR:
994         case PRT_SPACE:
995           /* nothing to do */
996           break;
997         case PRT_ERROR:
998           assert (0);
999           break;
1000         }
1001       n = i->next;
1002       free (i);
1003     }
1004   if (prt->writer != NULL)
1005     ok = dfm_close_writer (prt->writer);
1006   free (prt->line);
1007   free (prt);
1008   return ok;
1009 }
1010 \f
1011 /* PRINT SPACE. */
1012
1013 /* PRINT SPACE transformation. */
1014 struct print_space_trns
1015 {
1016   struct dfm_writer *writer;    /* Output data file. */
1017   struct expression *e;         /* Number of lines; NULL=1. */
1018 }
1019 print_space_trns;
1020
1021 static trns_proc_func print_space_trns_proc;
1022 static trns_free_func print_space_trns_free;
1023
1024 int
1025 cmd_print_space (void)
1026 {
1027   struct print_space_trns *t;
1028   struct file_handle *fh;
1029   struct expression *e;
1030   struct dfm_writer *writer;
1031
1032   if (lex_match_id ("OUTFILE"))
1033     {
1034       lex_match ('=');
1035
1036       fh = fh_parse (FH_REF_FILE);
1037       if (fh == NULL)
1038         return CMD_FAILURE;
1039       lex_get ();
1040     }
1041   else
1042     fh = NULL;
1043
1044   if (token != '.')
1045     {
1046       e = expr_parse (default_dict, EXPR_NUMBER);
1047       if (token != '.')
1048         {
1049           expr_free (e);
1050           lex_error (_("expecting end of command"));
1051           return CMD_FAILURE;
1052         }
1053     }
1054   else
1055     e = NULL;
1056
1057   if (fh != NULL)
1058     {
1059       writer = dfm_open_writer (fh);
1060       if (writer == NULL) 
1061         {
1062           expr_free (e);
1063           return CMD_FAILURE;
1064         } 
1065     }
1066   else
1067     writer = NULL;
1068   
1069   t = xmalloc (sizeof *t);
1070   t->writer = writer;
1071   t->e = e;
1072
1073   add_transformation (print_space_trns_proc, print_space_trns_free, t);
1074   return CMD_SUCCESS;
1075 }
1076
1077 /* Executes a PRINT SPACE transformation. */
1078 static int
1079 print_space_trns_proc (void *t_, struct ccase *c,
1080                        int case_num UNUSED)
1081 {
1082   struct print_space_trns *t = t_;
1083   int n;
1084
1085   n = 1;
1086   if (t->e)
1087     {
1088       double f = expr_evaluate_num (t->e, c, case_num);
1089       if (f == SYSMIS) 
1090         msg (SW, _("The expression on PRINT SPACE evaluated to the "
1091                    "system-missing value."));
1092       else if (f < 0 || f > INT_MAX)
1093         msg (SW, _("The expression on PRINT SPACE evaluated to %g."), f);
1094       else
1095         n = f;
1096     }
1097
1098   while (n--)
1099     if (t->writer == NULL)
1100       som_blank_line ();
1101     else
1102       dfm_put_record (t->writer, "\n", 1);
1103
1104   if (t->writer != NULL && dfm_write_error (t->writer))
1105     return TRNS_ERROR;
1106   return TRNS_CONTINUE;
1107 }
1108
1109 /* Frees a PRINT SPACE transformation.
1110    Returns true if successful, false if an I/O error occurred. */
1111 static bool
1112 print_space_trns_free (void *trns_)
1113 {
1114   struct print_space_trns *trns = trns_;
1115   bool ok = dfm_close_writer (trns->writer);
1116   expr_free (trns->e);
1117   free (trns);
1118   return ok;
1119 }