/*
 * OpenMRCP - Open Source Media Resource Control Protocol Stack
 * Copyright (C) 2007, Cepstral LLC
 *
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Author(s):
 * Arsen Chaloyan <achaloyan@yahoo.com>
 *
 * Contributor(s):
 *
 */

#include "apt_string_table.h"
#include "apt_text_stream.h"

static apt_bool_t is_unique(apt_string_table_t table, size_t count, size_t item_index, size_t char_index, char value)
{
	size_t i;
	for(i=0; i<count; i++) {
		if(i != item_index && char_index < table[i].length && value == table[i].value[char_index]) {
			return FALSE;
		}
	}
	return TRUE;
}

static apt_bool_t string_table_key_generate(apt_string_table_t table, size_t count)
{
	size_t i,j;
	size_t length;
	for(i=0; i<count; i++) {
		length = strlen(table[i].value);
		table[i].key = length;
		for(j=0; j<length; j++) {
			if(is_unique(table,count,i,j,table[i].value[j]) == TRUE) {
				table[i].key = j;
				break;
			}
		}
	}
	return TRUE;
}

#define TEST_BUFFER_SIZE 2048
static char parse_buffer[TEST_BUFFER_SIZE];

static size_t string_table_read(apt_string_table_t table, FILE *f)
{
	apt_text_stream_t text_stream;
	size_t count = 0;
	char *line;

	text_stream.size = fread(parse_buffer, 1, sizeof(parse_buffer)-1, f);
	parse_buffer[text_stream.size] = '\0';

	text_stream.buffer = parse_buffer;
	text_stream.pos = parse_buffer;

	do {
		line = apt_read_line(&text_stream);
		if(!line) {
			break;
		}
		if(*line == '\0') {
			break;
		}
		table[count].value = line;
		table[count].length = strlen(line);
		table[count].key = 0;
		count++;
	}
	while(line);

	return count;
}

static apt_bool_t string_table_write(apt_string_table_t table, size_t count, FILE *f)
{
	size_t i;
	for(i=0; i<count; i++) {
		fprintf(f,"{\"%s\",%"APR_SIZE_T_FMT",%"APR_SIZE_T_FMT"},\n",table[i].value,table[i].length,table[i].key);
	}
	
	return TRUE;
}



int main(int argc, char *argv[])
{
	apt_string_table_item_t table[100];
	size_t count;
	
	FILE *f1, *f2;
	if(argc < 2) {
		printf("usage: stringtablegen stringtable.in [stringtable.out]\n");
		return 0;
	}
	f1 = fopen(argv[1], "rb");
	if(f1 == NULL) {
		printf("cannot open file %s\n", argv[1]);
		return 0;
	}

	if(argc > 2) {
		f2 = fopen(argv[2], "wb");
	}
	else {
		f2 = stdout;
	}

	count = string_table_read(table,f1);

	string_table_key_generate(table,count);
	
	string_table_write(table, count,f2);

	fclose(f1);
	if(f2 != stdout) {
		fclose(f2);
	}
	return 0;
}
