Debian Codegraph @

terps/scott/ai_uk/decompresstext.c

raw symbols SCIP
1 //
2 // decompresstext.c
3 // part of ScottFree, an interpreter for adventures in Scott Adams format
4 //
5 // Created by Petter Sjölund on 2022-01-10.
6 //
7
8 #include <ctype.h>
9 #include <string.h>
10
11 #include "decompresstext.h"
12
13 #include "scott.h"
14
15 char *DecompressText(uint8_t *source, int stringindex)
16 {
17 // Lookup table
18 const char *alphabet = " abcdefghijklmnopqrstuvwxyz'\x01,.\x00";
19
20 int c, uppercase, i, j;
21 uint8_t decompressed[256];
22 int idx = 0;
23
24 // Find the start of the compressed message
25 for (i = 0; i < stringindex; i++) {
26 source += *source & 0x7F;
27 };
28
29 uppercase = ((*source & 0x40) == 0); // Test bit 6
30
31 source++;
32 do {
33 // Get eight characters squeezed into five bytes
34 uint64_t fortybits = ((uint64_t)source[0] << 32) | ((uint64_t)source[1] << 24) | ((uint64_t)source[2] << 16) | ((uint64_t)source[3] << 8) | source[4];
35 source += 5;
36 for (j = 35; j >= 0; j -= 5) {
37 // Decompress one character:
38 int next = (fortybits >> j) & 0x1f;
39 c = alphabet[next];
40
41 if (c == 0x01) {
42 uppercase = 1;
43 c = ' ';
44 }
45
46 if (c >= 'a' && uppercase) {
47 c = toupper(c);
48 uppercase = 0;
49 }
50 decompressed[idx++] = c;
51
52 if (idx > 255)
53 return NULL;
54
55 if (idx == 255)
56 c = 0; // We've gone too far, return
57
58 if (c == 0) {
59 char *result = malloc(idx);
60 memcpy(result, decompressed, idx);
61 return result;
62 } else if (c == '.' || c == ',') {
63 if (c == '.')
64 uppercase = 1;
65 decompressed[idx++] = ' ';
66 }
67 }
68 } while (idx < 0xff); // Chosen arbitrarily, might be too small
69 return NULL;
70 }