#ifndef STRINGTOKENIZER_H
#define STRINGTOKENIZER_H

/*
 * @(#)StringTokenizer.h
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2003 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 */

#include "String.h"

class NoSuchElementException {
};

class StringTokenizer {
	private: const char *str0;
	private: char *str1;
	private: const char *delimiters;
	private: int pos;

	public: StringTokenizer(
			const char *str,
			const char *delim = " \t\n\r\f") {
		str0 = strDup(str);
		str1 = strDup(str);
		delimiters = strDup(delim);
		pos = 0;
	}

	public: ~StringTokenizer() {
		delete[] delimiters;
		delete[] str1;
		delete[] str0;
	}

	private: int isDelimiter(char ch) {
		for (int i = 0; delimiters[i] != 0; i++)
			if (delimiters[i] == ch)
				return 1;
		return 0;
	}

	public: const char *nextToken(const char *delim = "") {
		if (delim[0] != 0) {
			delete[] delimiters;
			delimiters = strDup(delim);
		}

		while (str0[pos] != 0 && isDelimiter(str0[pos]))
			pos++;
		if (str0[pos] == 0)
			throw new NoSuchElementException();
		int pos0 = pos;

		while (str0[pos] != 0 && !isDelimiter(str0[pos]))
			pos++;
		str1[pos] = 0;

		return &str1[pos0];
	}

	private: char *strDup(const char *orig) {
		int len = strlen(orig);
		char *copy = new char[len + 1];
		strncpy(copy, orig, len);
		copy[len] = 0;
		return copy;
	}
};

#endif
