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