/*
 * wmlc.c - very simple WML compiler based on Kannel Gateway library
 * 
 * Sebastien Aperghis-Tramoni <maddingue@free.fr>
 */

/* ANSI includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

/* Kannel Gateway includes */
#include "gwlib/gwlib.h"
#include "gw/wml_compiler.h"

static void usage(void) {
	fputs("usage: wmlc input.wml [output.wmlc]\n", stderr);
	exit(0);
}

static void fatal(const char * message) {
	fputs("wmlc: ", stderr);
	fputs(message, stderr);
	if(errno != 0) {
		fputs(": ", stderr);
		fputs(strerror(errno), stderr);
	}
	fputs("\n", stderr);
	exit(-1);
}

int main(int argc, char ** argv) {
	char * input = NULL;  
	char * output = NULL;  
	FILE * out_fd = NULL;
	Octstr * wml_text = NULL;
	Octstr * charset = NULL;
	Octstr * wml_binary = NULL;
	int err = 0;
	
	if((argc < 2) || (argc > 3)) usage();
	if(strncmp(argv[1], "-h", 2) == 0) usage();
	
	input = argv[1];
	
	if(argc == 2) {
		size_t len = strlen(input);
		output = (char *) gw_malloc((len+2)*sizeof(char));
		if(output == NULL) fatal("malloc failed");
		strncpy(output, input, len);
		output[len] = 'c';
		output[len+1] = '\0';
	}
	
	/* initialize Kannel Gateway */
	gwlib_init();
	
	/* read WML file */
	wml_text = octstr_read_file(input);
	if(wml_text == NULL) fatal("cannot read WML file");
	
	/* compile WML */
	err = wml_compile(wml_text, charset, &wml_binary);
	
	/* write WML binary */
	if(strncmp(output, "-", 1) == 0) {
		out_fd = stdout;
	} else {
		out_fd = fopen(output, "w");
		if(out_fd == NULL) fatal("cannot write WML binary");
	}
	octstr_print(out_fd, wml_binary);
	fclose(out_fd);
	octstr_destroy(wml_binary);
	
	/* cleans up */
	if (charset != NULL) octstr_destroy(charset);
	octstr_destroy(wml_text);
	
	return 0;
}

