#include <stdio.h>
#include <libmawk.h>

/*
	Purpose: demonstrate how to call an awk user function from the app
	Run: ./app -f test.awk
*/

int main(int argc, char **argv)
{
	mawk_state_t *m;
	mawk_cell_t ret = libmawk_empty_cell;

	/* init a context, execute BEGIN */
	m = libmawk_initialize(argc, argv);
	if (m == NULL) {
		fprintf(stderr, "libmawk_initialize failed, exiting\n");
		return 1;
	}

	/* call user function foo with 3 arguments; the "format string" is similar
	   to printf's without "%":  d (int), f (float) and s (\0 terminated string)
	   The actual arguments are taken as varargs. This function is designed
	   for static calls.
	   NOTE: expect the function to return; that is, the function may not getline
	         from FIFOs, as that may cause them to return as "interrupted waiting
	         for input" in which case the app should fill the FIFO and resume
	         running the function.
	*/
	if (libmawk_call_function(m, "foo", &ret, "dfs", (int)42, (double)1.234, (char *)"test string1.") == MAWK_EXER_FUNCRET) {
		char buff[32];
		printf("app: return value of foo is '%s'\n", libmawk_print_cell(m, &ret, buff, sizeof(buff)));
		libmawk_cell_destroy(m, &ret);
	}
	else {
		printf("app: error: function foo didn't return\n");
		goto quit;
	}

	/* this is the same function call with a syntax more suitable for dynamic
	   calls. Same limitation on getline applies. */
	{
		int i = 42;
		double d = 1.234;
		char *s = "test string2.";
		void *args[] = {&i, &d, s};
		if (libmawk_call_functionp(m, "foo", &ret, "dfs", args) == MAWK_EXER_FUNCRET) {
			char buff[32];
			printf("app: return value of func foo '%s'\n", libmawk_print_cell(m, &ret, buff, sizeof(buff)));
			libmawk_cell_destroy(m, &ret);
		}
		else {
			printf("app: error: function foo didn't return\n");
			goto quit;
		}
	}


quit:;
	/* run END and free the context */
	libmawk_uninitialize(m);

	return 0;
}

