#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "vargs.h"
#include "mawk.h"
#include "memory.h"
#include "regexp.h"

void mawk_exit_(mawk_state_t *MAWK, int x)
{
	fprintf(stderr, "mawk_exit\n");
	exit(1);
}

char *mawk_str_str(register char *target, char *key, unsigned key_len)
{
	register int k = key[0];

	switch (key_len) {
	case 0:
		return (char *) 0;
	case 1:
		return strchr(target, k);
	case 2:
		{
			int k1 = key[1];
			while ((target = strchr(target, k)))
				if (target[1] == k1)
					return target;
				else
					target++;
			/*failed */
			return (char *) 0;
		}
	}

	key_len--;
	while ((target = strchr(target, k))) {
		if (strncmp(target + 1, key + 1, key_len) == 0)
			return target;
		else
			target++;
	}
	/*failed */
	return (char *) 0;
}

void mawk_rt_error VA_ALIST(const char *, format)
{
	va_list args;

	fprintf(stderr, "%s: run time error: ", MAWK->progname);
	VA_START(args, char *, format);
	vfprintf(stderr, format, args);
	va_end(args);
	putc('\n', stderr);
	exit(1);
}


void mawk_compile_error VA_ALIST(const char *, format)
{
	va_list args;
	const char *s0, *s1;

	/* with multiple program files put program name in
	   error message */
	if (MAWK->ps.pfile_name) {
		s0 = MAWK->ps.pfile_name;
		s1 = ": ";
	}
	else {
		s0 = s1 = "";
	}

	fprintf(stderr, "%s: %s%sline %u: ", MAWK->progname, s0, s1, MAWK->token_lineno);
	VA_START(args, char *, format);
	vfprintf(stderr, format, args);
	va_end(args);
	fprintf(stderr, "\n");
	if (++(MAWK->compile_error_count) == MAX_COMPILE_ERRORS)
		mawk_exit(MAWK, 2);
}


#define test(str) \
	do { \
		PTR p = mawk_REcompile(MAWK, str); \
		printf("%s -> %s %d\n", str,  p == NULL ? "err" : "ok", MAWK->REerrno); \
	} while(0)

int main()
{
	mawk_state_t MAWK_, *MAWK = &MAWK_;

	memset(MAWK, 0, sizeof(mawk_state_t));

	test("foo");
	test(")");
	test("(");
	test("[abc");
	test("foo|");
	test("(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)+)");
	test("^*hah");
	/* TODO: how to cause E7? */


	mawk_free_all(MAWK);

	return 0;
}
