#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

void usage()
{
	fprintf(stderr, "\nbit-stream -d delimiter -D word-delimiter\n");
	exit(0);
}

int
main(int argc, char **argv)
{
	char *delimiter = strdup("\n");
	char *word_del  = strdup("\n");
	int ch;
	int unstream;

	unstream = 0;
	while ((ch = getopt(argc, argv, "d:uD:")) != -1) {
		switch (ch) {
		case 'd':
			delimiter = strdup(optarg);
			break;
		case 'D':
			word_del = strdup(optarg);
			break;
		case 'u':
			unstream = 1;
			break;
		default:
			usage();
		}
	}

	if (unstream) {
		int nr;
		int bit;

		ch = 0;
		nr = 1;
		while ((bit = getchar()) != EOF) {
			switch(bit) {
			case '1':
				ch <<= 1;
				ch += 1;
				break;
			case '0':
				ch <<= 1;
				break;
			case '\n':
			case '\r':
				continue;
			default:
				fprintf(stderr, "Conversion failed.\n");
				exit(0);
			}
			if (!(nr & 07))
				printf("%c", ch);
			++ nr;
		}
	} else while ((ch = getchar()) != EOF) {
		int bit;

		for (bit = 7 ; bit >= 0 ; -- bit)
			printf("%i%s", (ch & (1 << bit)) ? 1 : 0, delimiter);
		printf("%s", word_del);
	}

	free(delimiter);
	free(word_del);
}
