/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.util;

public class Base64Encoder
	{
  	StringBuffer output;
	char[] triplet;
	
	public Base64Encoder()
		{
		output = new StringBuffer();
		triplet = new char[4];
		}

	public synchronized String encode( byte[] input )
		{
   	output.setLength( 0 );
   	for ( int i = 0; i < input.length; i+=3 )
      	encodeTriplet( input, i );
      	
   	return output.toString();
		}
  
	private synchronized void encodeTriplet( byte[] input, int offset )
		{
   	int block = 0;
   	int slack = input.length - offset - 1;
   	
   	int end = (slack >= 2) ? 2 : slack;
   	for ( int i = 0; i <= end; i++ )
   		{
      	byte b = input[offset + i];
      	int neuter = (b < 0) ? b + 256 : b;
      	block += neuter << (8 * (2 - i));
   		}
   		
   	for (int i = 0; i < 4; i++)
   		{
      	int sixbit = (block >>> (6 * (3 - i))) & 0x3f;
      	triplet[i] = getChar(sixbit);
   		}

   	if (slack < 1) triplet[2] = '=';
   	if (slack < 2) triplet[3] = '=';
   	
   	output.append( triplet );
		}
  
	protected static char getChar( int sixBit )
		{
		if (sixBit >= 0 && sixBit <= 25)
			return (char)('A' + sixBit);
		if (sixBit >= 26 && sixBit <= 51)
			return (char)('a' + (sixBit - 26));
		if (sixBit >= 52 && sixBit <= 61)
			return (char)('0' + (sixBit - 52));
		if (sixBit == 62) return '+';
		if (sixBit == 63) return '/';
		return '?';
		}
	}

