/* Copyright (c) 1993 by Sanjay Ghemawat */
#include <stdio.h>
#include <string.h>

#include "Array.h"
#include "arrays.h"
#include "lexer.h"
#include "unparsed.h"

static const char opener = '[';
static const char closer = ']';

struct UnparsedItem {
    char* id;
    char* value;
};

declareArray(UnparsedItemList,UnparsedItem)
implementArray(UnparsedItemList,UnparsedItem)

UnparsedItems::UnparsedItems() {
    list = 0;
    buffer = 0;
}

UnparsedItems::~UnparsedItems() {
    if (list != 0) {
	for (int i = 0; i < list->size(); i++) {
	    delete list->slot(i).id;
	    delete list->slot(i).value;
	}
	delete list;
    }
    if (buffer != 0) {
	delete buffer;
    }
}

int UnparsedItems::Read(char const* id, Lexer* lexer) {
    /* Read value into buffer */
    if (buffer == 0) {
	buffer = new charArray;
    }
    buffer->clear();

    while (1) {
	char c;
	if (! lexer->Peek(c)) return 0;
	if (c == closer) {
	    /* Got it */
	    break;
	}

	lexer->Next(c);
	buffer->append(c);
	if (c == '\\') {
	    /* Add next character too */
	    if (! lexer->Next(c)) return 0;
	    buffer->append(c);
	}
    }

    /* Got value in buffer */
    buffer->append('\0');

    UnparsedItem item;
    item.id = new char[strlen(id) + 1];
    strcpy(item.id, id);
    item.value = new char[buffer->size()];
    strcpy(item.value, buffer->as_pointer());

    if (list == 0) {
	list = new UnparsedItemList;
    }
    list->append(item);

    return 1;
}

void UnparsedItems::Write(FILE* out) const {
    if (list != 0) {
	for (int i = 0; i < list->size(); i++) {
	    fprintf(out, "%s [%s]\n", list->slot(i).id, list->slot(i).value);
	}
    }
}
