#include <stdio.h>
#include <assert.h>

#define NEWBASE64
#ifdef NEWBASE64
static char base64vec[] =
  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:.";
#else
static char base64vec[] =
  "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#endif

/* btob64  -- convert arbitrary bits to base 64 string
 *
 * Input: bit array (represented as u_char array)
 *        number of bits in the array
 *        ptr-to-str for return string val
 *
 *  This is high magic.  Trust me.  --spaf
 */

char *
btob64(pcbitvec, pcout, numbits)
    register unsigned char *pcbitvec;
    register char  *pcout;
    int numbits;
{
    register unsigned int val;
    register int offset;
    unsigned char *pcorig = (unsigned char *) pcout;

    assert(sizeof(unsigned char) == 1);	/* everything breaks otherwise */
    assert(numbits > 0);

    val = *pcbitvec;

    offset = numbits % 6;   /* how many bits initially? */
    if (offset) 
    {
	val >>= (8 - offset);
	*pcout++ = base64vec[val & 0x1f];
    }

    for ( numbits -= offset; numbits > 0; offset += 6, numbits -= 6)
    {
	val = *pcbitvec;
	if (offset > 2) 
	{
	    offset -= 8;
	    val <<= 8;
	    val |= *++pcbitvec;
	}
	val >>= (2-offset);

	*pcout++ =  base64vec[val & 0x3f];
    }

    *pcout = '\0';

    return (char *) pcorig;
}

