/* $Id: cheat.c,v 1.11 2005/09/15 15:03:17 cegger Exp $
******************************************************************************

   This LibGIC module is a very simple parser keyboard cheats.

   Copyright (C) 1999 Andreas Beck	[becka@ggi-project.org]

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************************
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <ggi/internal/gic.h>
#include <ggi/internal/gic_debug.h>

#include <ggi/gg.h>


/* The first poly is CRC-32, which is AFAIK known good.
 * The second is its bitreverse. Does that raise a simple method to
 * calculate the CRC2 from the CRC1 ? Any maths people out there ?
 */
#define POLY1	0x04c11db7
#define POLY2	0xdb710641

#define CRC_INIT    0xffffffff
#define CRC_TOPMASK 0x80000000

#define MAXKEYS 32

struct cheatpress
{ 
	int numkeys;
	uint32_t seed;
	uint32_t check1;
	uint32_t keybuf[MAXKEYS];
};

static int cheat_check(gic_handle_t hand, gic_recognizer *ctrl,
		gii_event *event,gic_feature *feature,int recnum);

static int cheat_get_name(gic_handle_t hand, gic_recognizer *ctrl,
		char *string,size_t maxlen);

static int cheat_write_pvtdata(gic_handle_t hand, gic_recognizer *ctrl,
			char *string,int maxlen);

static int cheat_read_pvtdata(gic_handle_t hand, gic_recognizer *ctrl,
			const char *string);

static void cheat_free_pvtdata(gic_handle_t hand, gic_recognizer *ctrl);

static int cheat_train(gic_handle_t hand, gic_recognizer **ctrl,
		gii_event *event);

static int cheat_check_conflict(gic_handle_t hand, gic_recognizer *ctrl,
		gic_recognizer *ctrl2);

static int cheat_get_opposite (gic_handle_t hand, gic_recognizer *recognizer,
		gic_recognizer **opposite);



static gic_recognizerdriver mycontrols = {
	"Cheat",
	cheat_check,
	cheat_get_name,
	cheat_write_pvtdata,
	cheat_read_pvtdata,
	cheat_free_pvtdata,
	cheat_train,
	cheat_check_conflict,
	cheat_get_opposite,
};


static uint32_t crc_add(uint32_t oldval,uint32_t add,uint32_t poly)
{
	int x;

	for(x = 0; x < 32; x++, add <<= 1) {
		if ( (oldval & CRC_TOPMASK) != (add & CRC_TOPMASK) ) {
			oldval <<= 1;
			oldval ^= poly;
		} else {
			oldval <<= 1;
		}
	}
	return oldval;
}

static int chkcheat(gic_handle_t hand, struct cheatpress *kp,
		uint32_t newlabel,gic_feature *feature,int recnum)
{
	uint32_t crc1,crc2;
	int x;

#if 0 /* Foo? */
	DPRINT_LIBS("Cheat: cheatEvent L%04x,B%04xS%04x [want %c,%04x].\n",
		event->cheat.label,event->cheat.button,event->cheat.sym,
		modemap[kp->mode],kp->value);
#endif

	/* Copy up the key-remember array. 
	 */
	memmove(&kp->keybuf[0],&kp->keybuf[1],(kp->numkeys-1)*sizeof(kp->keybuf[0]));
	kp->keybuf[kp->numkeys-1]=newlabel;
	
	crc1 = crc2 = CRC_INIT;
	
	for(x = 0; x < kp->numkeys; x++) {
		crc1=crc_add(crc1,kp->keybuf[x],POLY1);
		crc2=crc_add(crc2,kp->keybuf[x],POLY2);
	}
	crc1 = crc_add(crc1,kp->seed,POLY1);
	crc2 = crc_add(crc2,kp->seed,POLY2);

	if (crc1 == kp->check1) {
		if ((gic_state)crc2 < GIC_STATE_MIN) crc2 = -crc2;
		while(crc2 > GIC_STATE_MAX) crc2 -= GIC_STATE_MAX;
		gicFeatureActivate(hand, feature,(gic_state)(crc2),
				GIC_FLAG_PULSE,recnum);
		return 1;
	}

	return 0;
}

static int cheat_check(gic_handle_t hand, gic_recognizer *ctrl,
		gii_event *event,gic_feature *feature,int recnum)
{
	DPRINT_LIBS("Cheat: Check with %p,%p.\n",ctrl,event);
	switch(event->any.type) {
	case evKeyPress:
		return chkcheat(hand, ctrl->privdata,event->key.label,feature,recnum);
	}
	return 0;
}

static struct cheatpress trainingstate;

static int cheat_register(gic_handle_t hand, gic_recognizer **ctrl)
{
	gic_recognizer *rl;
	struct cheatpress *mkp;

	for(rl=*ctrl;rl!=NULL;rl=rl->next) {
		if (rl->driver==&mycontrols) {	/* We always attach one control max */
			/* Update, we _must_ be better. */
			memcpy(rl->privdata,&trainingstate,sizeof(trainingstate));
			return 1;
		}
	}

	rl = malloc(sizeof(gic_recognizer));
	if (rl == NULL) return GGI_ENOMEM;

	mkp = malloc(sizeof(struct cheatpress));
	if (mkp == NULL) {
		free(rl);
		return GGI_ENOMEM;
	}
	
	memcpy(mkp,&trainingstate,sizeof(trainingstate));
	rl->driver=&mycontrols;
	rl->confidence=GIC_STATE_MIN;	/* We are pretty unlikely to be meant */
	rl->privdata=mkp;
	gicRecognizerTrainAdd(hand, ctrl, rl);
	return 1;
}

static int    cheat_train(gic_handle_t hand, gic_recognizer **ctrl,gii_event *event)
{
	int x;

	DPRINT_LIBS("Cheat: Training with %p,%p.\n",ctrl,event);

	if (event) {
		DPRINT_LIBS("Cheat: Analyzing event ...\n");
		if (event->any.type==evKeyPress) {	/* O.K. remember the press */
			if (trainingstate.numkeys<MAXKEYS) {
				trainingstate.keybuf[trainingstate.numkeys++]=
					event->key.label;
				trainingstate.check1=CRC_INIT;
				for(x=0;x<trainingstate.numkeys;x++) {
					trainingstate.check1=
						crc_add(trainingstate.check1,
							trainingstate.keybuf[x],POLY1);
				}
				trainingstate.check1=
					crc_add(trainingstate.check1,
						trainingstate.seed,POLY1);
			}
			DPRINT_LIBS("Cheat: %2d %08x %08x\n",trainingstate.numkeys,
				trainingstate.seed,trainingstate.check1);
			return cheat_register(hand, ctrl);
		}
	} else {
		trainingstate.numkeys=0;
		DPRINT_LIBS("Cheat: Initialized training state.\n");
	}
	return 0;
}

/*
 * Privatedata format is :
 * len (dez,2 digits) seed check1 (hex, 8 digits)
 * modes are : KeyLabel (0), Keycode (1), KeySymbol (2)
 * value is the appropriate value of the corresponding field.
 */
 
static int cheat_write_pvtdata(gic_handle_t hand, gic_recognizer *ctrl,
			char *string,int maxlen)
{
	struct cheatpress *cheatp=ctrl->privdata;

	if (maxlen < 20) {
		*string='\0';
		return GGI_ENOSPACE;
	}
	sprintf(string,"%2d %08x %08x",cheatp->numkeys,cheatp->seed,cheatp->check1);

	return 0;
}

static int cheat_read_pvtdata(gic_handle_t hand, gic_recognizer *ctrl,
			const char *string)
{
	struct cheatpress *cheatp;

	cheatp=ctrl->privdata=malloc(sizeof(struct cheatpress));
	sscanf(string,"%d %x %x",&cheatp->numkeys,&cheatp->seed,&cheatp->check1);

	return 0;
}

static void cheat_free_pvtdata(gic_handle_t hand, gic_recognizer *ctrl)
{
	struct cheatpress *cheatp=ctrl->privdata;

	free(cheatp);ctrl->privdata=NULL;
	
	return;
}

static int cheat_get_name(gic_handle_t hand, gic_recognizer *ctrl,
		char *string,size_t maxlen)
{
/*	struct cheatpress *cheatp=ctrl->privdata;*/

	ggstrlcpy(string,"CHEAT",maxlen);
	return 0;
}

static int cheat_check_conflict(gic_handle_t hand, gic_recognizer *ctrl,
		gic_recognizer *ctrl2)
{
	return GIC_C_NOCONFLICT;	/* Cheats never conflict - well, we can't check it :-)  */
}

static int cheat_get_opposite (gic_handle_t hand, gic_recognizer *recognizer,
		gic_recognizer **opposite)
{
	return GGI_ENOMATCH;	/* Cheats have no natural opposite */
}


EXPORTFUNC gic_recognizerdriver *GICdl_cheat(void);

gic_recognizerdriver *GICdl_cheat(void)
{
	trainingstate.seed=rand();
	return &mycontrols;
}
