Allow "1+23" even for F format, for compatibility.
[pspp-builds.git] / src / data-in.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 #include <config.h>
21 #include "data-in.h"
22 #include "error.h"
23 #include <math.h>
24 #include <ctype.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include "bool.h"
30 #include "error.h"
31 #include "getline.h"
32 #include "calendar.h"
33 #include "lexer.h"
34 #include "magic.h"
35 #include "misc.h"
36 #include "settings.h"
37 #include "str.h"
38 #include "var.h"
39 \f
40 #include "debug-print.h"
41
42 \f
43 /* Specialized error routine. */
44
45 static void dls_error (const struct data_in *, const char *format, ...)
46      PRINTF_FORMAT (2, 3);
47
48 static void
49 vdls_error (const struct data_in *i, const char *format, va_list args)
50 {
51   struct error e;
52   struct string title;
53
54   if (i->flags & DI_IGNORE_ERROR)
55     return;
56
57   ds_init (&title, 64);
58   if (!getl_reading_script)
59     ds_puts (&title, _("data-file error: "));
60   if (i->f1 == i->f2)
61     ds_printf (&title, _("(column %d"), i->f1);
62   else
63     ds_printf (&title, _("(columns %d-%d"), i->f1, i->f2);
64   ds_printf (&title, _(", field type %s) "), fmt_to_string (&i->format));
65     
66   e.class = DE;
67   err_location (&e.where);
68   e.title = ds_c_str (&title);
69
70   err_vmsg (&e, format, args);
71
72   ds_destroy (&title);
73 }
74
75 static void
76 dls_error (const struct data_in *i, const char *format, ...) 
77 {
78   va_list args;
79
80   va_start (args, format);
81   vdls_error (i, format, args);
82   va_end (args);
83 }
84 \f
85 /* Parsing utility functions. */
86
87 /* Excludes leading and trailing whitespace from I by adjusting
88    pointers. */
89 static void
90 trim_whitespace (struct data_in *i)
91 {
92   while (i->s < i->e && isspace (i->s[0])) 
93     i->s++;
94
95   while (i->s < i->e && isspace (i->e[-1]))
96     i->e--;
97 }
98
99 /* Returns nonzero if we're not at the end of the string being
100    parsed. */
101 static inline bool
102 have_char (struct data_in *i)
103 {
104   return i->s < i->e;
105 }
106
107 /* If implied decimal places are enabled, apply them to
108    I->v->f. */
109 static void
110 apply_implied_decimals (struct data_in *i) 
111 {
112   if ((i->flags & DI_IMPLIED_DECIMALS) && i->format.d > 0)
113     i->v->f /= pow (10., i->format.d);
114 }
115 \f
116 /* Format parsers. */ 
117
118 static bool parse_int (struct data_in *i, long *result);
119
120 /* This function is based on strtod() from the GNU C library. */
121 static bool
122 parse_numeric (struct data_in *i)
123 {
124   int sign;                     /* +1 or -1. */
125   double num;                   /* The number so far.  */
126
127   bool got_dot;                 /* Found a decimal point.  */
128   size_t digit_cnt;             /* Count of digits.  */
129
130   int decimal;                  /* Decimal point character. */
131   int grouping;                 /* Grouping character. */
132
133   long int exponent;            /* Number's exponent. */
134   int type;                     /* Usually same as i->format.type. */
135
136   trim_whitespace (i);
137
138   type = i->format.type;
139   if (type == FMT_DOLLAR && have_char (i) && *i->s == '$')
140     {
141       i->s++;
142       type = FMT_COMMA;
143     }
144
145   /* Get the sign.  */
146   if (have_char (i))
147     {
148       sign = *i->s == '-' ? -1 : 1;
149       if (*i->s == '-' || *i->s == '+')
150         i->s++;
151     }
152   else
153     sign = 1;
154   
155   if (type != FMT_DOT)
156     {
157       decimal = get_decimal();
158       grouping = get_grouping();
159     }
160   else
161     {
162       decimal = get_grouping();
163       grouping = get_decimal();
164     }
165
166   i->v->f = SYSMIS;
167   num = 0.0;
168   got_dot = false;
169   digit_cnt = 0;
170   exponent = 0;
171   for (; have_char (i); i->s++)
172     {
173       if (isdigit (*i->s))
174         {
175           digit_cnt++;
176
177           /* Make sure that multiplication by 10 will not overflow.  */
178           if (num > DBL_MAX * 0.1)
179             /* The value of the digit doesn't matter, since we have already
180                gotten as many digits as can be represented in a `double'.
181                This doesn't necessarily mean the result will overflow.
182                The exponent may reduce it to within range.
183
184                We just need to record that there was another
185                digit so that we can multiply by 10 later.  */
186             ++exponent;
187           else
188             num = (num * 10.0) + (*i->s - '0');
189
190           /* Keep track of the number of digits after the decimal point.
191              If we just divided by 10 here, we would lose precision.  */
192           if (got_dot)
193             --exponent;
194         }
195       else if (!got_dot && *i->s == decimal)
196         /* Record that we have found the decimal point.  */
197         got_dot = true;
198       else if ((type != FMT_COMMA && type != FMT_DOT) || *i->s != grouping)
199         /* Any other character terminates the number.  */
200         break;
201     }
202
203   if (!digit_cnt)
204     {
205       if (got_dot)
206         {
207           i->v->f = SYSMIS;
208           return true;
209         }
210       dls_error (i, _("Field does not form a valid floating-point constant."));
211       i->v->f = SYSMIS;
212       return false;
213     }
214   
215   if (have_char (i) && strchr ("eEdD-+", *i->s))
216     {
217       /* Get the exponent specified after the `e' or `E'.  */
218       long exp;
219
220       if (isalpha (*i->s))
221         i->s++;
222       if (!parse_int (i, &exp))
223         {
224           i->v->f = SYSMIS;
225           return false;
226         }
227
228       exponent += exp;
229     }
230   else if (!got_dot && (i->flags & DI_IMPLIED_DECIMALS))
231     exponent -= i->format.d;
232
233   if (type == FMT_PCT && have_char (i) && *i->s == '%')
234     i->s++;
235   if (i->s < i->e)
236     {
237       dls_error (i, _("Field contents followed by garbage."));
238       i->v->f = SYSMIS;
239       return false;
240     }
241
242   if (num == 0.0)
243     {
244       i->v->f = 0.0;
245       return true;
246     }
247
248   /* Multiply NUM by 10 to the EXPONENT power, checking for overflow
249      and underflow.  */
250   if (exponent < 0)
251     {
252       if (-exponent + digit_cnt > -(DBL_MIN_10_EXP) + 5
253           || num < DBL_MIN * pow (10.0, (double) -exponent)) 
254         {
255           dls_error (i, _("Underflow in floating-point constant."));
256           i->v->f = 0.0;
257           return false;
258         }
259
260       num *= pow (10.0, (double) exponent);
261     }
262   else if (exponent > 0)
263     {
264       if (num > DBL_MAX * pow (10.0, (double) -exponent))
265         {
266           dls_error (i, _("Overflow in floating-point constant."));
267           i->v->f = SYSMIS;
268           return false;
269         }
270       
271       num *= pow (10.0, (double) exponent);
272     }
273
274   i->v->f = sign > 0 ? num : -num;
275   return true;
276 }
277
278 /* Returns the integer value of hex digit C. */
279 static inline int
280 hexit_value (int c)
281 {
282   const char s[] = "0123456789abcdef";
283   const char *cp = strchr (s, tolower ((unsigned char) c));
284
285   assert (cp != NULL);
286   return cp - s;
287 }
288
289 static inline bool
290 parse_N (struct data_in *i)
291 {
292   const unsigned char *cp;
293
294   i->v->f = 0;
295   for (cp = i->s; cp < i->e; cp++)
296     {
297       if (!isdigit (*cp))
298         {
299           dls_error (i, _("All characters in field must be digits."));
300           return false;
301         }
302
303       i->v->f = i->v->f * 10.0 + *cp - '0';
304     }
305
306   apply_implied_decimals (i);
307   return true;
308 }
309
310 static inline bool
311 parse_PIBHEX (struct data_in *i)
312 {
313   double n;
314   const unsigned char *cp;
315
316   trim_whitespace (i);
317
318   n = 0.0;
319   for (cp = i->s; cp < i->e; cp++)
320     {
321       if (!isxdigit (*cp))
322         {
323           dls_error (i, _("Unrecognized character in field."));
324           return false;
325         }
326
327       n = n * 16.0 + hexit_value (*cp);
328     }
329   
330   i->v->f = n;
331   return true;
332 }
333
334 static inline bool
335 parse_RBHEX (struct data_in *i)
336 {
337   /* Validate input. */
338   trim_whitespace (i);
339   if ((i->e - i->s) % 2)
340     {
341       dls_error (i, _("Field must have even length."));
342       return false;
343     }
344   
345   {
346     const unsigned char *cp;
347     
348     for (cp = i->s; cp < i->e; cp++)
349       if (!isxdigit (*cp))
350         {
351           dls_error (i, _("Field must contain only hex digits."));
352           return false;
353         }
354   }
355   
356   /* Parse input. */
357   {
358     union
359       {
360         double d;
361         unsigned char c[sizeof (double)];
362       }
363     u;
364
365     int j;
366
367     memset (u.c, 0, sizeof u.c);
368     for (j = 0; j < min ((i->e - i->s) / 2, sizeof u.d); j++)
369       u.c[j] = 16 * hexit_value (i->s[j * 2]) + hexit_value (i->s[j * 2 + 1]);
370
371     i->v->f = u.d;
372   }
373   
374   return true;
375 }
376
377 static inline bool
378 parse_Z (struct data_in *i)
379 {
380   char buf[64];
381   bool got_dot = false;
382
383   /* Warn user that we suck. */
384   {
385     static bool warned;
386
387     if (!warned)
388       {
389         msg (MW, 
390              _("Quality of zoned decimal (Z) input format code is "
391                "suspect.  Check your results three times. Report bugs "
392                 "to %s."),PACKAGE_BUGREPORT);
393         warned = true;
394       }
395   }
396
397   /* Validate input. */
398   trim_whitespace (i);
399
400   if (i->e - i->s < 2)
401     {
402       dls_error (i, _("Zoned decimal field contains fewer than 2 "
403                       "characters."));
404       return false;
405     }
406
407   /* Copy sign into buf[0]. */
408   if ((i->e[-1] & 0xc0) != 0xc0)
409     {
410       dls_error (i, _("Bad sign byte in zoned decimal number."));
411       return false;
412     }
413   buf[0] = (i->e[-1] ^ (i->e[-1] >> 1)) & 0x10 ? '-' : '+';
414
415   /* Copy digits into buf[1 ... len - 1] and terminate string. */
416   {
417     const unsigned char *sp;
418     char *dp;
419
420     for (sp = i->s, dp = buf + 1; sp < i->e - 1; sp++, dp++)
421       if (*sp == '.') 
422         {
423           *dp = '.';
424           got_dot = true;
425         }
426       else if ((*sp & 0xf0) == 0xf0 && (*sp & 0xf) < 10)
427         *dp = (*sp & 0xf) + '0';
428       else
429         {
430           dls_error (i, _("Format error in zoned decimal number."));
431           return false;
432         }
433
434     *dp = '\0';
435   }
436
437   /* Parse as number. */
438   {
439     char *tail;
440     
441     i->v->f = strtod ((char *) buf, (char **) &tail);
442     if ((unsigned char *) tail != i->e)
443       {
444         dls_error (i, _("Error in syntax of zoned decimal number."));
445         return false;
446       }
447   }
448
449   if (!got_dot)
450     apply_implied_decimals (i);
451
452   return true;
453 }
454
455 static inline bool
456 parse_IB (struct data_in *i)
457 {
458   char buf[64];
459   const char *p;
460
461   unsigned char xor;
462
463   /* We want the data to be in big-endian format.  If this is a
464      little-endian machine, reverse the byte order. */
465 #ifdef WORDS_BIGENDIAN
466   p = i->s;
467 #else
468   memcpy (buf, i->s, i->e - i->s);
469   buf_reverse (buf, i->e - i->s);
470   p = buf;
471 #endif
472
473   /* If the value is negative, we need to logical-NOT each value
474      before adding it. */
475   if (p[0] & 0x80)
476     xor = 0xff;
477   else
478     xor = 0x00;
479   
480   {
481     int j;
482
483     i->v->f = 0.0;
484     for (j = 0; j < i->e - i->s; j++)
485       i->v->f = i->v->f * 256.0 + (p[j] ^ xor);
486   }
487
488   /* If the value is negative, add 1 and set the sign, to complete a
489      two's-complement negation. */
490   if (p[0] & 0x80)
491     i->v->f = -(i->v->f + 1.0);
492
493   apply_implied_decimals (i);
494
495   return true;
496 }
497
498 static inline bool
499 parse_PIB (struct data_in *i)
500 {
501   int j;
502
503   i->v->f = 0.0;
504 #if WORDS_BIGENDIAN
505   for (j = 0; j < i->e - i->s; j++)
506     i->v->f = i->v->f * 256.0 + i->s[j];
507 #else
508   for (j = i->e - i->s - 1; j >= 0; j--)
509     i->v->f = i->v->f * 256.0 + i->s[j];
510 #endif
511
512   apply_implied_decimals (i);
513
514   return true;
515 }
516
517 static inline bool
518 parse_P (struct data_in *i)
519 {
520   const unsigned char *cp;
521
522   i->v->f = 0.0;
523   for (cp = i->s; cp < i->e - 1; cp++)
524     {
525       i->v->f = i->v->f * 10 + (*cp >> 4);
526       i->v->f = i->v->f * 10 + (*cp & 15);
527     }
528   i->v->f = i->v->f * 10 + (*cp >> 4);
529   if ((*cp ^ (*cp >> 1)) & 0x10)
530       i->v->f = -i->v->f;
531
532   apply_implied_decimals (i);
533
534   return true;
535 }
536
537 static inline bool
538 parse_PK (struct data_in *i)
539 {
540   const unsigned char *cp;
541
542   i->v->f = 0.0;
543   for (cp = i->s; cp < i->e; cp++)
544     {
545       i->v->f = i->v->f * 10 + (*cp >> 4);
546       i->v->f = i->v->f * 10 + (*cp & 15);
547     }
548
549   apply_implied_decimals (i);
550
551   return true;
552 }
553
554 static inline bool
555 parse_RB (struct data_in *i)
556 {
557   union
558     {
559       double d;
560       unsigned char c[sizeof (double)];
561     }
562   u;
563
564   memset (u.c, 0, sizeof u.c);
565   memcpy (u.c, i->s, min ((int) sizeof (u.c), i->e - i->s));
566   i->v->f = u.d;
567
568   return true;
569 }
570
571 static inline bool
572 parse_A (struct data_in *i)
573 {
574   ptrdiff_t len = i->e - i->s;
575   
576   if (len >= i->format.w)
577     memcpy (i->v->s, i->s, i->format.w);
578   else
579     {
580       memcpy (i->v->s, i->s, len);
581       memset (i->v->s + len, ' ', i->format.w - len);
582     }
583
584   return true;
585 }
586
587 static inline bool
588 parse_AHEX (struct data_in *i)
589 {
590   /* Validate input. */
591   trim_whitespace (i);
592   if ((i->e - i->s) % 2)
593     {
594       dls_error (i, _("Field must have even length."));
595       return false;
596     }
597
598   {
599     const unsigned char *cp;
600     
601     for (cp = i->s; cp < i->e; cp++)
602       if (!isxdigit (*cp))
603         {
604           dls_error (i, _("Field must contain only hex digits."));
605           return false;
606         }
607   }
608   
609   {
610     int j;
611     
612     /* Parse input. */
613     for (j = 0; j < min (i->e - i->s, i->format.w); j += 2)
614       i->v->s[j / 2] = hexit_value (i->s[j]) * 16 + hexit_value (i->s[j + 1]);
615     memset (i->v->s + (i->e - i->s) / 2, ' ', (i->format.w - (i->e - i->s)) / 2);
616   }
617   
618   return true;
619 }
620 \f
621 /* Date & time format components. */
622
623 /* Advances *CP past any whitespace characters. */
624 static inline void
625 skip_whitespace (struct data_in *i)
626 {
627   while (isspace ((unsigned char) *i->s))
628     i->s++;
629 }
630
631 static inline bool
632 parse_leader (struct data_in *i)
633 {
634   skip_whitespace (i);
635   return true;
636 }
637
638 static inline bool
639 force_have_char (struct data_in *i)
640 {
641   if (have_char (i))
642     return true;
643
644   dls_error (i, _("Unexpected end of field."));
645   return false;
646 }
647
648 static bool
649 parse_int (struct data_in *i, long *result)
650 {
651   bool negative = false;
652   
653   if (!force_have_char (i))
654     return false;
655
656   if (*i->s == '+')
657     {
658       i->s++;
659       force_have_char (i);
660     }
661   else if (*i->s == '-')
662     {
663       negative = true;
664       i->s++;
665       force_have_char (i);
666     }
667   
668   if (!isdigit (*i->s))
669     {
670       dls_error (i, _("Digit expected in field."));
671       return false;
672     }
673
674   *result = 0;
675   for (;;)
676     {
677       *result = *result * 10 + *i->s++ - '0';
678       if (!have_char (i) || !isdigit (*i->s))
679         break;
680     }
681
682   if (negative)
683     *result = -*result;
684   return true;
685 }
686
687 static bool
688 parse_day (struct data_in *i, long *day)
689 {
690   if (!parse_int (i, day))
691     return false;
692   if (*day >= 1 && *day <= 31)
693     return true;
694
695   dls_error (i, _("Day (%ld) must be between 1 and 31."), *day);
696   return false;
697 }
698
699 static bool
700 parse_day_count (struct data_in *i, long *day_count)
701 {
702   return parse_int (i, day_count);
703 }
704
705 static bool
706 parse_date_delimiter (struct data_in *i)
707 {
708   bool delim = false;
709
710   while (have_char (i)
711          && (*i->s == '-' || *i->s == '/' || isspace (*i->s)
712              || *i->s == '.' || *i->s == ','))
713     {
714       delim = true;
715       i->s++;
716     }
717   if (delim)
718     return true;
719
720   dls_error (i, _("Delimiter expected between fields in date."));
721   return false;
722 }
723
724 /* Association between a name and a value. */
725 struct enum_name
726   {
727     const char *name;           /* Name. */
728     bool can_abbreviate;        /* True if name may be abbreviated. */
729     int value;                  /* Value associated with name. */
730   };
731
732 /* Reads a name from I and sets *OUTPUT to the value associated
733    with that name.  Returns true if successful, false otherwise. */
734 static bool
735 parse_enum (struct data_in *i, const char *what,
736             const struct enum_name *enum_names,
737             long *output) 
738 {
739   const char *name;
740   size_t length;
741   const struct enum_name *ep;
742
743   /* Consume alphabetic characters. */
744   name = i->s;
745   length = 0;
746   while (have_char (i) && isalpha (*i->s)) 
747     {
748       length++;
749       i->s++; 
750     }
751   if (length == 0) 
752     {
753       dls_error (i, _("Parse error at `%c' expecting %s."), *i->s, what);
754       return false;
755     }
756
757   for (ep = enum_names; ep->name != NULL; ep++)
758     if ((ep->can_abbreviate
759          && lex_id_match_len (ep->name, strlen (ep->name), name, length))
760         || (!ep->can_abbreviate && length == strlen (ep->name)
761             && !buf_compare_case (name, ep->name, length)))
762       {
763         *output = ep->value;
764         return true;
765       }
766
767   dls_error (i, _("Unknown %s `%.*s'."), what, (int) length, name);
768   return false;
769 }
770
771 static bool
772 parse_month (struct data_in *i, long *month)
773 {
774   static const struct enum_name month_names[] = 
775     {
776       {"january", true, 1},
777       {"february", true, 2},
778       {"march", true, 3},
779       {"april", true, 4},
780       {"may", true, 5},
781       {"june", true, 6},
782       {"july", true, 7},
783       {"august", true, 8},
784       {"september", true, 9},
785       {"october", true, 10},
786       {"november", true, 11},
787       {"december", true, 12},
788
789       {"i", false, 1},
790       {"ii", false, 2},
791       {"iii", false, 3},
792       {"iv", false, 4},
793       {"iiii", false, 4},
794       {"v", false, 5},
795       {"vi", false, 6},
796       {"vii", false, 7},
797       {"viii", false, 8},
798       {"ix", false, 9},
799       {"viiii", false, 9},
800       {"x", false, 10},
801       {"xi", false, 11},
802       {"xii", false, 12},
803
804       {NULL, false, 0},
805     };
806
807   if (!force_have_char (i))
808     return false;
809   
810   if (isdigit (*i->s))
811     {
812       if (!parse_int (i, month))
813         return false;
814       if (*month >= 1 && *month <= 12)
815         return true;
816       
817       dls_error (i, _("Month (%ld) must be between 1 and 12."), *month);
818       return false;
819     }
820   else 
821     return parse_enum (i, _("month"), month_names, month);
822 }
823
824 static bool
825 parse_year (struct data_in *i, long *year)
826 {
827   if (!parse_int (i, year))
828     return false;
829   
830   if (*year >= 0 && *year <= 199)
831     *year += 1900;
832   if (*year >= 1582 || *year <= 19999)
833     return true;
834
835   dls_error (i, _("Year (%ld) must be between 1582 and 19999."), *year);
836   return false;
837 }
838
839 static bool
840 parse_trailer (struct data_in *i)
841 {
842   skip_whitespace (i);
843   if (!have_char (i))
844     return true;
845   
846   dls_error (i, _("Trailing garbage \"%s\" following date."), i->s);
847   return false;
848 }
849
850 static bool
851 parse_julian (struct data_in *i, long *julian)
852 {
853   if (!parse_int (i, julian))
854     return false;
855    
856   {
857     int day = *julian % 1000;
858
859     if (day < 1 || day > 366)
860       {
861         dls_error (i, _("Julian day (%d) must be between 1 and 366."), day);
862         return false;
863       }
864   }
865   
866   {
867     int year = *julian / 1000;
868
869     if (year >= 0 && year <= 199)
870       *julian += 1900000L;
871     else if (year < 1582 || year > 19999)
872       {
873         dls_error (i, _("Year (%d) must be between 1582 and 19999."), year);
874         return false;
875       }
876   }
877
878   return true;
879 }
880
881 static bool
882 parse_quarter (struct data_in *i, long *quarter)
883 {
884   if (!parse_int (i, quarter))
885     return false;
886   if (*quarter >= 1 && *quarter <= 4)
887     return true;
888
889   dls_error (i, _("Quarter (%ld) must be between 1 and 4."), *quarter);
890   return false;
891 }
892
893 static bool
894 parse_q_delimiter (struct data_in *i)
895 {
896   skip_whitespace (i);
897   if (!have_char (i) || tolower (*i->s) != 'q')
898     {
899       dls_error (i, _("`Q' expected between quarter and year."));
900       return false;
901     }
902   i->s++;
903   skip_whitespace (i);
904   return true;
905 }
906
907 static bool
908 parse_week (struct data_in *i, long *week)
909 {
910   if (!parse_int (i, week))
911     return false;
912   if (*week >= 1 && *week <= 53)
913     return true;
914
915   dls_error (i, _("Week (%ld) must be between 1 and 53."), *week);
916   return false;
917 }
918
919 static bool
920 parse_wk_delimiter (struct data_in *i)
921 {
922   skip_whitespace (i);
923   if (i->s + 1 >= i->e
924       || tolower (i->s[0]) != 'w' || tolower (i->s[1]) != 'k')
925     {
926       dls_error (i, _("`WK' expected between week and year."));
927       return false;
928     }
929   i->s += 2;
930   skip_whitespace (i);
931   return true;
932 }
933
934 static bool
935 parse_time_delimiter (struct data_in *i)
936 {
937   bool delim = false;
938
939   while (have_char (i) && (*i->s == ':' || *i->s == '.' || isspace (*i->s)))
940     {
941       delim = true;
942       i->s++;
943     }
944
945   if (delim)
946     return true;
947   
948   dls_error (i, _("Delimiter expected between fields in time."));
949   return false;
950 }
951
952 static bool
953 parse_hour (struct data_in *i, long *hour)
954 {
955   if (!parse_int (i, hour))
956     return false;
957   if (*hour >= 0)
958     return true;
959   
960   dls_error (i, _("Hour (%ld) must be positive."), *hour);
961   return false;
962 }
963
964 static bool
965 parse_minute (struct data_in *i, long *minute)
966 {
967   if (!parse_int (i, minute))
968     return false;
969   if (*minute >= 0 && *minute <= 59)
970     return true;
971   
972   dls_error (i, _("Minute (%ld) must be between 0 and 59."), *minute);
973   return false;
974 }
975
976 static bool
977 parse_opt_second (struct data_in *i, double *second)
978 {
979   bool delim = false;
980
981   char buf[64];
982   char *cp;
983
984   while (have_char (i)
985          && (*i->s == ':' || *i->s == '.' || isspace (*i->s)))
986     {
987       delim = true;
988       i->s++;
989     }
990   
991   if (!delim || !isdigit (*i->s))
992     {
993       *second = 0.0;
994       return true;
995     }
996
997   cp = buf;
998   while (have_char (i) && isdigit (*i->s))
999     *cp++ = *i->s++;
1000   if (have_char (i) && *i->s == '.')
1001     *cp++ = *i->s++;
1002   while (have_char (i) && isdigit (*i->s))
1003     *cp++ = *i->s++;
1004   *cp = '\0';
1005   
1006   *second = strtod (buf, NULL);
1007
1008   return true;
1009 }
1010
1011 static bool
1012 parse_hour24 (struct data_in *i, long *hour24)
1013 {
1014   if (!parse_int (i, hour24))
1015     return false;
1016   if (*hour24 >= 0 && *hour24 <= 23)
1017     return true;
1018   
1019   dls_error (i, _("Hour (%ld) must be between 0 and 23."), *hour24);
1020   return false;
1021 }
1022
1023      
1024 static bool
1025 parse_weekday (struct data_in *i, long *weekday)
1026 {
1027   static const struct enum_name weekday_names[] = 
1028     {
1029       {"sunday", true, 1},
1030       {"su", true, 1},
1031       {"monday", true, 2},
1032       {"mo", true, 2},
1033       {"tuesday", true, 3},
1034       {"tu", true, 3},
1035       {"wednesday", true, 4},
1036       {"we", true, 4},
1037       {"thursday", true, 5},
1038       {"th", true, 5},
1039       {"friday", true, 6},
1040       {"fr", true, 6},
1041       {"saturday", true, 7},
1042       {"sa", true, 7},
1043       
1044       {NULL, false, 0},
1045     };
1046
1047   return parse_enum (i, _("weekday"), weekday_names, weekday);
1048 }
1049
1050 static bool
1051 parse_spaces (struct data_in *i)
1052 {
1053   skip_whitespace (i);
1054   return true;
1055 }
1056
1057 static bool
1058 parse_sign (struct data_in *i, int *sign)
1059 {
1060   if (!force_have_char (i))
1061     return false;
1062
1063   switch (*i->s)
1064     {
1065     case '-':
1066       i->s++;
1067       *sign = -1;
1068       break;
1069
1070     case '+':
1071       i->s++;
1072       /* fall through */
1073
1074     default:
1075       *sign = 1;
1076       break;
1077     }
1078
1079   return true;
1080 }
1081 \f
1082 /* Date & time formats. */
1083
1084 static void
1085 calendar_error (void *i_, const char *format, ...) 
1086 {
1087   struct data_in *i = i_;
1088   va_list args;
1089
1090   va_start (args, format);
1091   vdls_error (i, format, args);
1092   va_end (args);
1093 }
1094
1095 static bool
1096 ymd_to_ofs (struct data_in *i, int year, int month, int day, double *ofs) 
1097 {
1098   *ofs = calendar_gregorian_to_offset (year, month, day, calendar_error, i);
1099   return *ofs != SYSMIS;
1100 }
1101
1102 static bool
1103 ymd_to_date (struct data_in *i, int year, int month, int day, double *date) 
1104 {
1105   if (ymd_to_ofs (i, year, month, day, date)) 
1106     {
1107       *date *= 60. * 60. * 24.;
1108       return true; 
1109     }
1110   else
1111     return false;
1112 }
1113
1114 static bool
1115 parse_DATE (struct data_in *i)
1116 {
1117   long day, month, year;
1118
1119   return (parse_leader (i)
1120           && parse_day (i, &day)
1121           && parse_date_delimiter (i)
1122           && parse_month (i, &month)
1123           && parse_date_delimiter (i)
1124           && parse_year (i, &year)
1125           && parse_trailer (i)
1126           && ymd_to_date (i, year, month, day, &i->v->f));
1127 }
1128
1129 static bool
1130 parse_ADATE (struct data_in *i)
1131 {
1132   long month, day, year;
1133
1134   return (parse_leader (i)
1135           && parse_month (i, &month)
1136           && parse_date_delimiter (i)
1137           && parse_day (i, &day)
1138           && parse_date_delimiter (i)
1139           && parse_year (i, &year)
1140           && parse_trailer (i)
1141           && ymd_to_date (i, year, month, day, &i->v->f));
1142 }
1143
1144 static bool
1145 parse_EDATE (struct data_in *i)
1146 {
1147   long month, day, year;
1148
1149   return (parse_leader (i)
1150           && parse_day (i, &day)
1151           && parse_date_delimiter (i)
1152           && parse_month (i, &month)
1153           && parse_date_delimiter (i)
1154           && parse_year (i, &year)
1155           && parse_trailer (i)
1156           && ymd_to_date (i, year, month, day, &i->v->f));
1157 }
1158
1159 static bool
1160 parse_SDATE (struct data_in *i)
1161 {
1162   long month, day, year;
1163
1164   return (parse_leader (i)
1165           && parse_year (i, &year)
1166           && parse_date_delimiter (i)
1167           && parse_month (i, &month)
1168           && parse_date_delimiter (i)
1169           && parse_day (i, &day)
1170           && parse_trailer (i)
1171           && ymd_to_date (i, year, month, day, &i->v->f));
1172 }
1173
1174 static bool
1175 parse_JDATE (struct data_in *i)
1176 {
1177   long julian;
1178   double ofs;
1179   
1180   if (!parse_leader (i)
1181       || !parse_julian (i, &julian)
1182       || !parse_trailer (i)
1183       || !ymd_to_ofs (i, julian / 1000, 1, 1, &ofs))
1184     return false;
1185
1186   i->v->f = (ofs + julian % 1000 - 1) * 60. * 60. * 24.;
1187   return true;
1188 }
1189
1190 static bool
1191 parse_QYR (struct data_in *i)
1192 {
1193   long quarter, year;
1194
1195   return (parse_leader (i)
1196           && parse_quarter (i, &quarter)
1197           && parse_q_delimiter (i)
1198           && parse_year (i, &year)
1199           && parse_trailer (i)
1200           && ymd_to_date (i, year, (quarter - 1) * 3 + 1, 1, &i->v->f));
1201 }
1202
1203 static bool
1204 parse_MOYR (struct data_in *i)
1205 {
1206   long month, year;
1207
1208   return (parse_leader (i)
1209           && parse_month (i, &month)
1210           && parse_date_delimiter (i)
1211           && parse_year (i, &year)
1212           && parse_trailer (i)
1213           && ymd_to_date (i, year, month, 1, &i->v->f));
1214 }
1215
1216 static bool
1217 parse_WKYR (struct data_in *i)
1218 {
1219   long week, year;
1220   double ofs;
1221
1222   if (!parse_leader (i)
1223       || !parse_week (i, &week)
1224       || !parse_wk_delimiter (i)
1225       || !parse_year (i, &year)
1226       || !parse_trailer (i))
1227     return false;
1228
1229   if (year != 1582) 
1230     {
1231       if (!ymd_to_ofs (i, year, 1, 1, &ofs))
1232         return false;
1233     }
1234   else 
1235     {
1236       if (ymd_to_ofs (i, 1583, 1, 1, &ofs))
1237         return false;
1238       ofs -= 365;
1239     }
1240
1241   i->v->f = (ofs + (week - 1) * 7) * 60. * 60. * 24.;
1242   return true;
1243 }
1244
1245 static bool
1246 parse_TIME (struct data_in *i)
1247 {
1248   int sign;
1249   double second;
1250   long hour, minute;
1251
1252   if (!parse_leader (i)
1253       || !parse_sign (i, &sign)
1254       || !parse_spaces (i)
1255       || !parse_hour (i, &hour)
1256       || !parse_time_delimiter (i)
1257       || !parse_minute (i, &minute)
1258       || !parse_opt_second (i, &second))
1259     return false;
1260
1261   i->v->f = (hour * 60. * 60. + minute * 60. + second) * sign;
1262   return true;
1263 }
1264
1265 static bool
1266 parse_DTIME (struct data_in *i)
1267 {
1268   int sign;
1269   long day_count, hour;
1270   double second;
1271   long minute;
1272
1273   if (!parse_leader (i)
1274       || !parse_sign (i, &sign)
1275       || !parse_spaces (i)
1276       || !parse_day_count (i, &day_count)
1277       || !parse_time_delimiter (i)
1278       || !parse_hour (i, &hour)
1279       || !parse_time_delimiter (i)
1280       || !parse_minute (i, &minute)
1281       || !parse_opt_second (i, &second))
1282     return false;
1283
1284   i->v->f = (day_count * 60. * 60. * 24.
1285              + hour * 60. * 60.
1286              + minute * 60.
1287              + second) * sign;
1288   return true;
1289 }
1290
1291 static bool
1292 parse_DATETIME (struct data_in *i)
1293 {
1294   long day, month, year;
1295   long hour24;
1296   double second;
1297   long minute;
1298
1299   if (!parse_leader (i)
1300       || !parse_day (i, &day)
1301       || !parse_date_delimiter (i)
1302       || !parse_month (i, &month)
1303       || !parse_date_delimiter (i)
1304       || !parse_year (i, &year)
1305       || !parse_time_delimiter (i)
1306       || !parse_hour24 (i, &hour24)
1307       || !parse_time_delimiter (i)
1308       || !parse_minute (i, &minute)
1309       || !parse_opt_second (i, &second)
1310       || !ymd_to_date (i, year, month, day, &i->v->f))
1311     return false;
1312
1313   i->v->f += hour24 * 60. * 60. + minute * 60. + second;
1314   return true;
1315 }
1316
1317 static bool
1318 parse_WKDAY (struct data_in *i)
1319 {
1320   long weekday;
1321
1322   if (!parse_leader (i)
1323       || !parse_weekday (i, &weekday)
1324       || !parse_trailer (i))
1325     return false;
1326
1327   i->v->f = weekday;
1328   return true;
1329 }
1330
1331 static bool
1332 parse_MONTH (struct data_in *i)
1333 {
1334   long month;
1335
1336   if (!parse_leader (i)
1337       || !parse_month (i, &month)
1338       || !parse_trailer (i))
1339     return false;
1340
1341   i->v->f = month;
1342   return true;
1343 }
1344 \f
1345 /* Main dispatcher. */
1346
1347 static void
1348 default_result (struct data_in *i)
1349 {
1350   const struct fmt_desc *const fmt = &formats[i->format.type];
1351
1352   /* Default to SYSMIS or blanks. */
1353   if (fmt->cat & FCAT_STRING)
1354     memset (i->v->s, ' ', i->format.w);
1355   else
1356     i->v->f = get_blanks();
1357 }
1358
1359 bool
1360 data_in (struct data_in *i)
1361 {
1362   const struct fmt_desc *const fmt = &formats[i->format.type];
1363
1364   assert (check_input_specifier (&i->format, 0));
1365
1366   /* Check that we've got a string to work with. */
1367   if (i->e == i->s || i->format.w <= 0)
1368     {
1369       default_result (i);
1370       return true;
1371     }
1372
1373   i->f2 = i->f1 + (i->e - i->s) - 1;
1374
1375   /* Make sure that the string isn't too long. */
1376   if (i->format.w > fmt->Imax_w)
1377     {
1378       dls_error (i, _("Field too long (%d characters).  Truncated after "
1379                    "character %d."),
1380                  i->format.w, fmt->Imax_w);
1381       i->format.w = fmt->Imax_w;
1382     }
1383
1384   if (fmt->cat & FCAT_BLANKS_SYSMIS)
1385     {
1386       const unsigned char *cp;
1387
1388       cp = i->s;
1389       for (;;)
1390         {
1391           if (!isspace (*cp))
1392             break;
1393
1394           if (++cp == i->e)
1395             {
1396               i->v->f = get_blanks();
1397               return true;
1398             }
1399         }
1400     }
1401   
1402   {
1403     static bool (*const handlers[FMT_NUMBER_OF_FORMATS])(struct data_in *) = 
1404       {
1405         parse_numeric, parse_N, parse_numeric, parse_numeric,
1406         parse_numeric, parse_numeric, parse_numeric,
1407         parse_Z, parse_A, parse_AHEX, parse_IB, parse_P, parse_PIB,
1408         parse_PIBHEX, parse_PK, parse_RB, parse_RBHEX,
1409         NULL, NULL, NULL, NULL, NULL,
1410         parse_DATE, parse_EDATE, parse_SDATE, parse_ADATE, parse_JDATE,
1411         parse_QYR, parse_MOYR, parse_WKYR,
1412         parse_DATETIME, parse_TIME, parse_DTIME,
1413         parse_WKDAY, parse_MONTH,
1414       };
1415
1416     bool (*handler)(struct data_in *);
1417     bool success;
1418
1419     handler = handlers[i->format.type];
1420     assert (handler != NULL);
1421
1422     success = handler (i);
1423     if (!success)
1424       default_result (i);
1425
1426     return success;
1427   }
1428 }
1429 \f
1430 /* Utility function. */
1431
1432 /* Sets DI->{s,e} appropriately given that LINE has length LEN and the
1433    field starts at one-based column FC and ends at one-based column
1434    LC, inclusive. */
1435 void
1436 data_in_finite_line (struct data_in *di, const char *line, size_t len,
1437                      int fc, int lc)
1438 {
1439   di->s = line + ((size_t) fc <= len ? fc - 1 : len);
1440   di->e = line + ((size_t) lc <= len ? lc : len);
1441 }