#include <stdlib.h>
#include <string.h>
#include "tree.h"

/* use the true versions in this file so that the original locations are inherited */
#undef tt_append
#undef Nalloc

void tt_append(node_type_t type, char *text YLINEARG)
{
	extern node_t *TOKT;
	node_t *n, *nnew, *del_start;

	/* only local tokens will work because of deletion */
	if (!loc_current->is_local)
		return;

	/* don't write newlines that are not even in the file */
	if (loc_current->soffs < 0)
		return;

	/* before the first preproc token that reveals the true file name */
	if (loc_current->cpp_file == NULL)
		return;

	/* c99tree-cpp uses this special file name for -D and friends */
	if (strcmp(loc_current->cpp_file, "<prinit>") == 0)
		return;


	nnew = Nalloc(type, text, NULL YLINEPARM);
	loc_current->twin_parent = nnew;
	nnew->loc.twin_parent = NULL;

	if (TOKT != NULL) {
			/* find the preceding token and delete anything after that (step back, jumping over \n's introduced by cpp) */
		if (TOKT->loc.soffs < nnew->loc.soffs) {
			for(n = TOKT; n->next != NULL; n = n->next) {
				if (n->next->loc.soffs >= nnew->loc.soffs)
					break;
			}
			del_start = n->next;
		}
		else {
			del_start = TOKT;
			TOKT = NULL;
		}

		/* free the rest of the nodes from del_start */
		if (del_start != NULL)
			Nfree(del_start);
	
		if (TOKT == NULL)
			TOKT = nnew;
		else
			n->next = nnew;
	}
	else
		TOKT = nnew;
}
