12ee73ebdf4d02d143776cb252eca089ac215a7e
[pspp] / dump.c
1 #include <assert.h>
2 #include <float.h>
3 #include <stdbool.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/stat.h>
9 #include <time.h>
10 #include <unistd.h>
11 #include "u8-mbtouc.h"
12
13 static uint8_t *data;
14 static size_t n;
15
16 int version;
17
18 static bool
19 all_ascii(const uint8_t *p, size_t n)
20 {
21   for (size_t i = 0; i < n; i++)
22     if (p[i] < 32 || p[i] > 126)
23       return false;
24   return true;
25 }
26
27 static size_t
28 try_find(const char *target, size_t target_len)
29 {
30   const uint8_t *pos = (const uint8_t *) memmem (data, n, target, target_len);
31   return pos ? pos - data : 0;
32 }
33
34 static size_t
35 find(const char *target, size_t target_len)
36 {
37   size_t pos = try_find(target, target_len);
38   if (!pos)
39     {
40       fprintf (stderr, "not found\n");
41       exit(1);
42     }
43   return pos;
44 }
45
46 size_t pos;
47
48 #define XSTR(x) #x
49 #define STR(x) XSTR(x)
50 #define WHERE __FILE__":" STR(__LINE__)
51
52 static uint8_t
53 get_byte(void)
54 {
55   return data[pos++];
56 }
57
58 static unsigned int
59 get_u32(void)
60 {
61   uint32_t x;
62   memcpy(&x, &data[pos], 4);
63   pos += 4;
64   return x;
65 }
66
67 static unsigned long long int
68 get_u64(void)
69 {
70   uint64_t x;
71   memcpy(&x, &data[pos], 8);
72   pos += 8;
73   return x;
74 }
75
76 static unsigned int
77 get_be32(void)
78 {
79   uint32_t x;
80   x = (data[pos] << 24) | (data[pos + 1] << 16) | (data[pos + 2] << 8) | data[pos + 3];
81   pos += 4;
82   return x;
83 }
84
85 static unsigned int
86 get_u16(void)
87 {
88   uint16_t x;
89   memcpy(&x, &data[pos], 2);
90   pos += 2;
91   return x;
92 }
93
94 static double
95 get_double(void)
96 {
97   double x;
98   memcpy(&x, &data[pos], 8);
99   pos += 8;
100   return x;
101 }
102
103 static double __attribute__((unused))
104 get_float(void)
105 {
106   float x;
107   memcpy(&x, &data[pos], 4);
108   pos += 4;
109   return x;
110 }
111
112 static bool
113 match_u32(uint32_t x)
114 {
115   if (get_u32() == x)
116     return true;
117   pos -= 4;
118   return false;
119 }
120
121 static void
122 match_u32_assert(uint32_t x, const char *where)
123 {
124   unsigned int y = get_u32();
125   if (x != y)
126     {
127       fprintf(stderr, "%s: 0x%x: expected i%u, got i%u\n", where, pos - 4, x, y);
128       exit(1);
129     }
130 }
131 #define match_u32_assert(x) match_u32_assert(x, WHERE)
132
133 static bool __attribute__((unused))
134 match_u64(uint64_t x)
135 {
136   if (get_u64() == x)
137     return true;
138   pos -= 8;
139   return false;
140 }
141
142 static void __attribute__((unused))
143 match_u64_assert(uint64_t x, const char *where)
144 {
145   unsigned long long int y = get_u64();
146   if (x != y)
147     {
148       fprintf(stderr, "%s: 0x%x: expected u64:%llu, got u64:%llu\n", where, pos - 8, x, y);
149       exit(1);
150     }
151 }
152 #define match_u64_assert(x) match_u64_assert(x, WHERE)
153
154 static bool __attribute__((unused))
155 match_be32(uint32_t x)
156 {
157   if (get_be32() == x)
158     return true;
159   pos -= 4;
160   return false;
161 }
162
163 static void
164 match_be32_assert(uint32_t x, const char *where)
165 {
166   unsigned int y = get_be32();
167   if (x != y)
168     {
169       fprintf(stderr, "%s: 0x%x: expected be%u, got be%u\n", where, pos - 4, x, y);
170       exit(1);
171     }
172 }
173 #define match_be32_assert(x) match_be32_assert(x, WHERE)
174
175 static bool
176 match_byte(uint8_t b)
177 {
178   if (pos < n && data[pos] == b)
179     {
180       pos++;
181       return true;
182     }
183   else
184     return false;
185 }
186
187 static void
188 match_byte_assert(uint8_t b, const char *where)
189 {
190   if (!match_byte(b))
191     {
192       fprintf(stderr, "%s: 0x%x: expected %02x, got %02x\n", where, pos, b, data[pos]);
193       exit(1);
194     }
195 }
196 #define match_byte_assert(b) match_byte_assert(b, WHERE)
197
198 static void
199 newline(FILE *stream, int pos)
200 {
201   fprintf(stream, "\n%08x: ", pos);
202 }
203
204 static void
205 dump_raw(FILE *stream, int start, int end)
206 {
207   for (size_t i = start; i < end; )
208     {
209       if (i + 5 <= n
210           && data[i]
211           //&& !data[i + 1]
212           && !data[i + 2]
213           && !data[i + 3]
214           && i + 4 + data[i] + data[i + 1] * 256 <= end
215           && all_ascii(&data[i + 4], data[i] + data[i + 1] * 256))
216         {
217           newline(stream, i);
218           fprintf(stream, "\"");
219           fwrite(&data[i + 4], 1, data[i] + data[i + 1] * 256, stream);
220           fputs("\" ", stream);
221
222           i += 4 + data[i] + data[i + 1] * 256;
223         }
224       else if (i + 12 <= end
225                && data[i + 1] == 40
226                && data[i + 2] == 5
227                && data[i + 3] == 0)
228         {
229           double d;
230
231           memcpy (&d, &data[i + 4], 8);
232           fprintf (stream, "F40.%d(%.*f)", data[i], data[i], d);
233           i += 12;
234           newline (stream, i);
235         }
236       else if (i + 12 <= end
237                && data[i + 1] == 40
238                && data[i + 2] == 31
239                && data[i + 3] == 0)
240         {
241           double d;
242
243           memcpy (&d, &data[i + 4], 8);
244           fprintf (stream, "PCT40.%d(%.*f)", data[i], data[i], d);
245           i += 12;
246           newline(stream, i);
247         }
248       else if (i + 4 <= end
249                && (data[i] && data[i] != 88 && data[i] != 0x41)
250                && !data[i + 1]
251                && !data[i + 2]
252                && !data[i + 3])
253         {
254           fprintf (stream, "i%d ", data[i]);
255           i += 4;
256         }
257       else
258         {
259           fprintf(stream, "%02x ", data[i]);
260           i++;
261         }
262     }
263
264
265 }
266
267 static bool __attribute__((unused))
268 all_utf8(const char *p_)
269 {
270   const uint8_t *p = (const uint8_t *) p_;
271   size_t len = strlen ((char *) p);
272   for (size_t ofs = 0, mblen; ofs < len; ofs += mblen)
273     {
274       ucs4_t uc;
275
276       mblen = u8_mbtouc (&uc, p + ofs, len - ofs);
277       if ((uc < 32 && uc != '\n') || uc == 127 || uc == 0xfffd)
278         return false;
279     }
280   return true;
281 }
282
283 static char *
284 get_string(const char *where)
285 {
286   if (1
287       /*data[pos + 1] == 0 && data[pos + 2] == 0 && data[pos + 3] == 0*/
288       /*&& all_ascii(&data[pos + 4], data[pos])*/)
289     {
290       int len = data[pos] + data[pos + 1] * 256;
291       char *s = malloc(len + 1);
292
293       memcpy(s, &data[pos + 4], len);
294       s[len] = 0;
295       pos += 4 + len;
296       return s;
297     }
298   else
299     {
300       fprintf(stderr, "%s: 0x%x: expected string\n", where, pos);
301       exit(1);
302     }
303 }
304 #define get_string() get_string(WHERE)
305
306 static char *
307 get_string_be(const char *where)
308 {
309   if (1
310       /*data[pos + 1] == 0 && data[pos + 2] == 0 && data[pos + 3] == 0*/
311       /*&& all_ascii(&data[pos + 4], data[pos])*/)
312     {
313       int len = data[pos + 2] * 256 + data[pos + 3];
314       char *s = malloc(len + 1);
315
316       memcpy(s, &data[pos + 4], len);
317       s[len] = 0;
318       pos += 4 + len;
319       return s;
320     }
321   else
322     {
323       fprintf(stderr, "%s: 0x%x: expected string\n", where, pos);
324       exit(1);
325     }
326 }
327 #define get_string_be() get_string_be(WHERE)
328
329 static int
330 get_end(void)
331 {
332   int len = get_u32();
333   return pos + len;
334 }
335
336 static void __attribute__((unused))
337 hex_dump(int ofs, int n)
338 {
339   for (int i = 0; i < n; i++)
340     {
341       int c = data[ofs + i];
342 #if 1
343       if (i && !(i % 16))
344         printf("-");
345       else
346         printf(" ");
347 #endif
348       printf("%02x", c);
349     }
350   for (int i = 0; i < n; i++)
351     {
352       int c = data[ofs + i];
353       printf("%c", c >= 32 && c < 127 ? c : '.');
354     }
355 }
356
357 static char *
358 dump_counted_string(void)
359 {
360   char *s = NULL;
361   int inner_end = get_end();
362   if (pos != inner_end)
363     {
364       if (match_u32(5))
365         {
366           match_u32_assert(0);
367           match_byte_assert(0x58);
368         }
369       else
370         match_u32_assert(0);
371       if (match_byte(0x31))
372         s = get_string();
373       else
374         match_byte_assert(0x58);
375       if (pos != inner_end)
376         {
377           fprintf(stderr, "inner end discrepancy\n");
378           exit(1);
379         }
380     }
381   return s;
382 }
383
384 static void
385 dump_style(FILE *stream)
386 {
387   match_byte(1);
388   match_byte(0);
389   match_byte(0);
390   match_byte(0);
391   match_byte_assert(1);
392   char *fg = get_string();     /* foreground */
393   char *bg = get_string();     /* background */
394   char *font = get_string();     /* font */
395   int size = data[pos];
396   if (!match_byte(14))
397     match_byte_assert(12); /* size? */
398   fprintf(stream, " fgcolor=\"%s\" bgcolor=\"%s\" font=\"%s\" size=\"%d\"",
399           fg, bg, font, size);
400 }
401
402 static char *
403 dump_nested_string(FILE *stream)
404 {
405   char *s = NULL;
406
407   match_byte_assert (0);
408   match_byte_assert (0);
409   int outer_end = get_end();
410   s = dump_counted_string();
411   if (s)
412     fprintf(stream, " \"%s\"", s);
413   if (match_byte(0x31))
414     dump_style(stream);
415   else
416     match_byte_assert(0x58);
417   match_byte_assert(0x58);
418   if (pos != outer_end)
419     {
420       fprintf(stderr, "outer end discrepancy\n");
421       exit(1);
422     }
423
424   return s;
425 }
426
427 static void
428 dump_value_modifier(FILE *stream)
429 {
430   if (match_byte (0x31))
431     {
432       if (match_u32 (0))
433         {
434           fprintf(stream, "<special0");
435           if (match_u32 (1))
436             {
437               /* Corpus frequencies:
438                  124 "a"
439                  12 "b"
440                  8 "a, b"
441
442                  The given text is appended to the cell in a subscript font.
443               */
444               fprintf(stream, " subscript=\"%s\"", get_string());
445             }
446           else
447             match_u32_assert (0);
448
449           if (version == 1)
450             {
451               /* We only have one SPV file for this version (with many
452                  tables). */
453               match_byte(0);
454               if (!match_u32(1))
455                 match_u32_assert(2);
456               match_byte(0);
457               match_byte(0);
458               if (!match_u32(0) && !match_u32(1) && !match_u32(2) && !match_u32(3) && !match_u32(4) && !match_u32(5) && !match_u32(6) && !match_u32(7) && !match_u32(8) && !match_u32(9))
459                 match_u32_assert(10);
460               match_byte(0);
461               match_byte(0);
462               fprintf(stream, "/>\n");
463               return;
464             }
465
466           int outer_end = get_end();
467           
468           /* This counted-string appears to be a template string,
469              e.g. "Design\: [:^1:]1 Within Subjects Design\: [:^1:]2". */
470           char *template = dump_counted_string();
471           if (template)
472             fprintf(stream, " template=\"%s\"", template);
473
474           if (match_byte(0x31))
475             dump_style(stream);
476           else
477             match_byte_assert(0x58);
478           if (match_byte(0x31))
479             {
480               /* Only two SPV files have anything like this, so it's hard to
481                  generalize. */
482               match_u32_assert(0);
483               match_u32_assert(0);
484               match_u32_assert(0);
485               match_u32_assert(0);
486               match_byte_assert(1);
487               match_byte_assert(0);
488               if (!match_byte(8) && !match_byte(1))
489                 match_byte_assert(2);
490               match_byte_assert(0);
491               match_byte_assert(8);
492               match_byte_assert(0);
493               match_byte_assert(10);
494               match_byte_assert(0);
495             }
496           else
497             match_byte_assert(0x58);
498           if (pos != outer_end)
499             {
500               fprintf(stderr, "outer end discrepancy\n");
501               exit(1);
502             }
503           fprintf(stream, "/>\n");
504         }
505       else
506         {
507           int count = get_u32();
508           fprintf(stream, "<footnote-ref indexes=\"");
509           for (int i = 0; i < count; i++)
510             {
511               if (i)
512                 putc(' ', stream);
513               fprintf(stream, "%d", get_u16());
514             }
515           putc('"', stream);
516           match_byte_assert(0);
517           match_byte_assert(0);
518           dump_nested_string(stream);
519           fprintf(stream, "/>\n");
520         }
521     }
522   else
523     match_byte_assert (0x58);
524 }
525
526 static const char *
527 format_to_string (int type)
528 {
529   static char tmp[16];
530   switch (type)
531     {
532     case 1: return "A";
533     case 2: return "AHEX";
534     case 3: return "COMMA";
535     case 4: return "DOLLAR";
536     case 5: case 40: return "F";
537     case 6: return "IB";
538     case 7: return "PIBHEX";
539     case 8: return "P";
540     case 9: return "PIB";
541     case 10: return "PK";
542     case 11: return "RB";
543     case 12: return "RBHEX";
544     case 15: return "Z";
545     case 16: return "N";
546     case 17: return "E";
547     case 20: return "DATE";
548     case 21: return "TIME";
549     case 22: return "DATETIME";
550     case 23: return "ADATE";
551     case 24: return "JDATE";
552     case 25: return "DTIME";
553     case 26: return "WKDAY";
554     case 27: return "MONTH";
555     case 28: return "MOYR";
556     case 29: return "QYR";
557     case 30: return "WKYR";
558     case 31: return "PCT";
559     case 32: return "DOT";
560     case 33: return "CCA";
561     case 34: return "CCB";
562     case 35: return "CCC";
563     case 36: return "CCD";
564     case 37: return "CCE";
565     case 38: return "EDATE";
566     case 39: return "SDATE";
567     default:
568       abort();
569       sprintf(tmp, "<%d>", type);
570       return tmp;
571     }
572 }
573
574 static void
575 dump_value(FILE *stream, int level)
576 {
577   match_byte(0);
578   match_byte(0);
579   match_byte(0);
580   match_byte(0);
581
582   for (int i = 0; i <= level; i++)
583     fprintf (stream, "    ");
584
585   if (match_byte (1))
586     {
587       unsigned int format;
588       double value;
589
590       dump_value_modifier(stream);
591       format = get_u32 ();
592       value = get_double ();
593       fprintf (stream, "<number value=\"%.*g\" format=\"%s%d.%d\"/>\n",
594                DBL_DIG, value, format_to_string(format >> 16), (format >> 8) & 0xff, format & 0xff);
595     }
596   else if (match_byte (2))
597     {
598       unsigned int format;
599       char *var, *vallab;
600       double value;
601
602       dump_value_modifier (stream);
603       format = get_u32 ();
604       value = get_double ();
605       var = get_string ();
606       vallab = get_string ();
607       fprintf (stream, "<numeric-datum value=\"%.*g\" format=\"%s%d.%d\"",
608               DBL_DIG, value, format_to_string(format >> 16), (format >> 8) & 0xff, format & 0xff);
609       if (var[0])
610         fprintf (stream, " variable=\"%s\"", var);
611       if (vallab[0])
612         fprintf (stream, " label=\"%s\"", vallab);
613       fprintf (stream, "/>\n");
614       if (!match_byte (1) && !match_byte(2))
615         match_byte_assert (3);
616     }
617   else if (match_byte (3))
618     {
619       char *text =  get_string();
620       dump_value_modifier(stream);
621       char *identifier = get_string();
622       char *text_eng = get_string();
623       fprintf (stream, "<string c=\"%s\"", text_eng);
624       if (identifier[0])
625         fprintf (stream, " identifier=\"%s\"", identifier);
626       if (strcmp(text_eng, text))
627         fprintf (stream, " local=\"%s\"", text);
628       fprintf (stream, "/>\n");
629       if (!match_byte (0))
630         match_byte_assert(1);
631     }
632   else if (match_byte (4))
633     {
634       unsigned int format;
635       char *var, *vallab, *value;
636
637       dump_value_modifier(stream);
638       format = get_u32 ();
639       vallab = get_string ();
640       var = get_string ();
641       if (!match_byte(1) && !match_byte(2))
642         match_byte_assert (3);
643       value = get_string ();
644       fprintf (stream, "<string-datum value=\"%s\" format=\"%s%d.%d\"",
645               value, format_to_string(format >> 16), (format >> 8) & 0xff, format & 0xff);
646       if (var[0])
647         fprintf (stream, " variable=\"%s\"", var);
648       if (vallab[0])
649         fprintf (stream, " label=\"%s\"/>\n", vallab);
650       fprintf (stream, "/>\n");
651     }
652   else if (match_byte (5))
653     {
654       dump_value_modifier(stream);
655       char *name = get_string ();
656       char *label = get_string ();
657       fprintf (stream, "<variable name=\"%s\"", name);
658       if (label[0])
659         fprintf (stream, " label=\"%s\"", label);
660       fprintf (stream, "/>\n");
661       if (!match_byte(1) && !match_byte(2))
662         match_byte_assert(3);
663     }
664   else
665     {
666       dump_value_modifier(stream);
667
668       char *base = get_string();
669       int x = get_u32();
670       fprintf (stream, "<template format=\"%s\">\n", base);
671       for (int i = 0; i < x; i++)
672         {
673           int y = get_u32();
674           if (!y)
675             y = 1;
676           else
677             match_u32_assert(0);
678           for (int j = 0; j <= level + 1; j++)
679             fprintf (stream, "    ");
680           fprintf (stream, "<substitution index=\"%d\">\n", i + 1);
681           for (int j = 0; j < y; j++)
682             dump_value (stream, level + 2);
683           for (int j = 0; j <= level + 1; j++)
684             fprintf (stream, "    ");
685           fprintf (stream, "</substitution>\n");
686         }
687       for (int j = 0; j <= level; j++)
688         fprintf (stream, "    ");
689       fprintf (stream, "</template>\n");
690     }
691 }
692
693 static int
694 compare_int(const void *a_, const void *b_)
695 {
696   const int *a = a_;
697   const int *b = b_;
698   return *a < *b ? -1 : *a > *b;
699 }
700
701 static void
702 check_permutation(int *a, int n, const char *name)
703 {
704   int b[n];
705   memcpy(b, a, n * sizeof *a);
706   qsort(b, n, sizeof *b, compare_int);
707   for (int i = 0; i < n; i++)
708     if (b[i] != i)
709       {
710         fprintf(stderr, "bad %s permutation:", name);
711         for (int i = 0; i < n; i++)
712           fprintf(stderr, " %d", a[i]);
713         putc('\n', stderr);
714         exit(1);
715       }
716 }
717
718 static void
719 dump_category(FILE *stream, int level, int **indexes, int *allocated_indexes,
720               int *n_indexes)
721 {
722   for (int i = 0; i <= level; i++)
723     fprintf (stream, "    ");
724   printf ("<category>\n");
725   dump_value (stream, level + 1);
726
727   int merge = data[pos];
728   if (!match_byte(0))
729     match_byte_assert (1);
730
731   match_byte_assert (0);
732
733   int unindexed = data[pos];
734   if (!match_byte(0))
735     match_byte_assert (1);
736
737   int x = get_u32 ();
738   pos -= 4;
739   if (!match_u32 (0))
740     match_u32_assert (2);
741
742   int indx = get_u32();
743   int n_categories = get_u32();
744   if (indx == -1)
745     {
746       if (merge)
747         {
748           for (int i = 0; i <= level + 1; i++)
749             fprintf (stream, "    ");
750           fprintf (stream, "<merge/>\n");
751         }
752     }
753   else
754     {
755       if (merge)
756         {
757           fprintf(stderr, "index not -1 but merged\n");
758           exit(1);
759         }
760       if (x != 2)
761         {
762           fprintf(stderr, "index not -1 but x != 2\n");
763           exit(1);
764         }
765       if (n_categories != 0)
766         {
767           fprintf(stderr, "index not -1 but subcategories\n");
768           exit(1);
769         }
770       if (*n_indexes >= *allocated_indexes)
771         {
772           *allocated_indexes = *allocated_indexes ? 2 * *allocated_indexes : 16;
773           *indexes = realloc(*indexes, *allocated_indexes * sizeof **indexes);
774         }
775       (*indexes)[(*n_indexes)++] = indx;
776     }
777
778   int expected_unindexed = indx == -1;
779   if (unindexed != expected_unindexed)
780     {
781       fprintf(stderr, "unindexed (%d) mismatch with indx (%d)\n",
782               unindexed, indx);
783       exit(1);
784     }
785
786   if (n_categories == 0)
787     {
788       for (int i = 0; i <= level + 1; i++)
789         fprintf (stream, "    ");
790       fprintf (stream, "<category-index>%d</category-index>\n", indx);
791     }
792   for (int i = 0; i < n_categories; i++)
793     dump_category (stream, level + 1, indexes, allocated_indexes, n_indexes);
794   for (int i = 0; i <= level; i++)
795     fprintf (stream, "    ");
796   printf ("</category>\n");
797 }
798
799 static int
800 dump_dim(int indx)
801 {
802   int n_categories;
803
804   printf ("<dimension index=\"%d\">\n", indx);
805   dump_value (stdout, 0);
806
807   /* This byte is usually 0 but many other values have been spotted. */
808   pos++;
809
810   if (!match_byte(0) && !match_byte(1))
811     match_byte_assert(2);
812   if (!match_u32(0))
813     match_u32_assert(2);
814   if (!match_byte(0))
815     match_byte_assert(1);
816   if (!match_byte(0))
817     match_byte_assert(1);
818   match_byte_assert(1);
819   if (!match_u32(UINT32_MAX))
820     match_u32_assert(indx);
821   n_categories = get_u32();
822
823   int *indexes = NULL;
824   int n_indexes = 0;
825   int allocated_indexes = 0;
826   for (int i = 0; i < n_categories; i++)
827     dump_category (stdout, 0, &indexes, &allocated_indexes, &n_indexes);
828   check_permutation(indexes, n_indexes, "categories");
829
830   fprintf (stdout, "</dimension>\n");
831   return n_indexes;
832 }
833
834 int n_dims;
835 static int dim_n_cats[64];
836 #define MAX_DIMS (sizeof dim_n_cats / sizeof *dim_n_cats)
837
838 static void
839 dump_dims(void)
840 {
841   n_dims = get_u32();
842   assert(n_dims < MAX_DIMS);
843   for (int i = 0; i < n_dims; i++)
844     dim_n_cats[i] = dump_dim (i);
845 }
846
847 static void
848 dump_data(void)
849 {
850   /* The first three numbers add to the number of dimensions. */
851   int l = get_u32();
852   int r = get_u32();
853   int c = n_dims - l - r;
854   match_u32_assert(c);
855
856   /* The next n_dims numbers are a permutation of the dimension numbers. */
857   int a[n_dims];
858   for (int i = 0; i < n_dims; i++)
859     {
860       int dim = get_u32();
861       a[i] = dim;
862
863       const char *name = i < l ? "layer" : i < l + r ? "row" : "column";
864       printf ("<%s dimension=\"%d\"/>\n", name, dim);
865     }
866   check_permutation(a, n_dims, "dimensions");
867
868   int x = get_u32();
869   printf ("<data>\n");
870   for (int i = 0; i < x; i++)
871     {
872       unsigned int indx = get_u32();
873       printf ("    <datum index=\"%d\" coords=", indx);
874
875       int coords[MAX_DIMS];
876       for (int i = n_dims; i-- > 0; )
877         {
878           coords[i] = indx % dim_n_cats[i];
879           indx /= dim_n_cats[i];
880         }
881       for (int i = 0; i < n_dims; i++)
882         printf("%c%d", i ? ',' : '"', coords[i]);
883
884       printf ("\">\n");
885       match_u32_assert(0);
886       if (version == 1)
887         match_byte(0);
888       dump_value(stdout, 1);
889       fprintf (stdout, "    </datum>\n");
890     }
891   printf ("</data>\n");
892 }
893
894 static void
895 dump_title(void)
896 {
897   printf ("<title-local>\n");
898   dump_value(stdout, 0);
899   match_byte(1);
900   printf ("</title-local>\n");
901
902   printf ("<subtype>\n");
903   dump_value(stdout, 0);
904   match_byte(1);
905   printf ("</subtype>\n");
906
907   match_byte_assert(0x31);
908
909   printf ("<title-c>\n");
910   dump_value(stdout, 0);
911   match_byte(1);
912   printf ("</title-c>\n");
913
914   if (match_byte(0x31))
915     {
916       printf ("<user-caption>\n");
917       dump_value(stdout, 0);
918       printf ("</user-caption>\n");
919     }
920   else
921     match_byte_assert(0x58);
922   if (match_byte(0x31))
923     {
924       printf ("<caption>\n");
925       dump_value(stdout, 0);
926       printf ("</caption>\n");
927     }
928   else
929     match_byte_assert(0x58);
930
931   int n_footnotes = get_u32();
932   for (int i = 0; i < n_footnotes; i++)
933     {
934       printf ("<footnote index=\"%d\">\n", i);
935       dump_value(stdout, 0);
936       /* Custom footnote marker string. */
937       if (match_byte (0x31))
938         dump_value(stdout, 0);
939       else
940         match_byte_assert (0x58);
941       get_u32 ();
942       printf ("</footnote>\n");
943     }
944 }
945
946 static void
947 dump_fonts(void)
948 {
949   match_byte(0);
950   for (int i = 1; i <= 8; i++)
951     {
952       printf ("<style index=\"%d\"", i);
953       match_byte_assert(i);
954       match_byte_assert(0x31);
955       printf(" font=\"%s\"", get_string());
956
957       printf(" size=\"%gpt\"", get_float());
958
959       int style = get_u32();
960       if (style & 1)
961         printf(" bold=\"true\"");
962       if (style & 2)
963         printf(" italic=\"true\"");
964
965       bool underline = data[pos++];
966       if (underline)
967         printf(" underline=\"true\"");
968
969       int halign = get_u32();
970       printf("\nhalign=%d\n", halign);
971
972       int valign = get_u32();
973       printf("\nvalign=%d\n", valign);
974
975       printf (" fgcolor=\"%s\"", get_string());
976       printf (" bgcolor=\"%s\"", get_string());
977
978       if (!match_byte(0))
979         match_byte_assert(1);
980       match_u32_assert(0);
981       char *othercolor = get_string();
982       if (othercolor[0])
983         printf(" othercolor=\"%s\"", othercolor);
984
985       if (version > 1)
986         {
987           printf("\nfonts:");
988           for (int i = 0; i < 4; i++)
989             printf(" %2d", get_u32());
990           printf("\n");
991         }
992
993       printf ("/>\n");
994     }
995
996   int x1 = get_u32();
997   int x1_end = pos + x1;
998   printf("<borders>\n");
999   match_be32_assert(1);
1000   int n_borders = get_be32();
1001   for (int i = 0; i < n_borders; i++)
1002     {
1003       int type = get_be32();
1004       int stroke = get_be32();
1005       int color = get_be32();
1006       printf("  <border type=\"%d\" stroke=\"%s\" color=\"#%06x\"/>\n",
1007              type,
1008              (stroke == 0 ? "none"
1009               : stroke == 1 ? "solid"
1010               : stroke == 2 ? "dashed"
1011               : stroke == 3 ? "thick"
1012               : stroke == 4 ? "thin"
1013               : stroke == 5 ? "double"
1014               : "<error>"),
1015              color);
1016     }
1017   bool grid = get_byte();
1018   pos += 3;
1019   printf("  <grid show=\"%s\"/>\n", grid ? "yes" : "no");
1020   printf("</borders>\n");
1021   assert(pos == x1_end);
1022
1023   int skip = get_u32();
1024   assert(skip == 18 || skip == 25);
1025   pos += skip;
1026
1027   int x3 = get_u32();
1028   int x3_end = pos + x3;
1029   if (version == 3)
1030     {
1031       match_be32_assert(1);
1032       get_be32();
1033       printf("<settings layer=\"%d\"", get_be32());
1034       if (!get_byte())
1035         printf(" skipempty=\"false\"");
1036       if (!get_byte())
1037         printf(" showdimensionincorner=\"false\"");
1038       if (!get_byte())
1039         printf(" markers=\"numeric\"");
1040       if (!get_byte())
1041         printf(" footnoteposition=\"subscript\"");
1042       get_byte();
1043       int nbytes = get_be32();
1044       printf("\n");
1045       hex_dump(pos, nbytes);
1046       printf("\n");
1047       pos += nbytes;
1048       get_string_be();
1049       char *look = get_string_be();
1050       if (look[0])
1051         printf(" look=\"%s\"", look);
1052       printf(">\n");
1053     }
1054   pos = x3_end;
1055
1056   /* Manual column widths, if present. */
1057   int count = get_u32();
1058   printf("<columnwidths>");
1059   for (int i = 0; i < count; i++)
1060     {
1061       if (i)
1062         putchar(' ');
1063       printf("%d", get_u32());
1064     }
1065   printf("</columnwidths>\n");
1066
1067   const char *locale = get_string();
1068   printf ("<locale>%s</locale>\n", locale);
1069
1070   get_u32();            /* Seen: 0, UINT32_MAX, 2, 3, 4, 5, 6, 8, 9, 21, 24. */
1071   if (!match_byte(0))
1072     match_byte_assert(1);
1073   match_byte_assert(0);
1074   if (!match_byte(0))
1075     match_byte_assert(1);
1076   printf("<epoch>%d</epoch>\n", get_u32());
1077
1078   int decimal = data[pos];
1079   int grouping = data[pos + 1];
1080   if (match_byte('.'))
1081     {
1082       if (!match_byte(',') && !match_byte('\''))
1083         match_byte_assert(' ');
1084     }
1085   else
1086     {
1087       match_byte_assert(',');
1088       if (!match_byte('.') && !match_byte(' ') && !match_byte(','))
1089         match_byte_assert(0);
1090     }
1091   printf("<format decimal=\"%c\" grouping=\"", decimal);
1092   if (grouping)
1093     putchar(grouping);
1094   printf("\"/>\n");
1095   if (match_u32(5))
1096     {
1097       for (int i = 0; i < 5; i++)
1098         printf("<CC%c>%s</CC%c>\n", 'A' + i, get_string(), 'A' + i);
1099     }
1100   else
1101     match_u32_assert(0);
1102
1103   /* The last chunk is an outer envelope that contains two inner envelopes.
1104      The second inner envelope has some interesting data like the encoding and
1105      the locale. */
1106   if (version == 3)
1107     {
1108       int outer_end = get_end();
1109
1110       /* First inner envelope: byte*33 int[n] int*[n]. */
1111       int inner_len = get_u32();
1112       int inner_end = pos + inner_len;
1113       int array_start = pos + 33;
1114       match_byte_assert(0);
1115       pos++;                    /* 0, 1, 10 seen. */
1116       match_byte_assert(0);
1117       pos++;                    /* 0...11 seen. */
1118       if (!match_byte(0) && !match_byte(1) && !match_byte(2))
1119         match_byte_assert(3);
1120       if (!match_byte(0) && !match_byte(2))
1121         match_byte_assert(3);
1122       if (!match_u64(0))
1123         match_u64_assert(UINT64_MAX);
1124       match_u32_assert(0);
1125       match_u32_assert(0);
1126       match_u32_assert(0);
1127       match_u32_assert(0);
1128       match_byte_assert(0);
1129       if (!match_byte(0))
1130         match_byte_assert(1);
1131       match_byte_assert(1);
1132       pos = array_start;
1133 #if 1
1134       printf("widths:");
1135       while (pos < inner_end)
1136         printf(" %d", get_u32());
1137       printf("\n");
1138 #endif
1139       pos = inner_end;;
1140
1141       /* Second inner envelope. */
1142       assert(get_end() == outer_end);
1143
1144       match_byte_assert(1);
1145       match_byte_assert(0);
1146       if (!match_byte(3) && !match_byte(4))
1147         match_byte_assert(5);
1148       match_byte_assert(0);
1149       match_byte_assert(0);
1150       match_byte_assert(0);
1151
1152       printf("<command>%s</command>\n", get_string());
1153       printf("<subcommand>%s</subcommand>\n", get_string());
1154       printf("<language>%s</language>\n", get_string());
1155       printf("<charset>%s</charset>\n", get_string());
1156       printf("<locale>%s</locale>\n", get_string());
1157
1158       if (!match_byte(0))
1159         match_byte_assert(1);
1160       match_byte_assert(0);
1161       if (!match_byte(0))
1162         match_byte_assert(1);
1163       if (!match_byte(0))
1164         match_byte_assert(1);
1165
1166       printf("<epoch2>%d</epoch2>\n", get_u32());
1167
1168       if (match_byte('.'))
1169         {
1170           if (!match_byte(',') && !match_byte('\''))
1171             match_byte_assert(' ');
1172         }
1173       else
1174         {
1175           match_byte_assert(',');
1176           if (!match_byte('.') && !match_byte(' ') && !match_byte(','))
1177             match_byte_assert(0);
1178         }
1179
1180       printf ("small: %g\n", get_double());
1181
1182       match_byte_assert(1);
1183       if (outer_end - pos > 6)
1184         {
1185           /* There might be a pair of strings representing a dataset and
1186              datafile name, or there might be a set of custom currency strings.
1187              The custom currency strings start with a pair of integers, so we
1188              can distinguish these from a string by checking for a null byte; a
1189              small 32-bit integer will always contain a null and a text string
1190              never will. */
1191           int save_pos = pos;
1192           int len = get_u32();
1193           bool has_dataset = !memchr(&data[pos], '\0', len);
1194           pos = save_pos;
1195
1196           if (has_dataset)
1197             {
1198               printf("<dataset>%s</dataset>\n", get_string());
1199               printf("<datafile>%s</datafile>\n", get_string());
1200
1201               match_u32_assert(0);
1202
1203               time_t date = get_u32();
1204               struct tm tm = *localtime(&date);
1205               char s[128];
1206               strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S %z", &tm);
1207               printf("<date>%s</date>\n", s);
1208
1209               match_u32_assert(0);
1210             }
1211         }
1212
1213       if (match_u32(5))
1214         {
1215           for (int i = 0; i < 5; i++)
1216             printf("<CC%c>%s</CC%c>\n", 'A' + i, get_string(), 'A' + i);
1217         }
1218       else
1219         match_u32_assert(0);
1220
1221       match_byte_assert('.');
1222       if (!match_byte(0))
1223         match_byte_assert(1);
1224
1225       if (pos < outer_end)
1226         {
1227           printf("<seed>%d</seed>\n", get_u32());
1228           match_u32_assert(0);
1229         }
1230       assert(pos == outer_end);
1231
1232       pos = outer_end;
1233     }
1234   else
1235     {
1236       pos = get_end();
1237     }
1238 }
1239
1240 int
1241 main(int argc, char *argv[])
1242 {
1243   size_t start;
1244   struct stat s;
1245
1246   if (isatty(STDIN_FILENO))
1247     {
1248       fprintf(stderr, "redirect stdin from a .bin file\n");
1249       exit(1);
1250     }
1251   if (fstat(STDIN_FILENO, &s))
1252     {
1253       perror("fstat");
1254       exit(1);
1255     }
1256   n = s.st_size;
1257   data = malloc(n);
1258   if (!data)
1259     {
1260       perror("malloc");
1261       exit(1);
1262     }
1263   if (read(STDIN_FILENO, data, n) != n)
1264     {
1265       perror("read");
1266       exit(1);
1267     }
1268
1269   if (argc != 2)
1270     {
1271       fprintf (stderr, "usage: %s TYPE < .bin", argv[0]);
1272       exit (1);
1273     }
1274
1275   if (!strcmp(argv[1], "title0"))
1276     {
1277       pos = 0x27;
1278       if (match_byte (0x03)
1279           || (match_byte (0x05) && match_byte (0x58)))
1280         printf ("%s\n", get_string());
1281       else
1282         printf ("<unknown>\n");
1283       return 0;
1284     }
1285   else if (!strcmp(argv[1], "title"))
1286     {
1287       pos = 0x27;
1288       dump_title();
1289       exit(0);
1290     }
1291   else if (!strcmp(argv[1], "titleraw"))
1292     {
1293       const char fonts[] = "\x01\x31\x09\0\0\0SansSerif";
1294       start = 0x27;
1295       n = find(fonts, sizeof fonts - 1);
1296     }
1297   else if (!strcmp(argv[1], "fonts"))
1298     {
1299       const char fonts[] = "\x01\x31\x09\0\0\0SansSerif";
1300       const char styles[] = "\xf0\0\0\0";
1301       start = find(fonts, sizeof fonts - 1);
1302       n = find(styles, sizeof styles - 1);
1303     }
1304   else if (!strcmp(argv[1], "styles"))
1305     {
1306       const char styles[] = "\xf0\0\0\0";
1307       const char dimensions[] = "-,,,.\0";
1308       start = find(styles, sizeof styles - 1);
1309       n = find(dimensions, sizeof dimensions - 1) + sizeof dimensions - 1;
1310     }
1311   else if (!strcmp(argv[1], "dimensions") || !strcmp(argv[1], "all"))
1312     {
1313       pos = 0;
1314       match_byte_assert(1);
1315       match_byte_assert(0);
1316
1317       /* This might be a version number of some kind, because value 1 seems
1318          to only appear in an SPV file that also required its own weird
1319          special cases in dump_value_modifier(). */
1320       version = get_u32();
1321       pos -= 4;
1322       if (!match_u32(1))
1323         match_u32_assert(3);
1324
1325       match_byte_assert(1);
1326       if (!match_byte(0))
1327         match_byte_assert(1);
1328
1329       /* Offset 8. */
1330       match_byte_assert(0);
1331       if (!match_byte(0))
1332         match_byte_assert(1);
1333       if (!match_byte(0))
1334         match_byte_assert(1);
1335
1336       /* Offset 11. */
1337       pos++;
1338       match_byte_assert(0);
1339       match_byte_assert(0);
1340       match_byte_assert(0);
1341
1342       /* Offset 15. */
1343       pos++;
1344       if (!match_byte(0))
1345         match_byte_assert(1);
1346       match_byte_assert(0);
1347       match_byte_assert(0);
1348
1349       /* Offset 19. */
1350       pos++;
1351       if (!match_byte(0))
1352         match_byte_assert(1);
1353       match_byte_assert(0);
1354       match_byte_assert(0);
1355
1356       /* Offset 23. */
1357       pos++;
1358       if (!match_byte(0))
1359         match_byte_assert(1);
1360       match_byte_assert(0);
1361       match_byte_assert(0);
1362
1363       /* Offset 27. */
1364 #if 1
1365       pos++;
1366       pos++;
1367       pos++;
1368       pos++;
1369 #else
1370       printf("\nheader:");
1371       for (int i = 0; i < 4; i++)
1372         printf(" %02x", data[pos++]);
1373       printf("\n");
1374 #endif
1375
1376       /* Offset 31. */
1377       printf("<tableid>%lld</tableid>", get_u64());
1378
1379       dump_title ();
1380       dump_fonts();
1381       dump_dims ();
1382       dump_data ();
1383       match_byte (1);
1384       if (pos != n)
1385         {
1386           fprintf (stderr, "%x / %x\n", pos, n);
1387           exit(1);
1388         }
1389       exit(0);
1390     }
1391   else if (!strcmp(argv[1], "raw"))
1392     {
1393       start = 0x27;
1394
1395       dump_raw(stdout, start, n);
1396     }
1397   else
1398     {
1399       fprintf (stderr, "unknown section %s\n", argv[1]);
1400       exit(1);
1401     }
1402
1403   return 0;
1404 }