/*
** GHBase64.c - 
** Copyright (C) 1996-97 Serge Emond
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <exec/types.h>
#include <exec/memory.h>
#include <proto/exec.h>
#include <string.h>
#include "GHBase64.h"

TEXT base64table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

TEXT *EnBaseString(TEXT *str)
{
	LONG i, c1, c2, c3, wrote;
	TEXT *to;
	
	if (strlen(str) > MAXPWLENGTH)
		return(NULL);

	if (to = (TEXT *)AllocMem(MAXBASELENGTH, MEMF_CLEAR|MEMF_REVERSE)) {

		c1=-1;c2=-1;c3=-1;wrote=0;
	
		for (i=0; (c3=(LONG)str[i]); i++) {
			if (c1 < 0)
				c1 = c3;
			else if (c2 < 0)
				c2 = c3;
			else {
				EnBase64(to+(wrote*4), c1, c2, c3);
				c1=-1;c2=-1;c3=-1;
				wrote++;
			}
		}
		EnBase64(to+(wrote*4), c1, c2, -1);
		return(to);
	}
	return(NULL);
}

void EnBase64(three, c1, c2, c3)
TEXT *three;
LONG c1, c2, c3;
{
	if (c1 < 0)
		return;

	three[0] = (UBYTE) base64table[c1 >> 2];
	if (c2 < 0)
		three[1] = (UBYTE) base64table[(c1 & 3) << 4];
	else
		three[1] = (UBYTE) base64table[((c1 & 3) << 4) + (c2 >> 4)];

	if (c2 < 0)
		three[2] = (UBYTE) '=';
	else if (c3 < 0)
		three[2] = (UBYTE) base64table[(c2 & 15) << 2];
	else
		three[2] = (UBYTE) base64table[((c2 & 15) << 2) + (c3 >> 6)];

	if (c3 < 0)
		three[3] = (UBYTE) '=';
	else
		three[3] = (UBYTE) base64table[c3 & 63];
}
