-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-
-static char *cd = "\t\n\r ";
-
-static int b2encode( FILE *inf, FILE *outf ) {
- int c;
- while ( EOF != ( c = fgetc( inf ) ) ) {
- for ( int i = 6; i >= 0; i -= 2 )
- fputc( cd[c >> i & 3], outf );
- }
- return ferror( inf );
-}
-
-static int b2decode( FILE *inf, FILE *outf ) {
- char c;
- unsigned d = 0;
- int i = 0;
- char *p;
- while ( EOF != ( c = fgetc( inf ) ) ) {
- if ( NULL == ( p = strchr( cd, c ) ) )
- return EILSEQ;
- d = d << 2 | ( p - cd );
- if ( 4 == ++i ) {
- fputc( d, outf );
- i = d = 0;
- }
- }
- return i ? -i : ferror( inf );
-}
-
-void usemsg( const char *n ) {
- fprintf( stderr, "Usage:\n%s [-c] [-d] [-t ABCD]\n", n );
- exit( EXIT_FAILURE );
-}
-
-int main( int argc, char *argv[] ) {
- int res = 0, encode = 1;
-
- for ( int oi = 1; oi < argc; ++oi ) {
- if ( 0 == strcmp( argv[oi], "-c" ) )
- encode = 1;
- else if ( 0 == strcmp( argv[oi], "-d" ) )
- encode = 0;
- else if ( 0 == strcmp( argv[oi], "-t" ) ) {
- ++oi;
- if ( oi >= argc || strlen( argv[oi] ) < 4 )
- usemsg( argv[0] );
- cd = argv[oi];
- }
- else
- usemsg( argv[0] );
- }
- res = encode ? b2encode( stdin, stdout ) : b2decode( stdin, stdout );
- exit( res ? EXIT_FAILURE : EXIT_SUCCESS );
-}