]>
git.gir.st - base65536.git/blob - main.c
1 /* base65536 en- and decoder with usage similar to GNU's base64.
2 (C) 2016 Tobias Girstmair, http://isticktoit.net/
3 Released under the GNU GPL v3. See LICENSE for details. */
11 #include "base65536.h"
15 #define DEFAULT_WRAP 72
17 #define COPYRIGHT "(C) 2016 Tobias Girstmair, GPLv3"
19 "Usage: %s [OPTION]... [FILE]\n"\
20 "Options: -d (decode), -i (ignore-garbage), -w COLS (wrap, default %d) "\
21 "-v (version) -h (help)\n"
26 int i
; /*ignore-garbage*/
30 void do_encode (FILE* in
, FILE* out
, int wrap_column
);
31 void do_decode (FILE* in
, FILE* out
, int ignore_garbage
);
33 int main (int argc
, char** argv
) {
34 struct ops op
= {stdin
, 0, 0, DEFAULT_WRAP
};
37 opterr
=0; /* suppress default error messages */
38 while ( (opt
= getopt(argc
, argv
, "diw:vh")) != -1) {
40 case 'd': op
.d
= 1; break;
41 case 'i': op
.i
= 1; break;
42 case 'w': op
.w
= atoi (optarg
); break;
44 fprintf (stderr
, "base65536 %s\n%s\n", VERSION
, COPYRIGHT
);
47 fprintf (stderr
, HELP_TEXT
, argv
[0], DEFAULT_WRAP
);
50 fprintf (stderr
, "unknown option '-%c'.\n", optopt
);
54 if (argc
-optind
> 1) {
55 fprintf (stderr
, "%s: extra operand '%s'. \n", argv
[0], argv
[argc
-1]);
57 } else if (optind
< argc
) {
58 if (strcmp (argv
[optind
], "-") != 0)
59 op
.f
= fopen (argv
[optind
], "rb");
61 fprintf (stderr
, "%s: %s: %s\n", argv
[0], argv
[optind
], strerror(errno
));
67 do_decode (op
.f
, stdout
, op
.i
);
69 do_encode (op
.f
, stdout
, op
.w
);
72 if (op
.f
!= stdin
) fclose (op
.f
);
78 void do_encode (FILE* in
, FILE* out
, int wrap_column
) {
85 if ((in_char
[0] = getc(in
)) == EOF
) break;
86 in_char
[1] = getc(in
);
88 unicode_cp
= base65536_encode_char (in_char
);
89 codepoint_to_utf8 (unicode_cp
, out_utf8
);
90 fprintf (out
, "%s%s", wrap_column
&&!(cnt
%wrap_column
)&&cnt
?"\n":"", out_utf8
);
92 if (in_char
[1] == EOF
) break;
97 void do_decode (FILE* in
, FILE* out
, int ignore_garbage
) {
104 for (int i
= 0; i
< 5; i
++) {
108 } else if (i
!= 0 && c
< 0x80) { /* start of new asciichar */
112 } else if (i
!= 0 && c
>= 0xc0) { /* start of new utf8char */
119 unicode_cp
= utf8_to_codepoint (in_utf8
);
120 /* ignore ascii-chars, because base65k won't map to those (but
121 whitespace may be added by the encoder / medium) */
122 if (unicode_cp
< 0x80) continue;
124 chars_written
= base65536_decode_char (unicode_cp
, out_char
);
125 if (chars_written
> 0) {
126 fputc (out_char
[0], out
);
127 if (chars_written
==2) fputc (out_char
[1], out
);
129 if (!ignore_garbage
) {
130 fprintf (stderr
, "Unrecognized glyph %s\n", in_utf8
);