#include <stdio.h>
#include <stdlib.h>
#include "input.h"
#include "trans.h"

int
main(int argc, char *argv[])
{
    int c, n, dec, hlp;
    char *prog = *argv;
    unsigned char *b;
    FILE *fp;

    dec = hlp = 0;
    while (--argc > 0 && (*++argv)[0] == '-')
        while ((c = *++argv[0]))
            switch (c) {
                case 'd':
                    dec = 1;
                    break;
                case 'h':
                    hlp = 1;
                    break;
                default:
                    fprintf(stderr, "%s: illegal option %c\n", prog, c);
                    exit(EXIT_FAILURE);
                    break;
            }
    if (hlp) {
        fprintf(stdout, "Usage: %s -d -h file\n", prog);
    } else if (argc != 1) {
        if (dec) {
            while ((b = getsxts(stdin, &n))) {
                    b = decode(b, &n);
                    fwrite(b, sizeof(*b), n, stdout);
            }
        } else {
            while ((b = getocts(stdin, &n)))
                    printf("%s", encode(b, n));
        }
    } else {
        if ((fp = fopen(*argv, "r")) == NULL) {
            fprintf(stderr, "%s: can't open %s\n", prog, *argv);
            exit(EXIT_FAILURE);
        }
        else if (dec) {
            while ((b = getsxts(fp, &n))) {
                    b = decode(b, &n);
                    fwrite(b, sizeof(*b), n, stdout);
            }
        } else {
            while ((b = getocts(fp, &n)))
                    printf("%s", encode(b, n));
        }
        fclose(fp);
    }
    exit(EXIT_SUCCESS);
}