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