Fixed a bug causing pspp to crash when computed variables had no format
[pspp-builds.git] / src / output.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 "output.h"
22 #include <assert.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <ctype.h>
27 #include "alloc.h"
28 #include "devind.h"
29 #include "error.h"
30 #include "filename.h"
31 #include "htmlP.h"
32 #include "lexer.h"
33 #include "misc.h"
34 #include "settings.h"
35 #include "str.h"
36
37 /* FIXME? Should the output configuration format be changed to
38    drivername:classname:devicetype:options, where devicetype is zero
39    or more of screen, printer, listing? */
40
41 /* FIXME: Have the reentrancy problems been solved? */
42
43 /* Where the output driver name came from. */
44 enum
45   {
46     OUTP_S_COMMAND_LINE,        /* Specified by the user. */
47     OUTP_S_INIT_FILE            /* `default' or the init file. */
48   };
49
50 /* Names the output drivers to be used. */
51 struct outp_names
52   {
53     char *name;                 /* Name of the output driver. */
54     int source;                 /* OUTP_S_* */
55     struct outp_names *next, *prev;
56   };
57
58 /* Defines an init file macro. */
59 struct outp_defn
60   {
61     char *key;
62     char *value;
63     struct outp_defn *next, *prev;
64   };
65
66 static struct outp_defn *outp_macros;
67 static struct outp_names *outp_configure_vec;
68
69 struct outp_driver_class_list *outp_class_list;
70 struct outp_driver *outp_driver_list;
71
72 char *outp_title;
73 char *outp_subtitle;
74
75 /* A set of OUTP_DEV_* bits indicating the devices that are
76    disabled. */
77 int disabled_devices;
78
79 static void destroy_driver (struct outp_driver *);
80 static void configure_driver (char *);
81
82 #if GLOBAL_DEBUGGING
83 /* This mechanism attempts to catch reentrant use of outp_driver_list. */
84 static int iterating_driver_list;
85
86 #define reentrancy() msg (FE, _("Attempt to iterate driver list reentrantly."))
87 #endif
88
89 /* Add a class to the class list. */
90 static void
91 add_class (struct outp_class *class)
92 {
93   struct outp_driver_class_list *new_list = xmalloc (sizeof *new_list);
94
95   new_list->class = class;
96   new_list->ref_count = 0;
97
98   if (!outp_class_list)
99     {
100       outp_class_list = new_list;
101       new_list->next = NULL;
102     }
103   else
104     {
105       new_list->next = outp_class_list;
106       outp_class_list = new_list;
107     }
108 }
109
110 /* Finds the outp_names in outp_configure_vec with name between BP and
111    EP exclusive. */
112 static struct outp_names *
113 search_names (char *bp, char *ep)
114 {
115   struct outp_names *n;
116
117   for (n = outp_configure_vec; n; n = n->next)
118     if ((int) strlen (n->name) == ep - bp && !memcmp (n->name, bp, ep - bp))
119       return n;
120   return NULL;
121 }
122
123 /* Deletes outp_names NAME from outp_configure_vec. */
124 static void
125 delete_name (struct outp_names * n)
126 {
127   free (n->name);
128   if (n->prev)
129     n->prev->next = n->next;
130   if (n->next)
131     n->next->prev = n->prev;
132   if (n == outp_configure_vec)
133     outp_configure_vec = n->next;
134   free (n);
135 }
136
137 /* Adds the name between BP and EP exclusive to list
138    outp_configure_vec with source SOURCE. */
139 static void
140 add_name (char *bp, char *ep, int source)
141 {
142   struct outp_names *n = xmalloc (sizeof *n);
143   n->name = xmalloc (ep - bp + 1);
144   memcpy (n->name, bp, ep - bp);
145   n->name[ep - bp] = 0;
146   n->source = source;
147   n->next = outp_configure_vec;
148   n->prev = NULL;
149   if (outp_configure_vec)
150     outp_configure_vec->prev = n;
151   outp_configure_vec = n;
152 }
153
154 /* Checks that outp_configure_vec is empty, bitches & clears it if it
155    isn't. */
156 static void
157 check_configure_vec (void)
158 {
159   struct outp_names *n;
160
161   for (n = outp_configure_vec; n; n = n->next)
162     if (n->source == OUTP_S_COMMAND_LINE)
163       msg (ME, _("Unknown output driver `%s'."), n->name);
164     else
165       msg (IE, _("Output driver `%s' referenced but never defined."), n->name);
166   outp_configure_clear ();
167 }
168
169 /* Searches outp_configure_vec for the name between BP and EP
170    exclusive.  If found, it is deleted, then replaced by the names
171    given in EP+1, if any. */
172 static void
173 expand_name (char *bp, char *ep)
174 {
175   struct outp_names *n = search_names (bp, ep);
176   if (!n)
177     return;
178   delete_name (n);
179
180   bp = ep + 1;
181   for (;;)
182     {
183       while (isspace ((unsigned char) *bp))
184         bp++;
185       ep = bp;
186       while (*ep && !isspace ((unsigned char) *ep))
187         ep++;
188       if (bp == ep)
189         return;
190       if (!search_names (bp, ep))
191         add_name (bp, ep, OUTP_S_INIT_FILE);
192       bp = ep;
193     }
194 }
195
196 /* Looks for a macro with key KEY, and returns the corresponding value
197    if found, or NULL if not. */
198 static const char *
199 find_defn_value (const char *key)
200 {
201   static char buf[INT_DIGITS + 1];
202   struct outp_defn *d;
203
204   for (d = outp_macros; d; d = d->next)
205     if (!strcmp (key, d->key))
206       return d->value;
207   if (!strcmp (key, "viewwidth"))
208     {
209       sprintf (buf, "%d", set_viewwidth);
210       return buf;
211     }
212   else if (!strcmp (key, "viewlength"))
213     {
214       sprintf (buf, "%d", set_viewlength);
215       return buf;
216     }
217   else
218     return getenv (key);
219 }
220
221 /* Initializes global variables. */
222 int
223 outp_init (void)
224 {
225   extern struct outp_class ascii_class;
226 #if !NO_POSTSCRIPT
227   extern struct outp_class postscript_class;
228   extern struct outp_class epsf_class;
229 #endif
230   extern struct outp_class html_class;
231   extern struct outp_class devind_class;
232
233   char def[] = "default";
234
235 #if !NO_HTML
236   add_class (&html_class);
237 #endif
238 #if !NO_POSTSCRIPT
239   add_class (&epsf_class);
240   add_class (&postscript_class);
241 #endif
242   add_class (&devind_class);
243   add_class (&ascii_class);
244
245   add_name (def, &def[strlen (def)], OUTP_S_INIT_FILE);
246
247   return 1;
248 }
249
250 /* Deletes all the output macros. */
251 static void
252 delete_macros (void)
253 {
254   struct outp_defn *d, *next;
255
256   for (d = outp_macros; d; d = next)
257     {
258       next = d->next;
259       free (d->key);
260       free (d->value);
261       free (d);
262     }
263 }
264
265 /* Reads the initialization file; initializes outp_driver_list. */
266 int
267 outp_read_devices (void)
268 {
269   int result = 0;
270
271   char *init_fn;
272
273   FILE *f = NULL;
274   struct string line;
275   struct file_locator where;
276
277 #if GLOBAL_DEBUGGING
278   if (iterating_driver_list)
279     reentrancy ();
280 #endif
281
282   init_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_INIT_FILE",
283                                                "devices"),
284                             fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
285                                                config_path),
286                             NULL);
287   where.filename = init_fn;
288   where.line_number = 0;
289   err_push_file_locator (&where);
290
291   ds_init (NULL, &line, 128);
292
293   if (init_fn == NULL)
294     {
295       msg (IE, _("Cannot find output initialization file.  Use `-vv' to view "
296            "search path."));
297       goto exit;
298     }
299
300   msg (VM (1), _("%s: Opening device description file..."), init_fn);
301   f = fopen (init_fn, "r");
302   if (f == NULL)
303     {
304       msg (IE, _("Opening %s: %s."), init_fn, strerror (errno));
305       goto exit;
306     }
307
308   for (;;)
309     {
310       char *cp;
311
312       if (!ds_get_config_line (f, &line, &where))
313         {
314           if (ferror (f))
315             msg (ME, _("Reading %s: %s."), init_fn, strerror (errno));
316           break;
317         }
318       for (cp = ds_value (&line); isspace ((unsigned char) *cp); cp++);
319       if (!strncmp ("define", cp, 6) && isspace ((unsigned char) cp[6]))
320         outp_configure_macro (&cp[7]);
321       else if (*cp)
322         {
323           char *ep;
324           for (ep = cp; *ep && *ep != ':' && *ep != '='; ep++);
325           if (*ep == '=')
326             expand_name (cp, ep);
327           else if (*ep == ':')
328             {
329               struct outp_names *n = search_names (cp, ep);
330               if (n)
331                 {
332                   configure_driver (cp);
333                   delete_name (n);
334                 }
335             }
336           else
337             msg (IS, _("Syntax error."));
338         }
339     }
340   result = 1;
341
342   check_configure_vec ();
343
344 exit:
345   err_pop_file_locator (&where);
346   if (f && -1 == fclose (f))
347     msg (MW, _("Closing %s: %s."), init_fn, strerror (errno));
348   free (init_fn);
349   ds_destroy (&line);
350   delete_macros ();
351   if (outp_driver_list == NULL)
352     msg (MW, _("No output drivers are active."));
353
354   if (result)
355     msg (VM (2), _("Device definition file read successfully."));
356   else
357     msg (VM (1), _("Error reading device definition file."));
358   return result;
359 }
360
361 /* Clear the list of drivers to configure. */
362 void
363 outp_configure_clear (void)
364 {
365   struct outp_names *n, *next;
366
367   for (n = outp_configure_vec; n; n = next)
368     {
369       next = n->next;
370       free (n->name);
371       free (n);
372     }
373   outp_configure_vec = NULL;
374 }
375
376 /* Adds the name BP to the list of drivers to configure into
377    outp_driver_list. */
378 void
379 outp_configure_add (char *bp)
380 {
381   char *ep = &bp[strlen (bp)];
382   if (!search_names (bp, ep))
383     add_name (bp, ep, OUTP_S_COMMAND_LINE);
384 }
385
386 /* Defines one configuration macro based on the text in BP, which
387    should be of the form `KEY=VALUE'. */
388 void
389 outp_configure_macro (char *bp)
390 {
391   struct outp_defn *d;
392   char *ep;
393
394   while (isspace ((unsigned char) *bp))
395     bp++;
396   ep = bp;
397   while (*ep && !isspace ((unsigned char) *ep) && *ep != '=')
398     ep++;
399
400   d = xmalloc (sizeof *d);
401   d->key = xmalloc (ep - bp + 1);
402   memcpy (d->key, bp, ep - bp);
403   d->key[ep - bp] = 0;
404
405   /* Earlier definitions for a particular KEY override later ones. */
406   if (find_defn_value (d->key))
407     {
408       free (d->key);
409       free (d);
410       return;
411     }
412   
413   if (*ep == '=')
414     ep++;
415   while (isspace ((unsigned char) *ep))
416     ep++;
417   d->value = fn_interp_vars (ep, find_defn_value);
418   d->next = outp_macros;
419   d->prev = NULL;
420   if (outp_macros)
421     outp_macros->prev = d;
422   outp_macros = d;
423 }
424
425 /* Destroys all the drivers in driver list *DL and sets *DL to
426    NULL. */
427 static void
428 destroy_list (struct outp_driver ** dl)
429 {
430   struct outp_driver *d, *next;
431
432   for (d = *dl; d; d = next)
433     {
434       destroy_driver (d);
435       next = d->next;
436       free (d);
437     }
438   *dl = NULL;
439 }
440
441 /* Closes all the output drivers. */
442 int
443 outp_done (void)
444 {
445 #if GLOBAL_DEBUGGING
446   if (iterating_driver_list)
447     reentrancy ();
448 #endif
449   destroy_list (&outp_driver_list);
450
451   return 1;
452 }
453
454 /* Display on stdout a list of all registered driver classes. */
455 void
456 outp_list_classes (void)
457 {
458   int width = set_viewwidth;
459   struct outp_driver_class_list *c;
460
461   printf (_("Driver classes:\n\t"));
462   width -= 8;
463   for (c = outp_class_list; c; c = c->next)
464     {
465       if ((int) strlen (c->class->name) + 1 > width)
466         {
467           printf ("\n\t");
468           width = set_viewwidth - 8;
469         }
470       else
471         putc (' ', stdout);
472       fputs (c->class->name, stdout);
473     }
474   putc('\n', stdout);
475 }
476
477 static int op_token;            /* `=', 'a', 0. */
478 static struct string op_tokstr;
479 static char *prog;
480
481 /* Parses a token from prog into op_token, op_tokstr.  Sets op_token
482    to '=' on an equals sign, to 'a' on a string or identifier token,
483    or to 0 at end of line.  Returns the new op_token. */
484 static int
485 tokener (void)
486 {
487   if (op_token == 0)
488     {
489       msg (IS, _("Syntax error."));
490       return 0;
491     }
492
493   while (isspace ((unsigned char) *prog))
494     prog++;
495   if (!*prog)
496     {
497       op_token = 0;
498       return 0;
499     }
500
501   if (*prog == '=')
502     op_token = *prog++;
503   else
504     {
505       ds_clear (&op_tokstr);
506
507       if (*prog == '\'' || *prog == '"')
508         {
509           int quote = *prog++;
510
511           while (*prog && *prog != quote)
512             {
513               if (*prog != '\\')
514                 ds_putchar (&op_tokstr, *prog++);
515               else
516                 {
517                   int c;
518                   
519                   prog++;
520                   assert ((int) *prog); /* How could a line end in `\'? */
521                   switch (*prog++)
522                     {
523                     case '\'':
524                       c = '\'';
525                       break;
526                     case '"':
527                       c = '"';
528                       break;
529                     case '?':
530                       c = '?';
531                       break;
532                     case '\\':
533                       c = '\\';
534                       break;
535                     case '}':
536                       c = '}';
537                       break;
538                     case 'a':
539                       c = '\a';
540                       break;
541                     case 'b':
542                       c = '\b';
543                       break;
544                     case 'f':
545                       c = '\f';
546                       break;
547                     case 'n':
548                       c = '\n';
549                       break;
550                     case 'r':
551                       c = '\r';
552                       break;
553                     case 't':
554                       c = '\t';
555                       break;
556                     case 'v':
557                       c = '\v';
558                       break;
559                     case '0':
560                     case '1':
561                     case '2':
562                     case '3':
563                     case '4':
564                     case '5':
565                     case '6':
566                     case '7':
567                       {
568                         c = prog[-1] - '0';
569                         while (*prog >= '0' && *prog <= '7')
570                           c = c * 8 + *prog++ - '0';
571                       }
572                       break;
573                     case 'x':
574                     case 'X':
575                       {
576                         c = 0;
577                         while (isxdigit ((unsigned char) *prog))
578                           {
579                             c *= 16;
580                             if (isdigit ((unsigned char) *prog))
581                               c += *prog - '0';
582                             else
583                               c += (tolower ((unsigned char) (*prog))
584                                     - 'a' + 10);
585                             prog++;
586                           }
587                       }
588                       break;
589                     default:
590                       msg (IS, _("Syntax error in string constant."));
591                     }
592                   ds_putchar (&op_tokstr, (unsigned char) c);
593                 }
594             }
595           prog++;
596         }
597       else
598         while (*prog && !isspace ((unsigned char) *prog) && *prog != '=')
599           ds_putchar (&op_tokstr, *prog++);
600       op_token = 'a';
601     }
602
603   return 1;
604 }
605
606 /* Applies the user-specified options in string S to output driver D
607    (at configuration time). */
608 static void
609 parse_options (char *s, struct outp_driver * d)
610 {
611   prog = s;
612   op_token = -1;
613
614   ds_init (NULL, &op_tokstr, 64);
615   while (tokener ())
616     {
617       char key[65];
618
619       if (op_token != 'a')
620         {
621           msg (IS, _("Syntax error in options."));
622           break;
623         }
624
625       ds_truncate (&op_tokstr, 64);
626       strcpy (key, ds_value (&op_tokstr));
627
628       tokener ();
629       if (op_token != '=')
630         {
631           msg (IS, _("Syntax error in options (`=' expected)."));
632           break;
633         }
634
635       tokener ();
636       if (op_token != 'a')
637         {
638           msg (IS, _("Syntax error in options (value expected after `=')."));
639           break;
640         }
641       d->class->option (d, key, &op_tokstr);
642     }
643   ds_destroy (&op_tokstr);
644 }
645
646 /* Find the driver in outp_driver_list with name NAME. */
647 static struct outp_driver *
648 find_driver (char *name)
649 {
650   struct outp_driver *d;
651
652 #if GLOBAL_DEBUGGING
653   if (iterating_driver_list)
654     reentrancy ();
655 #endif
656   for (d = outp_driver_list; d; d = d->next)
657     if (!strcmp (d->name, name))
658       return d;
659   return NULL;
660 }
661
662 /* Tokenize string S into colon-separated fields, removing leading and
663    trailing whitespace on tokens.  Returns a pointer to the
664    null-terminated token, which is formed by setting a NUL character
665    into the string.  After the first call, subsequent calls should set
666    S to NULL.  CP should be consistent across calls.  Returns NULL
667    after all fields have been used up.
668
669    FIXME: Should ignore colons inside double quotes. */
670 static char *
671 colon_tokenize (char *s, char **cp)
672 {
673   char *token;
674   
675   if (!s)
676     {
677       s = *cp;
678       if (*s == 0)
679         return NULL;
680     }
681   token = s += strspn (s, " \t\v\r");
682   *cp = strchr (s, ':');
683   if (*cp == NULL)
684     s = *cp = strchr (s, 0);
685   else
686     s = (*cp)++;
687   while (s > token && strchr (" \t\v\r", s[-1]))
688     s--;
689   *s = 0;
690   return token;
691 }
692
693 /* String S is in format:
694    DRIVERNAME:CLASSNAME:DEVICETYPE:OPTIONS
695    Adds a driver to outp_driver_list pursuant to the specification
696    provided.  */
697 static void
698 configure_driver (char *s)
699 {
700   char *token, *cp;
701   struct outp_driver *d = NULL, *iter;
702   struct outp_driver_class_list *c = NULL;
703
704   s = fn_interp_vars (s, find_defn_value);
705
706   /* Driver name. */
707   token = colon_tokenize (s, &cp);
708   if (!token)
709     {
710       msg (IS, _("Driver name expected."));
711       goto error;
712     }
713
714   d = xmalloc (sizeof *d);
715
716   d->class = NULL;
717   d->name = xstrdup (token);
718   d->driver_open = 0;
719   d->page_open = 0;
720
721   d->next = d->prev = NULL;
722
723   d->device = OUTP_DEV_NONE;
724   
725   d->ext = NULL;
726
727   /* Class name. */
728   token = colon_tokenize (NULL, &cp);
729   if (!token)
730     {
731       msg (IS, _("Class name expected."));
732       goto error;
733     }
734
735   for (c = outp_class_list; c; c = c->next)
736     if (!strcmp (c->class->name, token))
737       break;
738   if (!c)
739     {
740       msg (IS, _("Unknown output driver class `%s'."), token);
741       goto error;
742     }
743   
744   d->class = c->class;
745   if (!c->ref_count && !d->class->open_global (d->class))
746     {
747       msg (IS, _("Can't initialize output driver class `%s'."),
748            d->class->name);
749       goto error;
750     }
751   c->ref_count++;
752   if (!d->class->preopen_driver (d))
753     {
754       msg (IS, _("Can't initialize output driver `%s' of class `%s'."),
755            d->name, d->class->name);
756       goto error;
757     }
758
759   /* Device types. */
760   token = colon_tokenize (NULL, &cp);
761   if (token)
762     {
763       char *sp, *type;
764
765       for (type = strtok_r (token, " \t\r\v", &sp); type;
766            type = strtok_r (NULL, " \t\r\v", &sp))
767         {
768           if (!strcmp (type, "listing"))
769             d->device |= OUTP_DEV_LISTING;
770           else if (!strcmp (type, "screen"))
771             d->device |= OUTP_DEV_SCREEN;
772           else if (!strcmp (type, "printer"))
773             d->device |= OUTP_DEV_PRINTER;
774           else
775             {
776               msg (IS, _("Unknown device type `%s'."), type);
777               goto error;
778             }
779         }
780     }
781   
782   /* Options. */
783   token = colon_tokenize (NULL, &cp);
784   if (token)
785     parse_options (token, d);
786   if (!d->class->postopen_driver (d))
787     {
788       msg (IS, _("Can't complete initialization of output driver `%s' of "
789            "class `%s'."), d->name, d->class->name);
790       goto error;
791     }
792
793   /* Find like-named driver and delete. */
794   iter = find_driver (d->name);
795   if (iter)
796     destroy_driver (iter);
797
798   /* Add to list. */
799   d->next = outp_driver_list;
800   d->prev = NULL;
801   if (outp_driver_list)
802     outp_driver_list->prev = d;
803   outp_driver_list = d;
804   goto exit;
805
806 error:
807   if (d)
808     destroy_driver (d);
809 exit:
810   free (s);
811 }
812
813 /* Destroys output driver D. */
814 static void
815 destroy_driver (struct outp_driver *d)
816 {
817   if (d->page_open)
818     d->class->close_page (d);
819   if (d->class)
820     {
821       struct outp_driver_class_list *c;
822
823       if (d->driver_open)
824         d->class->close_driver (d);
825
826       for (c = outp_class_list; c; c = c->next)
827         if (c->class == d->class)
828           break;
829       assert (c != NULL);
830       
831       c->ref_count--;
832       if (c->ref_count == 0)
833         {
834           if (!d->class->close_global (d->class))
835             msg (IS, _("Can't deinitialize output driver class `%s'."),
836                  d->class->name);
837         }
838     }
839   free (d->name);
840
841   /* Remove this driver from the global driver list. */
842   if (d->prev)
843     d->prev->next = d->next;
844   if (d->next)
845     d->next->prev = d->prev;
846   if (d == outp_driver_list)
847     outp_driver_list = d->next;
848 }
849
850 static int
851 option_cmp (const void *a, const void *b)
852 {
853   const struct outp_option *o1 = a;
854   const struct outp_option *o2 = b;
855   return strcmp (o1->keyword, o2->keyword);
856 }
857
858 /* Tries to match S as one of the keywords in TAB, with corresponding
859    information structure INFO.  Returns category code or 0 on failure;
860    if category code is negative then stores subcategory in *SUBCAT. */
861 int
862 outp_match_keyword (const char *s, struct outp_option *tab,
863                     struct outp_option_info *info, int *subcat)
864 {
865   char *cp;
866   struct outp_option *oip;
867
868   /* Form hash table. */
869   if (NULL == info->initial)
870     {
871       /* Count items. */
872       int count, i;
873       char s[256], *cp;
874       struct outp_option *ptr[255], **oip;
875
876       for (count = 0; tab[count].keyword[0]; count++)
877         ;
878
879       /* Sort items. */
880       qsort (tab, count, sizeof *tab, option_cmp);
881
882       cp = s;
883       oip = ptr;
884       *cp = tab[0].keyword[0];
885       *oip++ = &tab[0];
886       for (i = 0; i < count; i++)
887         if (tab[i].keyword[0] != *cp)
888           {
889             *++cp = tab[i].keyword[0];
890             *oip++ = &tab[i];
891           }
892       *++cp = 0;
893
894       info->initial = xstrdup (s);
895       info->options = xmalloc (sizeof *info->options * (cp - s));
896       memcpy (info->options, ptr, sizeof *info->options * (cp - s));
897     }
898
899   cp = info->initial;
900   oip = *info->options;
901
902   if (s[0] == 0)
903     return 0;
904   cp = strchr (info->initial, s[0]);
905   if (!cp)
906     return 0;
907 #if 0
908   printf (_("Trying to find keyword `%s'...\n"), s);
909 #endif
910   oip = info->options[cp - info->initial];
911   while (oip->keyword[0] == s[0])
912     {
913 #if 0
914       printf ("- %s\n", oip->keyword);
915 #endif
916       if (!strcmp (s, oip->keyword))
917         {
918           if (oip->cat < 0)
919             *subcat = oip->subcat;
920           return oip->cat;
921         }
922       oip++;
923     }
924
925   return 0;
926 }
927
928 /* Encapsulate two characters in a single int. */
929 #define TWO_CHARS(A, B)                         \
930         ((A) + ((B)<<8))
931
932 /* Determines the size of a dimensional measurement and returns the
933    size in units of 1/72000".  Units if not specified explicitly are
934    inches for values under 50, millimeters otherwise.  Returns 0,
935    stores NULL to *TAIL on error; otherwise returns dimension, stores
936    address of next */
937 int
938 outp_evaluate_dimension (char *dimen, char **tail)
939 {
940   char *s = dimen;
941   char *ptail;
942   double value;
943
944   value = strtod (s, &ptail);
945   if (ptail == s)
946     goto lossage;
947   if (*ptail == '-')
948     {
949       double b, c;
950       s = &ptail[1];
951       b = strtod (s, &ptail);
952       if (b <= 0.0 || ptail == s)
953         goto lossage;
954       if (*ptail != '/')
955         goto lossage;
956       s = &ptail[1];
957       c = strtod (s, &ptail);
958       if (c <= 0.0 || ptail == s)
959         goto lossage;
960       s = ptail;
961       if (c == 0.0)
962         goto lossage;
963       if (value > 0)
964         value += b / c;
965       else
966         value -= b / c;
967     }
968   else if (*ptail == '/')
969     {
970       double b;
971       s = &ptail[1];
972       b = strtod (s, &ptail);
973       if (b <= 0.0 || ptail == s)
974         goto lossage;
975       s = ptail;
976       value /= b;
977     }
978   else
979     s = ptail;
980   if (*s == 0 || isspace ((unsigned char) *s))
981     {
982       if (value < 50.0)
983         value *= 72000;
984       else
985         value *= 72000 / 25.4;
986     }
987   else
988     {
989       double factor;
990
991       /* Standard TeX units are supported. */
992       if (*s == '"')
993         factor = 72000, s++;
994       else
995         switch (TWO_CHARS (s[0], s[1]))
996           {
997           case TWO_CHARS ('p', 't'):
998             factor = 72000 / 72.27;
999             break;
1000           case TWO_CHARS ('p', 'c'):
1001             factor = 72000 / 72.27 * 12.0;
1002             break;
1003           case TWO_CHARS ('i', 'n'):
1004             factor = 72000;
1005             break;
1006           case TWO_CHARS ('b', 'p'):
1007             factor = 72000 / 72.0;
1008             break;
1009           case TWO_CHARS ('c', 'm'):
1010             factor = 72000 / 2.54;
1011             break;
1012           case TWO_CHARS ('m', 'm'):
1013             factor = 72000 / 25.4;
1014             break;
1015           case TWO_CHARS ('d', 'd'):
1016             factor = 72000 / 72.27 * 1.0700086;
1017             break;
1018           case TWO_CHARS ('c', 'c'):
1019             factor = 72000 / 72.27 * 12.840104;
1020             break;
1021           case TWO_CHARS ('s', 'p'):
1022             factor = 72000 / 72.27 / 65536.0;
1023             break;
1024           default:
1025             msg (SE, _("Unit \"%s\" is unknown in dimension \"%s\"."), s, dimen);
1026             *tail = NULL;
1027             return 0;
1028           }
1029       ptail += 2;
1030       value *= factor;
1031     }
1032   if (value <= 0.0)
1033     goto lossage;
1034   if (tail)
1035     *tail = ptail;
1036   return value + 0.5;
1037
1038 lossage:
1039   *tail = NULL;
1040   msg (SE, _("Bad dimension \"%s\"."), dimen);
1041   return 0;
1042 }
1043
1044 /* Stores the dimensions in 1/72000" units of paper identified by
1045    SIZE, which is of form `HORZ x VERT' or `HORZ by VERT' where each
1046    of HORZ and VERT are dimensions, into *H and *V.  Return nonzero on
1047    success. */
1048 static int
1049 internal_get_paper_size (char *size, int *h, int *v)
1050 {
1051   char *tail;
1052
1053   while (isspace ((unsigned char) *size))
1054     size++;
1055   *h = outp_evaluate_dimension (size, &tail);
1056   if (tail == NULL)
1057     return 0;
1058   while (isspace ((unsigned char) *tail))
1059     tail++;
1060   if (*tail == 'x')
1061     tail++;
1062   else if (*tail == 'b' && tail[1] == 'y')
1063     tail += 2;
1064   else
1065     {
1066       msg (SE, _("`x' expected in paper size `%s'."), size);
1067       return 0;
1068     }
1069   *v = outp_evaluate_dimension (tail, &tail);
1070   if (tail == NULL)
1071     return 0;
1072   while (isspace ((unsigned char) *tail))
1073     tail++;
1074   if (*tail)
1075     {
1076       msg (SE, _("Trailing garbage `%s' on paper size `%s'."), tail, size);
1077       return 0;
1078     }
1079   
1080   return 1;
1081 }
1082
1083 /* Stores the dimensions, in 1/72000" units, of paper identified by
1084    SIZE into *H and *V.  SIZE may be a pair of dimensions of form `H x
1085    V', or it may be a case-insensitive paper identifier, which is
1086    looked up in the `papersize' configuration file.  Returns nonzero
1087    on success.  May modify SIZE. */
1088 /* Don't read further unless you've got a strong stomach. */
1089 int
1090 outp_get_paper_size (char *size, int *h, int *v)
1091 {
1092   struct paper_size
1093     {
1094       char *name;
1095       int use;
1096       int h, v;
1097     };
1098
1099   static struct paper_size cache[4];
1100   static int use;
1101
1102   FILE *f;
1103   char *pprsz_fn;
1104
1105   struct string line;
1106   struct file_locator where;
1107
1108   int free_it = 0;
1109   int result = 0;
1110   int min_value, min_index;
1111   char *ep;
1112   int i;
1113
1114   while (isspace ((unsigned char) *size))
1115     size++;
1116   if (isdigit ((unsigned char) *size))
1117     return internal_get_paper_size (size, h, v);
1118   ep = size;
1119   while (*ep)
1120     ep++;
1121   while (isspace ((unsigned char) *ep) && ep >= size)
1122     ep--;
1123   if (ep == size)
1124     {
1125       msg (SE, _("Paper size name must not be empty."));
1126       return 0;
1127     }
1128   
1129   ep++;
1130   if (*ep)
1131     *ep = 0;
1132
1133   use++;
1134   for (i = 0; i < 4; i++)
1135     if (cache[i].name != NULL && !strcasecmp (cache[i].name, size))
1136       {
1137         *h = cache[i].h;
1138         *v = cache[i].v;
1139         cache[i].use = use;
1140         return 1;
1141       }
1142
1143   pprsz_fn = fn_search_path (fn_getenv_default ("STAT_OUTPUT_PAPERSIZE_FILE",
1144                                                 "papersize"),
1145                              fn_getenv_default ("STAT_OUTPUT_INIT_PATH",
1146                                                 config_path),
1147                              NULL);
1148
1149   where.filename = pprsz_fn;
1150   where.line_number = 0;
1151   err_push_file_locator (&where);
1152   ds_init (NULL, &line, 128);
1153
1154   if (pprsz_fn == NULL)
1155     {
1156       msg (IE, _("Cannot find `papersize' configuration file."));
1157       goto exit;
1158     }
1159
1160   msg (VM (1), _("%s: Opening paper size definition file..."), pprsz_fn);
1161   f = fopen (pprsz_fn, "r");
1162   if (!f)
1163     {
1164       msg (IE, _("Opening %s: %s."), pprsz_fn, strerror (errno));
1165       goto exit;
1166     }
1167
1168   for (;;)
1169     {
1170       char *cp, *bp, *ep;
1171
1172       if (!ds_get_config_line (f, &line, &where))
1173         {
1174           if (ferror (f))
1175             msg (ME, _("Reading %s: %s."), pprsz_fn, strerror (errno));
1176           break;
1177         }
1178       for (cp = ds_value (&line); isspace ((unsigned char) *cp); cp++);
1179       if (*cp == 0)
1180         continue;
1181       if (*cp != '"')
1182         goto lex_error;
1183       for (bp = ep = cp + 1; *ep && *ep != '"'; ep++);
1184       if (!*ep)
1185         goto lex_error;
1186       *ep = 0;
1187       if (0 != strcasecmp (bp, size))
1188         continue;
1189
1190       for (cp = ep + 1; isspace ((unsigned char) *cp); cp++);
1191       if (*cp == '=')
1192         {
1193           size = xmalloc (ep - bp + 1);
1194           strcpy (size, bp);
1195           free_it = 1;
1196           continue;
1197         }
1198       size = &ep[1];
1199       break;
1200
1201     lex_error:
1202       msg (IE, _("Syntax error in paper size definition."));
1203     }
1204
1205   /* We found the one we want! */
1206   result = internal_get_paper_size (size, h, v);
1207   if (result)
1208     {
1209       min_value = cache[0].use;
1210       min_index = 0;
1211       for (i = 1; i < 4; i++)
1212         if (cache[0].use < min_value)
1213           {
1214             min_value = cache[i].use;
1215             min_index = i;
1216           }
1217       free (cache[min_index].name);
1218       cache[min_index].name = xstrdup (size);
1219       cache[min_index].use = use;
1220       cache[min_index].h = *h;
1221       cache[min_index].v = *v;
1222     }
1223
1224 exit:
1225   err_pop_file_locator (&where);
1226   ds_destroy (&line);
1227   if (free_it)
1228     free (size);
1229
1230   if (result)
1231     msg (VM (2), _("Paper size definition file read successfully."));
1232   else
1233     msg (VM (1), _("Error reading paper size definition file."));
1234   
1235   return result;
1236 }
1237
1238 /* If D is NULL, returns the first enabled driver if any, NULL if
1239    none.  Otherwise D must be the last driver returned by this
1240    function, in which case the next enabled driver is returned or NULL
1241    if that was the last. */
1242 struct outp_driver *
1243 outp_drivers (struct outp_driver *d)
1244 {
1245 #if GLOBAL_DEBUGGING
1246   struct outp_driver *orig_d = d;
1247 #endif
1248
1249   for (;;)
1250     {
1251       if (d == NULL)
1252         d = outp_driver_list;
1253       else
1254         d = d->next;
1255
1256       if (d == NULL
1257           || (d->driver_open
1258               && (d->device == 0
1259                   || (d->device & disabled_devices) != d->device)))
1260         break;
1261     }
1262
1263 #if GLOBAL_DEBUGGING
1264   if (d && !orig_d)
1265     {
1266       if (iterating_driver_list++)
1267         reentrancy ();
1268     }
1269   else if (orig_d && !d)
1270     {
1271       assert (iterating_driver_list == 1);
1272       iterating_driver_list = 0;
1273     }
1274 #endif
1275
1276   return d;
1277 }
1278
1279 /* Enables (if ENABLE is nonzero) or disables (if ENABLE is zero) the
1280    device(s) given in mask DEVICE. */
1281 void
1282 outp_enable_device (int enable, int device)
1283 {
1284   if (enable)
1285     disabled_devices &= ~device;
1286   else
1287     disabled_devices |= device;
1288 }
1289
1290 /* Ejects the paper on device D, if the page is not blank. */
1291 int
1292 outp_eject_page (struct outp_driver *d)
1293 {
1294   if (d->page_open == 0)
1295     return 1;
1296   
1297   if (d->cp_y != 0)
1298     {
1299       d->cp_x = d->cp_y = 0;
1300
1301       if (d->class->close_page (d) == 0)
1302         msg (ME, _("Error closing page on %s device of %s class."),
1303              d->name, d->class->name);
1304       if (d->class->open_page (d) == 0)
1305         {
1306           msg (ME, _("Error opening page on %s device of %s class."),
1307                d->name, d->class->name);
1308           return 0;
1309         }
1310     }
1311   return 1;
1312 }
1313
1314 /* Returns the width of string S, in device units, when output on
1315    device D. */
1316 int
1317 outp_string_width (struct outp_driver *d, const char *s)
1318 {
1319   struct outp_text text;
1320
1321   text.options = OUTP_T_JUST_LEFT;
1322   ls_init (&text.s, (char *) s, strlen (s));
1323   d->class->text_metrics (d, &text);
1324
1325   return text.h;
1326 }