aboutsummaryrefslogtreecommitdiff
path: root/src/brle-enc.c
blob: d14c462c3465043416473e0794e3d2d9ae13c93f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <wchar.h>
#include <locale.h>
#include <stdbool.h>
#include <libgen.h>

#include "config.h"

FILE *istream;
FILE *ostream;

char
getbit (void)
{
  static int byte;
  static int i = 8;
  if (i > 7) {
    byte = fgetc (istream);
    if (byte == EOF)
      return -1;
    i = 0;
  }
  char bit = byte >> i & 1;
  i += 1;
  return bit;
}

bool
put4bit (uint8_t data)
{
  static uint8_t byte;
  static bool nonempty = false;
  if (nonempty) {
    byte |= data << 4;
    fputc (byte, ostream);
    nonempty = false;
  } else {
    byte = data & (1 << 4) - 1;
    nonempty = true;
  }
  return nonempty;
}

int
main (int argc, char *argv[])
{
  setlocale (LC_ALL, "");

  if (argc != 3) {
    fprintf (stderr, "Usage: %s {infile} {outfile}\n", basename (argv[0]));
    return EXIT_FAILURE;
  }

  istream = fopen (argv[1], "rb");
  if (istream == NULL) {
    perror (NULL);
    return EXIT_FAILURE;
  }

  ostream = fopen (argv[2], "wb");
  if (ostream == NULL) {
    perror (NULL);
    return EXIT_FAILURE;
  }

  char current = getbit ();
  bool nonempty;
  while (current != -1) {
    uint8_t count = 1;
    char next;
    while ((next = getbit ()) == current && count < (1 << 3) - 1)
      ++count;

    nonempty = put4bit (current << 3 | count);

    current = next;
  }
  if (nonempty)
    put4bit (0);

  if (fclose (ostream) == EOF) {
    perror (NULL);
    return EXIT_FAILURE;
  }

  if (fclose (istream) == EOF) {
    perror (NULL);
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}