
/* swtrutil.c */

#include <stdio.h>
#include "swtr_driver.h"
#include "video_conf.h"


/* -------------------------------------------------------------- */

SWTR_ptr
swtrutil_open( devtbl, num )

	VCONF_DEVTABLE *devtbl;
	int		num;
{
char *calloc();
SWTR_ptr	swtr;
char devport[64];
int res;

	if( !devtbl || num<0 || (num+1)>devtbl->ndevs )
	{
		fprintf(stderr,"swtrutil_open: given bad devtable or number\n");
		return NULL;
	}
	if( devtbl->dev[num].type != SWTR_DEV )
	{
		fprintf(stderr,"swtrutil_open: device is not a SWTR\n");
		return NULL;
	}

	swtr = (SWTR_ptr) calloc( 1, sizeof(SWTR) );
	if( swtr == NULL )
		return NULL;

	strcpy(devport,"/dev/");
	strcat(devport,devtbl->dev[num].tty);

	if( (swtr->fd = ttyutil_open(
		devport,
		devtbl->dev[num].baud,
		devtbl->dev[num].parity) ) == -1 )
	{
		fprintf(stderr,"swtrutil_open: unable to open SWTR device\n");
		free( (char *) swtr );
		return NULL;
	}

	strcpy(swtr->port,devport);
	strcpy(swtr->devname,devtbl->dev[num].name);
	strcpy(swtr->model,devtbl->dev[num].model);

	res = vconf_find_model( swtr->model );
	switch( res )
	{
	case 2:	/* from the model_table in video_conf.c */
		a4x1_setfuncs( swtr );	/* sets the # of inputs and outputs */
		break;
	default:
		printf("swtrutil_open: bad model <%s>\n",swtr->model);
		free( (char *) swtr );
		return NULL;
		break;
	}

	(*swtr->reset)(swtr);
	return swtr;
}

/* -------------------------------------------------------------- */

SWTR_ptr
swtrutil_close( swtr )

	SWTR_ptr swtr;
{
	ttyutil_close( swtr->fd );
	free( (char *) swtr );
	return NULL;
}

/* -------------------------------------------------------------- */

	/*
	 	the following utilities encode/decode the 3
		input channel settings for a given output 
		channel to/from an integer; the 3 lowest nibbles
		are used, thus:

		0 0 0 0 | 0 0 0 0 | 0 0 0 0 | 0 0 0 0
	     	    	   left      right    video

		where each nibble is 0-15 (1-4 in case of a4x1)
	*/

int
swtrutil_encode_settings( video, left, right )

	int	video,left,right;
{
int	temp = 0;

	/* assume the numbers are okay */

	temp |= (video & 0xf);
	temp |= ( (right & 0xf) << 4 );
	temp |= ( (left & 0xf) << 8 );
	return temp;
}

/* -------------------------------------------------------------- */

int
swtrutil_decode_settings( code, vptr, lptr, rptr )

	int	code;
	int *	vptr;
	int *	lptr;
	int *	rptr;
{
int	temp = 0;

	if( !vptr || !lptr || !rptr )
		return -1;

	/* assume the numbers are okay */

	*vptr = ( code & 0xf );
	*lptr = ( (code & 0xf0) >> 4 );
	*rptr = ( (code & 0xf00) >> 8 );
	return 0;
}
