/********************************************
vars.c

libmawk changes (C) 2009-2010, Tibor 'Igor2' Palinkas;
based on mawk code coming with the below copyright:

copyright 1991, Michael D. Brennan

This is a source file for mawk, an implementation of
the AWK programming language.

Mawk is distributed without warranty under the terms of
the GNU General Public License, version 2, 1991.
********************************************/

#include "vars.h"
#include "symtype.h"
#include "zmalloc.h"
#include "cell.h"

mawk_cell_t *mawk_get_var(mawk_state_t *MAWK, const char *vname)
{
	SYMTAB *fs;

	fs = mawk_find(MAWK, vname, 0);

	/* does symbol exist at all? */
	if (fs == NULL)
		return NULL;

	/* return it if it is a variable */
	if ((fs->type == ST_VAR) || (fs->type == ST_NR) || (fs->type == ST_FIELD) || (fs->type == ST_ARRAY))
		return fs->stval.cp;

	return NULL;
}

mawk_cell_t *mawk_create_var(mawk_state_t *MAWK, const char *name, mawk_cell_t **fp)
{
	SYMTAB *stp;
	mawk_cell_t *cp;
	static mawk_cell_t cell;										/* used if command line assign to pseudo field */

	stp = mawk_find(MAWK, name, 1);

	switch (stp->type) {
	case ST_NONE:
		stp->type = ST_VAR;
		stp->stval.cp = cp = MAWK_ZMALLOC(MAWK, mawk_cell_t);
		break;

	case ST_VAR:
	case ST_NR:									/* !! no one will do this */
		cp = stp->stval.cp;
		mawk_cell_destroy(MAWK, cp);
		break;

	case ST_FIELD:
		if (fp == NULL)
			return NULL;
		/* must be pseudo field */
		*fp = stp->stval.cp;
		cp = &cell;
		break;

	default:
		return NULL;
	}
	return cp;
}
