#define NUMBER 0
#define ALPHA 1
#include <stdio.h>
#include <string.h>


/* ================================= */
/* CHECKSUM FUNCTIONS  */

/* CHECKDIG - returns the check digit for the number in aptr with length l.
 	NOTE: when the check digit is computed to be 10 an `x' is returned.  

   This algorithm protects against interchanged digits.
*/
 
#define TEN	'x'

char GL_checkdig(aptr,l)
char *aptr;
int l;
{
int i,odds,evens,checkdigit;
	
odds = evens = 0;
i = 0;

while (i < l) {
	if (i % 2 == 0) { evens += (*(aptr+i) - '0'); }
	else { odds += (*(aptr+i) - '0'); }
	i++;
	}
checkdigit = (odds + (3 * evens)) % 11;
	
/* if the checkdigit is 10 then return the character to be used in place of ten */
if ( checkdigit == 10 ) return ( TEN );
else return(checkdigit+'0'); 
}


/* ------------ */
/* script entry point for checksum functions */
int
GL_checksum_functions( hash, name, arg, nargs, result, typ )
int hash;
char *name;
char *arg[];
int nargs;
char *result;
int *typ;
{
char *s;

if( hash == 2182 ) { /* $checksumvalid(s) -  validate s which is an integer containing a trailing check digit, 
   			using the algorithm in $ps/clibx/checkdig  */
	int i;
	i = GL_checkdig( arg[0], strlen( arg[0] ) -1 );
	if( i == arg[0][ strlen( arg[0] ) -1 ] ) sprintf( result, "1" );
	else sprintf( result, "0" );
	*typ = NUMBER;
	return( 0 );
	}

if( hash == 2412 ) { /* $checksumencode(i) - result is i with checksum digit appended. */
	long i, atol();
	char tmp[20];
	int cs;
	i = atol( arg[0] );
	sprintf( tmp, "%ld", i );
	cs = GL_checkdig( tmp, strlen( tmp ) );
	sprintf( result, "%s%c", tmp, cs );
	*typ = ALPHA;
	return( 0 );
	}
	
if( hash == 2155 ) { /* $checksumnext(s) take s which is a number including trailing checksum 
   			digit, increment number and recompute new checksum digit. */
	int cs;
	long i, atol();
	char tmp[20];
	s = arg[0];
	s[ strlen( s ) - 1 ] = '\0'; /* strip off existing checksum digit */
	i = atol( s );
	i++;
	sprintf( tmp, "%ld", i );
	cs = GL_checkdig( tmp, strlen( tmp ) );
	sprintf( result, "%s%c", tmp, cs );
	*typ = ALPHA;
	return( 0 );
	}

fprintf( stderr, "unrecognized function: %s\n", name ); /* not found */
return( 195 );
}

