/*
 *				a s c r 5 0 . c
 */

/*)LIBRARY
*/

#ifdef	DOCUMENTATION

title	ascr50	Ascii to Radix 50
index		Ascii to radix 50

synopsis
	.s.nf

	ascr50(count, input, output)
	int		count;
	int		*output;
	char		*input;

description

	Convert 'count' characters from Ascii to Radix 50.  If there aren't a
	multiple of 3 characters, blanks are padded on the end.  The Ascii
	string is moved to the output when finished.  The input and output
	areas may be the same since three input characters are read for
	every two bytes of output.

bugs

#endif

#ifdef	pdp11
#define	SHORT	unsigned
#else
#define	SHORT	unsigned short
#endif

#ifdef	OLD_CODE

struct table {
	char	low, high;
	int	magic;
};

static struct table r50tab[] = {
	{ 'a',	'z',	-0140	},
	{ 'A',	'Z',	-0100	},
	{ '0',	'9',	-0022	},
	{ ' ',	' ',	-0040	},
	{ '$',	'$',	-0011	},
	{ '.',	'.',	-0022	},
	{ 0,	0, 	0	},
};
	
ascr50(count, input, output)
int		count;		/* Characters to convert		*/
char		*input;		/* Input string (ascii)			*/
SHORT int	*output;	/* Output vector (rad50)		*/
{
	register char		*wp;	/* Work area pointer		*/
	register int		byte;	/* Working byte			*/
	register struct table	*rp;	/* Rad50 table pointer		*/
	int			result;	/* Rad50 work -- gets value	*/
	char			work[3+1]; /* Gets next three bytes	*/

	for (;;) {
	    work[0] = work[1] = work[2] = ' ';
	    for (wp = work; --count >= 0;) {
		*wp++ = *input++;		/* Get one input byte	*/
		if (wp >= &work[3])
		    break;
	    }
	    if (wp == work)
		return;				/* Nothing left to do	*/
	    /*
	     * Convert 3 bytes (in word) to rad50
	     */
	    result = 0;
	    for (wp = work; wp < &work[3];) {
		byte = *wp++ & 0377;
		for (rp = r50tab; rp->low > 0; rp++) {
		    if (byte >= rp->low && byte <= rp->high)
			break;
		}
		if (rp->low == 0)
		    byte == 0;
		byte += rp->magic;
		result <<= 3;
		byte += result;
		result <<= 2;
		result += byte;
	    }
	    *output++ = result;
	}
}

#else

/*
 * Dave Conroy's algorithm
 */

ascr50(count, input, output)
int		count;		/* Characters to convert		*/
register char	*input;		/* Input string (ascii)			*/
register SHORT	int *output;	/* Output vector (rad50)		*/
{
	register int	r50;

	while (--count >= 0) {
	    r50  = 050 * 050 * r50char(*input++);
	    r50 += 050 * r50char(*input++);
	    r50 += r50char(*input++);
	    *output++ = r50;
	}
}

static int
r50char(c)
register int	c;
{
	if (c == ' ')
	    return (0);
	if (c >= 'A' && c <= 'Z')
	    return (c - 'A' + 01);
        if (c >= 'a' && c <= 'z')
	    return (c - 'a' + 01);
	if (c == '$')
	    return (033);
	if (c == '.')
	    return (034);
	if (c >= '0' && c <= '9')
	    return (c - '0' + 036);
	return (035);
}

#endif
