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