#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <signal.h>
#include <cjson/cJSON.h>
#include <bencoding.c>
#define S0(x) (x ? x : "")
int main (int argc, char ** argv) {
if (argc != 1+1)
error_at_line(1, 0, __FILE__, __LINE__, "%s encode < json || %s decode < bencoding", S0(argv[0]), S0(argv[0]));
int size = 2048;
int len = 0;
char * in = malloc(size);
while (!feof(stdin) && !ferror(stdin)) {
if (!in)
error_at_line(2, 0, __FILE__, __LINE__, "heap alloc failed");
len += fread(in, 1, size-len-1, stdin);
if ((size - len) < 1024)
in = realloc(in, size *= 2);
}
if (argv[1][0] == 'e')
error_at_line(3, 0, __FILE__, __LINE__, "N/I");
struct bencoding * bencoding = bdecode(in, size, terminate);
len = b2json_length(bencoding);
char out[len+1];
char * end = b2json(out, bencoding);
*end = '\0';
puts(out);
if (end - out != len)
error_at_line(4, 0, __FILE__, __LINE__, "b2json wrote %ld instead of %d bytes.", end-out, len);
fprintf(stderr, "len: %d\n", len);
free_bencoding(bencoding);
free(in);
return 0;
}