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

#include "bfcode.h"

char version[]={"$VER: BFEncode V1.1 (" __DATE__ ")"};

FILE *infile,*outfile;

#define rnd(x) (rand()%(x))

long linelen;
long quotemode;

void codenibble(long nibble)
{
   int lastch;

   if(linelen>64) {
      fprintf(outfile,"\n");
		if(quotemode) {
			for(lastch=0; lastch<quotemode; lastch++) fprintf(outfile,"> ");
		}
   		if(quotemode>1 && !rnd(4)) quotemode--;
                linelen=0;
   }
   else if(linelen) fprintf(outfile," ");
   fprintf(outfile,codetab[nibble]);
   linelen+=strlen(codetab[nibble]);
   if(!rnd(8)) {
	fprintf(outfile,"%c","...?!,,,;,,"[(lastch=rnd(11))]);
	if(quotemode<2 && !rnd(7) && lastch<5) {
		fprintf(outfile,"\n\n");
		if(!quotemode && !rnd(9)) { quotemode=rnd(5)+1; linelen=999; return;}
		else quotemode=0;
		linelen=0;
	}
   }
   else if(linelen<30 && !rnd(32)) fprintf(outfile," -");
}

void main(int argc, char **argv)
{
   int c=0,ch;

   srand((long)argv[2]);
   printf("\x1b[1m%s\x1b[0m\n",&version[6]);

   if(argc!=3) {
      printf("Usage: %s infile outfile\n",argv[0]);
      exit(0);
   }
   if(!(infile=fopen(argv[1],"r"))) {
      printf("can't open input file %s\n",argv[1]);
      exit(10);
   }
   if(!(outfile=fopen(argv[2],"w"))) {
      printf("can't open output file %s\n",argv[2]);
      exit(10);
   }

   while((ch=fgetc(infile))!=EOF) {
      c++;
      codenibble(ch&0x0f);
      codenibble((ch>>4)&0x0f);
   }
   fprintf(outfile,"\n");
   printf("coded %ld bytes, ok\n",c);
   exit(0);
}
