/*
 * This is yet another protocol for scriptcontext. This is for variable 
 * terminated protocols. The Astriums have deliverd the SANS-2 NVS with 
 * a protocol which uses a \n as a terminator most of the time but sometimes 
 * a \. This protocl handler expects messages in the form: terminator:payload
 * The caller is responsible for providing the proper send termiantor.
 * 
 * copyright: see file COPYRIGHT
 * 
 * Mark Koennecke, April 2009
 */
#include <errno.h>
#include <ascon.h>
#include <ascon.i>
#include <dynstring.h>

/*-----------------------------------------------------------------------------*/
int TermProtHandler(Ascon *a)
{
	char *data, *copy, *colon;
	
	switch (a->state) {
	  case AsconWriteStart:
	    data = GetCharArray(a->wrBuffer);
	    copy = strdup(data);
	    if(copy){
	    	colon = strstr(copy,":");
	    	if(colon){
	    		*colon = '\0';
	    		if(a->replyTerminator != NULL){
	    			free(a->replyTerminator);
	    		}
	    		a->replyTerminator = strdup(copy);
	    		colon++;
	    		DynStringClear(a->wrBuffer);
	    		DynStringConcat(a->wrBuffer,colon);
	    	}
	    	free(copy);
	    }
		a->state = AsconWriting;
	    a->wrPos = 0;
	    break;
	}
	return AsconStdHandler(a);
}
/*-------------------------------------------------------------------------*/
void AddTermProtocoll()
{
  AsconProtocol *prot = NULL;

  prot = calloc(sizeof(AsconProtocol), 1);
  prot->name = strdup("varterm");
  prot->init = AsconStdInit;
  prot->handler = TermProtHandler;
  AsconInsertProtocol(prot);
}
