Changed all the licence notices in all the files.
[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)
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 false;
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 false;
242     }
243
244   if (num == 0.0)
245     {
246       i->v->f = 0.0;
247       return true;
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 + digit_cnt > -(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 false;
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 false;
271         }
272       
273       num *= pow (10.0, (double) exponent);
274     }
275
276   i->v->f = sign > 0 ? num : -num;
277   return true;
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 bool
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 false;
303         }
304
305       i->v->f = i->v->f * 10.0 + *cp - '0';
306     }
307
308   apply_implied_decimals (i);
309   return true;
310 }
311
312 static inline bool
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 false;
327         }
328
329       n = n * 16.0 + hexit_value (*cp);
330     }
331   
332   i->v->f = n;
333   return true;
334 }
335
336 static inline bool
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 false;
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 false;
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 true;
377 }
378
379 static inline bool
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 bool 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 = true;
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 false;
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 false;
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 false;
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 false;
448       }
449   }
450
451   if (!got_dot)
452     apply_implied_decimals (i);
453
454   return true;
455 }
456
457 static inline bool
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 true;
498 }
499
500 static inline bool
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 true;
517 }
518
519 static inline bool
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 true;
537 }
538
539 static inline bool
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 true;
554 }
555
556 static inline bool
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 true;
571 }
572
573 static inline bool
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 true;
587 }
588
589 static inline bool
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 false;
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 false;
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 true;
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 bool
634 parse_leader (struct data_in *i)
635 {
636   skip_whitespace (i);
637   return true;
638 }
639
640 static inline bool
641 force_have_char (struct data_in *i)
642 {
643   if (have_char (i))
644     return true;
645
646   dls_error (i, _("Unexpected end of field."));
647   return false;
648 }
649
650 static bool
651 parse_int (struct data_in *i, long *result)
652 {
653   bool negative = false;
654   
655   if (!force_have_char (i))
656     return false;
657
658   if (*i->s == '+')
659     {
660       i->s++;
661       force_have_char (i);
662     }
663   else if (*i->s == '-')
664     {
665       negative = true;
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 false;
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 true;
687 }
688
689 static bool
690 parse_day (struct data_in *i, long *day)
691 {
692   if (!parse_int (i, day))
693     return false;
694   if (*day >= 1 && *day <= 31)
695     return true;
696
697   dls_error (i, _("Day (%ld) must be between 1 and 31."), *day);
698   return false;
699 }
700
701 static bool
702 parse_day_count (struct data_in *i, long *day_count)
703 {
704   return parse_int (i, day_count);
705 }
706
707 static bool
708 parse_date_delimiter (struct data_in *i)
709 {
710   bool delim = false;
711
712   while (have_char (i)
713          && (*i->s == '-' || *i->s == '/' || isspace (*i->s)
714              || *i->s == '.' || *i->s == ','))
715     {
716       delim = true;
717       i->s++;
718     }
719   if (delim)
720     return true;
721
722   dls_error (i, _("Delimiter expected between fields in date."));
723   return false;
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 false;
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 true;
767       }
768
769   dls_error (i, _("Unknown %s `%.*s'."), what, (int) length, name);
770   return false;
771 }
772
773 static bool
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 false;
811   
812   if (isdigit (*i->s))
813     {
814       if (!parse_int (i, month))
815         return false;
816       if (*month >= 1 && *month <= 12)
817         return true;
818       
819       dls_error (i, _("Month (%ld) must be between 1 and 12."), *month);
820       return false;
821     }
822   else 
823     return parse_enum (i, _("month"), month_names, month);
824 }
825
826 static bool
827 parse_year (struct data_in *i, long *year)
828 {
829   if (!parse_int (i, year))
830     return false;
831   
832   if (*year >= 0 && *year <= 199)
833     *year += 1900;
834   if (*year >= 1582 || *year <= 19999)
835     return true;
836
837   dls_error (i, _("Year (%ld) must be between 1582 and 19999."), *year);
838   return false;
839 }
840
841 static bool
842 parse_trailer (struct data_in *i)
843 {
844   skip_whitespace (i);
845   if (!have_char (i))
846     return true;
847   
848   dls_error (i, _("Trailing garbage \"%s\" following date."), i->s);
849   return false;
850 }
851
852 static bool
853 parse_julian (struct data_in *i, long *julian)
854 {
855   if (!parse_int (i, julian))
856     return false;
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 false;
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 false;
877       }
878   }
879
880   return true;
881 }
882
883 static bool
884 parse_quarter (struct data_in *i, long *quarter)
885 {
886   if (!parse_int (i, quarter))
887     return false;
888   if (*quarter >= 1 && *quarter <= 4)
889     return true;
890
891   dls_error (i, _("Quarter (%ld) must be between 1 and 4."), *quarter);
892   return false;
893 }
894
895 static bool
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 false;
903     }
904   i->s++;
905   skip_whitespace (i);
906   return true;
907 }
908
909 static bool
910 parse_week (struct data_in *i, long *week)
911 {
912   if (!parse_int (i, week))
913     return false;
914   if (*week >= 1 && *week <= 53)
915     return true;
916
917   dls_error (i, _("Week (%ld) must be between 1 and 53."), *week);
918   return false;
919 }
920
921 static bool
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 false;
930     }
931   i->s += 2;
932   skip_whitespace (i);
933   return true;
934 }
935
936 static bool
937 parse_time_delimiter (struct data_in *i)
938 {
939   bool delim = false;
940
941   while (have_char (i) && (*i->s == ':' || *i->s == '.' || isspace (*i->s)))
942     {
943       delim = true;
944       i->s++;
945     }
946
947   if (delim)
948     return true;
949   
950   dls_error (i, _("Delimiter expected between fields in time."));
951   return false;
952 }
953
954 static bool
955 parse_hour (struct data_in *i, long *hour)
956 {
957   if (!parse_int (i, hour))
958     return false;
959   if (*hour >= 0)
960     return true;
961   
962   dls_error (i, _("Hour (%ld) must be positive."), *hour);
963   return false;
964 }
965
966 static bool
967 parse_minute (struct data_in *i, long *minute)
968 {
969   if (!parse_int (i, minute))
970     return false;
971   if (*minute >= 0 && *minute <= 59)
972     return true;
973   
974   dls_error (i, _("Minute (%ld) must be between 0 and 59."), *minute);
975   return false;
976 }
977
978 static bool
979 parse_opt_second (struct data_in *i, double *second)
980 {
981   bool delim = false;
982
983   char buf[64];
984   char *cp;
985
986   while (have_char (i)
987          && (*i->s == ':' || *i->s == '.' || isspace (*i->s)))
988     {
989       delim = true;
990       i->s++;
991     }
992   
993   if (!delim || !isdigit (*i->s))
994     {
995       *second = 0.0;
996       return true;
997     }
998
999   cp = buf;
1000   while (have_char (i) && isdigit (*i->s))
1001     *cp++ = *i->s++;
1002   if (have_char (i) && *i->s == '.')
1003     *cp++ = *i->s++;
1004   while (have_char (i) && isdigit (*i->s))
1005     *cp++ = *i->s++;
1006   *cp = '\0';
1007   
1008   *second = strtod (buf, NULL);
1009
1010   return true;
1011 }
1012
1013 static bool
1014 parse_hour24 (struct data_in *i, long *hour24)
1015 {
1016   if (!parse_int (i, hour24))
1017     return false;
1018   if (*hour24 >= 0 && *hour24 <= 23)
1019     return true;
1020   
1021   dls_error (i, _("Hour (%ld) must be between 0 and 23."), *hour24);
1022   return false;
1023 }
1024
1025      
1026 static bool
1027 parse_weekday (struct data_in *i, long *weekday)
1028 {
1029   static const struct enum_name weekday_names[] = 
1030     {
1031       {"sunday", true, 1},
1032       {"su", true, 1},
1033       {"monday", true, 2},
1034       {"mo", true, 2},
1035       {"tuesday", true, 3},
1036       {"tu", true, 3},
1037       {"wednesday", true, 4},
1038       {"we", true, 4},
1039       {"thursday", true, 5},
1040       {"th", true, 5},
1041       {"friday", true, 6},
1042       {"fr", true, 6},
1043       {"saturday", true, 7},
1044       {"sa", true, 7},
1045       
1046       {NULL, false, 0},
1047     };
1048
1049   return parse_enum (i, _("weekday"), weekday_names, weekday);
1050 }
1051
1052 static bool
1053 parse_spaces (struct data_in *i)
1054 {
1055   skip_whitespace (i);
1056   return true;
1057 }
1058
1059 static bool
1060 parse_sign (struct data_in *i, int *sign)
1061 {
1062   if (!force_have_char (i))
1063     return false;
1064
1065   switch (*i->s)
1066     {
1067     case '-':
1068       i->s++;
1069       *sign = -1;
1070       break;
1071
1072     case '+':
1073       i->s++;
1074       /* fall through */
1075
1076     default:
1077       *sign = 1;
1078       break;
1079     }
1080
1081   return true;
1082 }
1083 \f
1084 /* Date & time formats. */
1085
1086 static void
1087 calendar_error (void *i_, const char *format, ...) 
1088 {
1089   struct data_in *i = i_;
1090   va_list args;
1091
1092   va_start (args, format);
1093   vdls_error (i, format, args);
1094   va_end (args);
1095 }
1096
1097 static bool
1098 ymd_to_ofs (struct data_in *i, int year, int month, int day, double *ofs) 
1099 {
1100   *ofs = calendar_gregorian_to_offset (year, month, day, calendar_error, i);
1101   return *ofs != SYSMIS;
1102 }
1103
1104 static bool
1105 ymd_to_date (struct data_in *i, int year, int month, int day, double *date) 
1106 {
1107   if (ymd_to_ofs (i, year, month, day, date)) 
1108     {
1109       *date *= 60. * 60. * 24.;
1110       return true; 
1111     }
1112   else
1113     return false;
1114 }
1115
1116 static bool
1117 parse_DATE (struct data_in *i)
1118 {
1119   long day, month, year;
1120
1121   return (parse_leader (i)
1122           && parse_day (i, &day)
1123           && parse_date_delimiter (i)
1124           && parse_month (i, &month)
1125           && parse_date_delimiter (i)
1126           && parse_year (i, &year)
1127           && parse_trailer (i)
1128           && ymd_to_date (i, year, month, day, &i->v->f));
1129 }
1130
1131 static bool
1132 parse_ADATE (struct data_in *i)
1133 {
1134   long month, day, year;
1135
1136   return (parse_leader (i)
1137           && parse_month (i, &month)
1138           && parse_date_delimiter (i)
1139           && parse_day (i, &day)
1140           && parse_date_delimiter (i)
1141           && parse_year (i, &year)
1142           && parse_trailer (i)
1143           && ymd_to_date (i, year, month, day, &i->v->f));
1144 }
1145
1146 static bool
1147 parse_EDATE (struct data_in *i)
1148 {
1149   long month, day, year;
1150
1151   return (parse_leader (i)
1152           && parse_day (i, &day)
1153           && parse_date_delimiter (i)
1154           && parse_month (i, &month)
1155           && parse_date_delimiter (i)
1156           && parse_year (i, &year)
1157           && parse_trailer (i)
1158           && ymd_to_date (i, year, month, day, &i->v->f));
1159 }
1160
1161 static bool
1162 parse_SDATE (struct data_in *i)
1163 {
1164   long month, day, year;
1165
1166   return (parse_leader (i)
1167           && parse_year (i, &year)
1168           && parse_date_delimiter (i)
1169           && parse_month (i, &month)
1170           && parse_date_delimiter (i)
1171           && parse_day (i, &day)
1172           && parse_trailer (i)
1173           && ymd_to_date (i, year, month, day, &i->v->f));
1174 }
1175
1176 static bool
1177 parse_JDATE (struct data_in *i)
1178 {
1179   long julian;
1180   double ofs;
1181   
1182   if (!parse_leader (i)
1183       || !parse_julian (i, &julian)
1184       || !parse_trailer (i)
1185       || !ymd_to_ofs (i, julian / 1000, 1, 1, &ofs))
1186     return false;
1187
1188   i->v->f = (ofs + julian % 1000 - 1) * 60. * 60. * 24.;
1189   return true;
1190 }
1191
1192 static bool
1193 parse_QYR (struct data_in *i)
1194 {
1195   long quarter, year;
1196
1197   return (parse_leader (i)
1198           && parse_quarter (i, &quarter)
1199           && parse_q_delimiter (i)
1200           && parse_year (i, &year)
1201           && parse_trailer (i)
1202           && ymd_to_date (i, year, (quarter - 1) * 3 + 1, 1, &i->v->f));
1203 }
1204
1205 static bool
1206 parse_MOYR (struct data_in *i)
1207 {
1208   long month, year;
1209
1210   return (parse_leader (i)
1211           && parse_month (i, &month)
1212           && parse_date_delimiter (i)
1213           && parse_year (i, &year)
1214           && parse_trailer (i)
1215           && ymd_to_date (i, year, month, 1, &i->v->f));
1216 }
1217
1218 static bool
1219 parse_WKYR (struct data_in *i)
1220 {
1221   long week, year;
1222   double ofs;
1223
1224   if (!parse_leader (i)
1225       || !parse_week (i, &week)
1226       || !parse_wk_delimiter (i)
1227       || !parse_year (i, &year)
1228       || !parse_trailer (i))
1229     return false;
1230
1231   if (year != 1582) 
1232     {
1233       if (!ymd_to_ofs (i, year, 1, 1, &ofs))
1234         return false;
1235     }
1236   else 
1237     {
1238       if (ymd_to_ofs (i, 1583, 1, 1, &ofs))
1239         return false;
1240       ofs -= 365;
1241     }
1242
1243   i->v->f = (ofs + (week - 1) * 7) * 60. * 60. * 24.;
1244   return true;
1245 }
1246
1247 static bool
1248 parse_TIME (struct data_in *i)
1249 {
1250   int sign;
1251   double second;
1252   long hour, minute;
1253
1254   if (!parse_leader (i)
1255       || !parse_sign (i, &sign)
1256       || !parse_spaces (i)
1257       || !parse_hour (i, &hour)
1258       || !parse_time_delimiter (i)
1259       || !parse_minute (i, &minute)
1260       || !parse_opt_second (i, &second))
1261     return false;
1262
1263   i->v->f = (hour * 60. * 60. + minute * 60. + second) * sign;
1264   return true;
1265 }
1266
1267 static bool
1268 parse_DTIME (struct data_in *i)
1269 {
1270   int sign;
1271   long day_count, hour;
1272   double second;
1273   long minute;
1274
1275   if (!parse_leader (i)
1276       || !parse_sign (i, &sign)
1277       || !parse_spaces (i)
1278       || !parse_day_count (i, &day_count)
1279       || !parse_time_delimiter (i)
1280       || !parse_hour (i, &hour)
1281       || !parse_time_delimiter (i)
1282       || !parse_minute (i, &minute)
1283       || !parse_opt_second (i, &second))
1284     return false;
1285
1286   i->v->f = (day_count * 60. * 60. * 24.
1287              + hour * 60. * 60.
1288              + minute * 60.
1289              + second) * sign;
1290   return true;
1291 }
1292
1293 static bool
1294 parse_DATETIME (struct data_in *i)
1295 {
1296   long day, month, year;
1297   long hour24;
1298   double second;
1299   long minute;
1300
1301   if (!parse_leader (i)
1302       || !parse_day (i, &day)
1303       || !parse_date_delimiter (i)
1304       || !parse_month (i, &month)
1305       || !parse_date_delimiter (i)
1306       || !parse_year (i, &year)
1307       || !parse_time_delimiter (i)
1308       || !parse_hour24 (i, &hour24)
1309       || !parse_time_delimiter (i)
1310       || !parse_minute (i, &minute)
1311       || !parse_opt_second (i, &second)
1312       || !ymd_to_date (i, year, month, day, &i->v->f))
1313     return false;
1314
1315   i->v->f += hour24 * 60. * 60. + minute * 60. + second;
1316   return true;
1317 }
1318
1319 static bool
1320 parse_WKDAY (struct data_in *i)
1321 {
1322   long weekday;
1323
1324   if (!parse_leader (i)
1325       || !parse_weekday (i, &weekday)
1326       || !parse_trailer (i))
1327     return false;
1328
1329   i->v->f = weekday;
1330   return true;
1331 }
1332
1333 static bool
1334 parse_MONTH (struct data_in *i)
1335 {
1336   long month;
1337
1338   if (!parse_leader (i)
1339       || !parse_month (i, &month)
1340       || !parse_trailer (i))
1341     return false;
1342
1343   i->v->f = month;
1344   return true;
1345 }
1346 \f
1347 /* Main dispatcher. */
1348
1349 static void
1350 default_result (struct data_in *i)
1351 {
1352   const struct fmt_desc *const fmt = &formats[i->format.type];
1353
1354   /* Default to SYSMIS or blanks. */
1355   if (fmt->cat & FCAT_STRING)
1356     memset (i->v->s, ' ', i->format.w);
1357   else
1358     i->v->f = get_blanks();
1359 }
1360
1361 bool
1362 data_in (struct data_in *i)
1363 {
1364   const struct fmt_desc *const fmt = &formats[i->format.type];
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 }