#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <mflib/exceptions.h>
#include <mfmod/mfmod.h>

/*
 * echo
 * ----
 * If the argument is of type string or number, return it unchanged.
 * Otherwise (mfmod_message), signal argument type error (e_inval).
 */
int
echo(long count, MFMOD_PARAM *p, MFMOD_PARAM *r)
{
	ASSERT_ARGCOUNT(r, count, 1);
	switch (p->type) {
	case mfmod_string:
		r->string = strdup(p->string);
		assert(r->string != NULL);
		break;

	case mfmod_number:
		r->number = p->number;
		break;

	default:
		return mfmod_error_argtype(p, r, 0, mfmod_string);
	}
	r->type = p->type;
	return 0;
}

/*
 * argcheck
 * --------
 * Checks number and types of its argument and signals a corresponding
 * exception if something's wrong.  Apart from that does nothing useful.
 *
 * Arguments:
 *  p[0]   string
 *  p[1]   number
 */
int
argcheck(long count, MFMOD_PARAM *p, MFMOD_PARAM *r)
{
	ASSERT_ARGCOUNT(r, count, 2);
	ASSERT_ARGTYPE(p, r, 0, mfmod_string);
	ASSERT_ARGTYPE(p, r, 1, mfmod_number);
	r->type = mfmod_number;
	return 0;
}

/*
 * sum(...)
 * --------
 * Returns sum of its arguments.  Intended for testing type checking in
 * variadic functions.
 *
 * Arguments: Any number (zero allowed) of numeric values.
 * Return: numeric value.
 */
int
sum(long count, MFMOD_PARAM *p, MFMOD_PARAM *r)
{
	long i;
	long sum = 0;
	
	for (i = 0; i < count; i++) {
		ASSERT_ARGTYPE(p, r, i, mfmod_number);
		sum += p[i].number;
	}
	r->type = mfmod_number;
	r->number = sum;
	return 0;	
}

