#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include "debug.h"
#include "lib.h"
static char	vec[] =
	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	
int decode_base64(char *buf, char *out, int max);
int decode_uu(char *line, char *out, int max);
int decode_base64_safe(char *buf, char *out, int maxout);

int decode_base64(char *buf, char *out, int max)
{
	return decode_base64_safe(buf,out,max);
}
int decode_base64_safe(char *buf, char *out, int maxout)
{
	int	i, num=0, len, j;
	int nout=0;
	long	d, val;
	char	nw[4], *p, *c;

	len = strlen(buf)-1;
	for (i = 0; i < len; i += 4)	{
		val = 0;
		num = 3;
		c = buf+i; 
		if (c[2] == '=')
			num = 1;
		else if (c[3] == '=') 
			num = 2;
		for (j = 0; j <= num; j++){
			if (!(p = strchr(vec, c[j]))) {
				return -1;
			}
			d = p-vec;
			d <<= (3-j)*6;
			val += d;
		}
		for (j = 2; j >= 0; j--){
			nw[j] = val & 255;
			val >>= 8;
		}
		if (maxout>0) if (nout+num>=maxout) break;
		//safe_memcpy(out+nout,nw,num,out,maxout);
		memcpy(out+nout,nw,num); 
		nout += num;
	}
	out[nout] = 0;
	return nout;
}

#define DEC(c)	(((c) - ' ') & 077)

int decode_uu(char *line, char *out, int max)
{
    int c, len;
    int nout=0;

	max--;
    len = DEC(*line++);
    while (len) {
	c = DEC(*line) << 2 | DEC(line[1]) >> 4;
	out[nout++] = c;
	if (--len) {
	    c = DEC(line[1]) << 4 | DEC(line[2]) >> 2;
		if (nout>=max) break;
	    out[nout++] = c;
	    if (--len) {
		c = DEC(line[2]) << 6 | DEC(line[3]);
	        out[nout++] = c;
		len--;
	    }
	}
	line += 4;
    }
    out[nout] = 0;
    return nout;
}

    
