Figure out cell styling details.
[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   for (int i = 0; i < 4; i++)
388     printf (" %d", get_byte());
389   char *fg = get_string();     /* foreground */
390   char *bg = get_string();     /* background */
391   char *font = get_string();     /* font */
392   int size = get_byte() * (72. / 96.);
393   fprintf(stream, " fgcolor=\"%s\" bgcolor=\"%s\" font=\"%s\" size=\"%dpt\"",
394           fg, bg, font, size);
395 }
396
397 static char *
398 dump_nested_string(FILE *stream)
399 {
400   char *s = NULL;
401
402   match_byte_assert (0);
403   match_byte_assert (0);
404   int outer_end = get_end();
405   s = dump_counted_string();
406   if (s)
407     fprintf(stream, " \"%s\"", s);
408   if (match_byte(0x31))
409     dump_style(stream);
410   else
411     match_byte_assert(0x58);
412   match_byte_assert(0x58);
413   if (pos != outer_end)
414     {
415       fprintf(stderr, "outer end discrepancy\n");
416       exit(1);
417     }
418
419   return s;
420 }
421
422 static void
423 dump_value_modifier(FILE *stream)
424 {
425   if (match_byte (0x31))
426     {
427       if (match_u32 (0))
428         {
429           fprintf(stream, "<special0");
430           if (match_u32 (1))
431             {
432               /* Corpus frequencies:
433                  124 "a"
434                  12 "b"
435                  8 "a, b"
436
437                  The given text is appended to the cell in a subscript font.
438               */
439               fprintf(stream, " subscript=\"%s\"", get_string());
440             }
441           else
442             match_u32_assert (0);
443
444           if (version == 1)
445             {
446               /* We only have one SPV file for this version (with many
447                  tables). */
448               match_byte(0);
449               if (!match_u32(1))
450                 match_u32_assert(2);
451               match_byte(0);
452               match_byte(0);
453               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))
454                 match_u32_assert(10);
455               match_byte(0);
456               match_byte(0);
457               fprintf(stream, "/>\n");
458               return;
459             }
460
461           int outer_end = get_end();
462           
463           /* This counted-string appears to be a template string,
464              e.g. "Design\: [:^1:]1 Within Subjects Design\: [:^1:]2". */
465           char *template = dump_counted_string();
466           if (template)
467             fprintf(stream, " template=\"%s\"", template);
468
469           if (match_byte(0x31))
470             dump_style(stream);
471           else
472             match_byte_assert(0x58);
473           if (match_byte(0x31))
474             {
475               uint32_t halign = get_u32();
476               printf (" halign=\"%s\"",
477                       halign == 0 ? "center"
478                       : halign == 2 ? "left"
479                       : halign == 4 ? "right"
480                       : halign == 6 ? "decimal"
481                       : halign == 0xffffffad ? "mixed"
482                       : "<error>");
483               int valign = get_u32();
484               printf (" valign=\"%s\"",
485                       valign == 0 ? "center"
486                       : valign == 1 ? "top"
487                       : valign == 3 ? "bottom"
488                       : "<error>");
489               printf (" %g", get_double());
490               int l = get_u16();
491               int r = get_u16();
492               int t = get_u16();
493               int b = get_u16();
494               printf (" margins=\"%d %d %d %d\"", l, r, t, b);
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(" halign=%d", halign);
971
972       int valign = get_u32();
973       printf(" valign=%d", 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
981       char *alt_fgcolor = get_string();
982       if (alt_fgcolor[0])
983         printf (" altfg=\"%s\"", alt_fgcolor);
984       char *alt_bgcolor = get_string();
985       if (alt_bgcolor[0])
986         printf (" altbg=\"%s\"", alt_bgcolor);
987
988       if (version > 1)
989         {
990           printf(" margins=\"");
991           for (int i = 0; i < 4; i++)
992             {
993               if (i)
994                 putchar(' ');
995               printf("%d", get_u32());
996             }
997           putchar('"');
998         }
999
1000       printf ("/>\n");
1001     }
1002
1003   int x1 = get_u32();
1004   int x1_end = pos + x1;
1005   printf("<borders>\n");
1006   match_be32_assert(1);
1007   int n_borders = get_be32();
1008   for (int i = 0; i < n_borders; i++)
1009     {
1010       int type = get_be32();
1011       int stroke = get_be32();
1012       int color = get_be32();
1013       printf("  <border type=\"%d\" stroke=\"%s\" color=\"#%06x\"/>\n",
1014              type,
1015              (stroke == 0 ? "none"
1016               : stroke == 1 ? "solid"
1017               : stroke == 2 ? "dashed"
1018               : stroke == 3 ? "thick"
1019               : stroke == 4 ? "thin"
1020               : stroke == 5 ? "double"
1021               : "<error>"),
1022              color);
1023     }
1024   bool grid = get_byte();
1025   pos += 3;
1026   printf("  <grid show=\"%s\"/>\n", grid ? "yes" : "no");
1027   printf("</borders>\n");
1028   assert(pos == x1_end);
1029
1030   int skip = get_u32();
1031   assert(skip == 18 || skip == 25);
1032   pos += skip;
1033
1034   int x3 = get_u32();
1035   int x3_end = pos + x3;
1036   if (version == 3)
1037     {
1038       match_be32_assert(1);
1039       get_be32();
1040       printf("<settings layer=\"%d\"", get_be32());
1041       if (!get_byte())
1042         printf(" skipempty=\"false\"");
1043       if (!get_byte())
1044         printf(" showdimensionincorner=\"false\"");
1045       if (!get_byte())
1046         printf(" markers=\"numeric\"");
1047       if (!get_byte())
1048         printf(" footnoteposition=\"subscript\"");
1049       get_byte();
1050       int nbytes = get_be32();
1051       printf("\n");
1052       hex_dump(pos, nbytes);
1053       printf("\n");
1054       pos += nbytes;
1055       char *notes = get_string_be();
1056       if (notes[0])
1057         printf(" notes=\"%s\"", notes);
1058       char *look = get_string_be();
1059       if (look[0])
1060         printf(" look=\"%s\"", look);
1061       printf(">\n");
1062     }
1063   pos = x3_end;
1064
1065   /* Manual column widths, if present. */
1066   int count = get_u32();
1067   if (count > 0)
1068     {
1069       printf("<columnwidths>");
1070       for (int i = 0; i < count; i++)
1071         {
1072           if (i)
1073             putchar(' ');
1074           printf("%d", get_u32());
1075         }
1076       printf("</columnwidths>\n");
1077     }
1078
1079   const char *locale = get_string();
1080   printf ("<locale>%s</locale>\n", locale);
1081
1082   get_u32();            /* Seen: 0, UINT32_MAX, 2, 3, 4, 5, 6, 8, 9, 21, 24. */
1083   if (!match_byte(0))
1084     match_byte_assert(1);
1085   match_byte_assert(0);
1086   if (!match_byte(0))
1087     match_byte_assert(1);
1088   printf("<epoch>%d</epoch>\n", get_u32());
1089
1090   int decimal = data[pos];
1091   int grouping = data[pos + 1];
1092   if (match_byte('.'))
1093     {
1094       if (!match_byte(',') && !match_byte('\''))
1095         match_byte_assert(' ');
1096     }
1097   else
1098     {
1099       match_byte_assert(',');
1100       if (!match_byte('.') && !match_byte(' ') && !match_byte(','))
1101         match_byte_assert(0);
1102     }
1103   printf("<format decimal=\"%c\" grouping=\"", decimal);
1104   if (grouping)
1105     putchar(grouping);
1106   printf("\"/>\n");
1107   if (match_u32(5))
1108     {
1109       for (int i = 0; i < 5; i++)
1110         printf("<CC%c>%s</CC%c>\n", 'A' + i, get_string(), 'A' + i);
1111     }
1112   else
1113     match_u32_assert(0);
1114
1115   /* The last chunk is an outer envelope that contains two inner envelopes.
1116      The second inner envelope has some interesting data like the encoding and
1117      the locale. */
1118   if (version == 3)
1119     {
1120       int outer_end = get_end();
1121
1122       /* First inner envelope: byte*33 int[n] int*[n]. */
1123       int inner_len = get_u32();
1124       int inner_end = pos + inner_len;
1125       int array_start = pos + 33;
1126       match_byte_assert(0);
1127       pos++;                    /* 0, 1, 10 seen. */
1128       match_byte_assert(0);
1129       pos++;                    /* 0...11 seen. */
1130       if (!match_byte(0) && !match_byte(1) && !match_byte(2))
1131         match_byte_assert(3);
1132       if (!match_byte(0) && !match_byte(2))
1133         match_byte_assert(3);
1134       if (!match_u64(0))
1135         match_u64_assert(UINT64_MAX);
1136       match_u32_assert(0);
1137       match_u32_assert(0);
1138       match_u32_assert(0);
1139       match_u32_assert(0);
1140       match_byte_assert(0);
1141       if (!match_byte(0))
1142         match_byte_assert(1);
1143       match_byte_assert(1);
1144       pos = array_start;
1145 #if 1
1146       printf("widths:");
1147       while (pos < inner_end)
1148         printf(" %d", get_u32());
1149       printf("\n");
1150 #endif
1151       pos = inner_end;;
1152
1153       /* Second inner envelope. */
1154       assert(get_end() == outer_end);
1155
1156       match_byte_assert(1);
1157       match_byte_assert(0);
1158       if (!match_byte(3) && !match_byte(4))
1159         match_byte_assert(5);
1160       match_byte_assert(0);
1161       match_byte_assert(0);
1162       match_byte_assert(0);
1163
1164       printf("<command>%s</command>\n", get_string());
1165       printf("<subcommand>%s</subcommand>\n", get_string());
1166       printf("<language>%s</language>\n", get_string());
1167       printf("<charset>%s</charset>\n", get_string());
1168       printf("<locale>%s</locale>\n", get_string());
1169
1170       if (!match_byte(0))
1171         match_byte_assert(1);
1172       match_byte_assert(0);
1173       if (!match_byte(0))
1174         match_byte_assert(1);
1175       if (!match_byte(0))
1176         match_byte_assert(1);
1177
1178       printf("<epoch2>%d</epoch2>\n", get_u32());
1179
1180       if (match_byte('.'))
1181         {
1182           if (!match_byte(',') && !match_byte('\''))
1183             match_byte_assert(' ');
1184         }
1185       else
1186         {
1187           match_byte_assert(',');
1188           if (!match_byte('.') && !match_byte(' ') && !match_byte(','))
1189             match_byte_assert(0);
1190         }
1191
1192       printf ("small: %g\n", get_double());
1193
1194       match_byte_assert(1);
1195       if (outer_end - pos > 6)
1196         {
1197           /* There might be a pair of strings representing a dataset and
1198              datafile name, or there might be a set of custom currency strings.
1199              The custom currency strings start with a pair of integers, so we
1200              can distinguish these from a string by checking for a null byte; a
1201              small 32-bit integer will always contain a null and a text string
1202              never will. */
1203           int save_pos = pos;
1204           int len = get_u32();
1205           bool has_dataset = !memchr(&data[pos], '\0', len);
1206           pos = save_pos;
1207
1208           if (has_dataset)
1209             {
1210               printf("<dataset>%s</dataset>\n", get_string());
1211               printf("<datafile>%s</datafile>\n", get_string());
1212
1213               match_u32_assert(0);
1214
1215               time_t date = get_u32();
1216               struct tm tm = *localtime(&date);
1217               char s[128];
1218               strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S %z", &tm);
1219               printf("<date>%s</date>\n", s);
1220
1221               match_u32_assert(0);
1222             }
1223         }
1224
1225       if (match_u32(5))
1226         {
1227           for (int i = 0; i < 5; i++)
1228             printf("<CC%c>%s</CC%c>\n", 'A' + i, get_string(), 'A' + i);
1229         }
1230       else
1231         match_u32_assert(0);
1232
1233       match_byte_assert('.');
1234       if (!match_byte(0))
1235         match_byte_assert(1);
1236
1237       if (pos < outer_end)
1238         {
1239           printf("<seed>%d</seed>\n", get_u32());
1240           match_u32_assert(0);
1241         }
1242       assert(pos == outer_end);
1243
1244       pos = outer_end;
1245     }
1246   else
1247     {
1248       pos = get_end();
1249     }
1250 }
1251
1252 int
1253 main(int argc, char *argv[])
1254 {
1255   size_t start;
1256   struct stat s;
1257
1258   if (isatty(STDIN_FILENO))
1259     {
1260       fprintf(stderr, "redirect stdin from a .bin file\n");
1261       exit(1);
1262     }
1263   if (fstat(STDIN_FILENO, &s))
1264     {
1265       perror("fstat");
1266       exit(1);
1267     }
1268   n = s.st_size;
1269   data = malloc(n);
1270   if (!data)
1271     {
1272       perror("malloc");
1273       exit(1);
1274     }
1275   if (read(STDIN_FILENO, data, n) != n)
1276     {
1277       perror("read");
1278       exit(1);
1279     }
1280
1281   if (argc != 2)
1282     {
1283       fprintf (stderr, "usage: %s TYPE < .bin", argv[0]);
1284       exit (1);
1285     }
1286
1287   if (!strcmp(argv[1], "title0"))
1288     {
1289       pos = 0x27;
1290       if (match_byte (0x03)
1291           || (match_byte (0x05) && match_byte (0x58)))
1292         printf ("%s\n", get_string());
1293       else
1294         printf ("<unknown>\n");
1295       return 0;
1296     }
1297   else if (!strcmp(argv[1], "title"))
1298     {
1299       pos = 0x27;
1300       dump_title();
1301       exit(0);
1302     }
1303   else if (!strcmp(argv[1], "titleraw"))
1304     {
1305       const char fonts[] = "\x01\x31\x09\0\0\0SansSerif";
1306       start = 0x27;
1307       n = find(fonts, sizeof fonts - 1);
1308     }
1309   else if (!strcmp(argv[1], "fonts"))
1310     {
1311       const char fonts[] = "\x01\x31\x09\0\0\0SansSerif";
1312       const char styles[] = "\xf0\0\0\0";
1313       start = find(fonts, sizeof fonts - 1);
1314       n = find(styles, sizeof styles - 1);
1315     }
1316   else if (!strcmp(argv[1], "styles"))
1317     {
1318       const char styles[] = "\xf0\0\0\0";
1319       const char dimensions[] = "-,,,.\0";
1320       start = find(styles, sizeof styles - 1);
1321       n = find(dimensions, sizeof dimensions - 1) + sizeof dimensions - 1;
1322     }
1323   else if (!strcmp(argv[1], "dimensions") || !strcmp(argv[1], "all"))
1324     {
1325       pos = 0;
1326       match_byte_assert(1);
1327       match_byte_assert(0);
1328
1329       /* This might be a version number of some kind, because value 1 seems
1330          to only appear in an SPV file that also required its own weird
1331          special cases in dump_value_modifier(). */
1332       version = get_u32();
1333       pos -= 4;
1334       if (!match_u32(1))
1335         match_u32_assert(3);
1336
1337       match_byte_assert(1);
1338       for (int i = 0; i < 4; i++)
1339         if (!match_byte(0))
1340           match_byte_assert(1);
1341       get_u32();
1342
1343       int min_col_width = get_u32();
1344       int max_col_width = get_u32();
1345       int min_row_width = get_u32();
1346       int max_row_width = get_u32();
1347       printf("<label-width min-col=\"%d\" max-col=\"%d\" min-row=\"%d\" "
1348              "max-row=\"%d\"/>\n",
1349              min_col_width, max_col_width,
1350              min_row_width, max_row_width);
1351
1352       /* Offset 31. */
1353       printf("<tableid>%lld</tableid>", get_u64());
1354
1355       dump_title ();
1356       dump_fonts();
1357       dump_dims ();
1358       dump_data ();
1359       match_byte (1);
1360       if (pos != n)
1361         {
1362           fprintf (stderr, "%x / %x\n", pos, n);
1363           exit(1);
1364         }
1365       exit(0);
1366     }
1367   else if (!strcmp(argv[1], "raw"))
1368     {
1369       start = 0x27;
1370
1371       dump_raw(stdout, start, n);
1372     }
1373   else
1374     {
1375       fprintf (stderr, "unknown section %s\n", argv[1]);
1376       exit(1);
1377     }
1378
1379   return 0;
1380 }