diff options
Diffstat (limited to 'src/brle-enc.c')
| -rw-r--r-- | src/brle-enc.c | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/src/brle-enc.c b/src/brle-enc.c new file mode 100644 index 0000000..d14c462 --- /dev/null +++ b/src/brle-enc.c | |||
| @@ -0,0 +1,94 @@ | |||
| 1 | #include <stdlib.h> | ||
| 2 | #include <stdio.h> | ||
| 3 | #include <stdint.h> | ||
| 4 | #include <wchar.h> | ||
| 5 | #include <locale.h> | ||
| 6 | #include <stdbool.h> | ||
| 7 | #include <libgen.h> | ||
| 8 | |||
| 9 | #include "config.h" | ||
| 10 | |||
| 11 | FILE *istream; | ||
| 12 | FILE *ostream; | ||
| 13 | |||
| 14 | char | ||
| 15 | getbit (void) | ||
| 16 | { | ||
| 17 | static int byte; | ||
| 18 | static int i = 8; | ||
| 19 | if (i > 7) { | ||
| 20 | byte = fgetc (istream); | ||
| 21 | if (byte == EOF) | ||
| 22 | return -1; | ||
| 23 | i = 0; | ||
| 24 | } | ||
| 25 | char bit = byte >> i & 1; | ||
| 26 | i += 1; | ||
| 27 | return bit; | ||
| 28 | } | ||
| 29 | |||
| 30 | bool | ||
| 31 | put4bit (uint8_t data) | ||
| 32 | { | ||
| 33 | static uint8_t byte; | ||
| 34 | static bool nonempty = false; | ||
| 35 | if (nonempty) { | ||
| 36 | byte |= data << 4; | ||
| 37 | fputc (byte, ostream); | ||
| 38 | nonempty = false; | ||
| 39 | } else { | ||
| 40 | byte = data & (1 << 4) - 1; | ||
| 41 | nonempty = true; | ||
| 42 | } | ||
| 43 | return nonempty; | ||
| 44 | } | ||
| 45 | |||
| 46 | int | ||
| 47 | main (int argc, char *argv[]) | ||
| 48 | { | ||
| 49 | setlocale (LC_ALL, ""); | ||
| 50 | |||
| 51 | if (argc != 3) { | ||
| 52 | fprintf (stderr, "Usage: %s {infile} {outfile}\n", basename (argv[0])); | ||
| 53 | return EXIT_FAILURE; | ||
| 54 | } | ||
| 55 | |||
| 56 | istream = fopen (argv[1], "rb"); | ||
| 57 | if (istream == NULL) { | ||
| 58 | perror (NULL); | ||
| 59 | return EXIT_FAILURE; | ||
| 60 | } | ||
| 61 | |||
| 62 | ostream = fopen (argv[2], "wb"); | ||
| 63 | if (ostream == NULL) { | ||
| 64 | perror (NULL); | ||
| 65 | return EXIT_FAILURE; | ||
| 66 | } | ||
| 67 | |||
| 68 | char current = getbit (); | ||
| 69 | bool nonempty; | ||
| 70 | while (current != -1) { | ||
| 71 | uint8_t count = 1; | ||
| 72 | char next; | ||
| 73 | while ((next = getbit ()) == current && count < (1 << 3) - 1) | ||
| 74 | ++count; | ||
| 75 | |||
| 76 | nonempty = put4bit (current << 3 | count); | ||
| 77 | |||
| 78 | current = next; | ||
| 79 | } | ||
| 80 | if (nonempty) | ||
| 81 | put4bit (0); | ||
| 82 | |||
| 83 | if (fclose (ostream) == EOF) { | ||
| 84 | perror (NULL); | ||
| 85 | return EXIT_FAILURE; | ||
| 86 | } | ||
| 87 | |||
| 88 | if (fclose (istream) == EOF) { | ||
| 89 | perror (NULL); | ||
| 90 | return EXIT_FAILURE; | ||
| 91 | } | ||
| 92 | |||
| 93 | return EXIT_SUCCESS; | ||
| 94 | } | ||
