/*--
  This file is a part of ZetaGrid, a simple and secure Grid Computing
  kernel.

  Copyright (c) 2001-2004 Sebastian Wedeniwski.  All rights reserved.

  Use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:

  1. The source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.

  2. The origin of this software must not be misrepresented; you must 
     not claim that you wrote the original software.  If you plan to
     use this software in a product, please contact the author.

  3. Altered source versions must be plainly marked as such, and must
     not be misrepresented as being the original software. The author
     must be informed about these changes.

  4. The name of the author may not be used to endorse or promote 
     products derived from this software without specific prior written 
     permission.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  Version 1.9.0, February 8, 2004

  This program is based on the work of:
     S. Wedeniwski
--*/

package zeta.util;

import java.util.Arrays;

/**
 *  Base64 is a system for representing raw byte data as ASCII characters.
 *  RFC 1521 is NOT implemented since the characters '-','.','*' are used instead of '+','/','='
 *  Then the encoded data can be used in URL.
**/
public class Base64 {
  public static char PAD = '*';   // use '=' for RFC 1521
  private static char ENCODING_62 = '-';   // use '+' for RFC 1521
  private static char ENCODING_63 = '.';   // use '/' for RFC 1521

  /**
   *  Encodes a string into Base64 format.
   *  No blanks or line breaks are inserted.
   *  RFC 1521 is NOT implemented since the output string is repesented in one line
   *  and not in lines of more than 76 characters each.
   *  @param data a raw byte data to be encoded.
   *  @return a string with the Base64 encoded data.
  **/
  public static String encode(byte[] data) {
    final int dataLength = data.length;
    char[] encodedData = new char[((dataLength+2)/3) << 2];   // including padding
    for (int i = 0, j = 3; j <= dataLength; j += 3, i += 4) {
      int d = ((data[j-3] & 255) << 16) | ((data[j-2] & 255) << 8) | (data[j-1] & 255);
      encodedData[i] = encodeMap[(d >> 18) & 63];
      encodedData[i+1] = encodeMap[(d >> 12) & 63];
      encodedData[i+2] = encodeMap[(d >> 6) & 63];
      encodedData[i+3] = encodeMap[d & 63];
    }
    int m = dataLength%3;
    if (m == 1) {
      int d = data[dataLength-1] & 255;
      encodedData[encodedData.length-4] = encodeMap[(d >> 2) & 63];
      encodedData[encodedData.length-3] = encodeMap[(d << 4) & 63];
      encodedData[encodedData.length-2] = PAD;
      encodedData[encodedData.length-1] = PAD;
    } else if (m == 2) {
      int d = ((data[dataLength-2] & 255) << 8) | (data[dataLength-1] & 255);
      encodedData[encodedData.length-4] = encodeMap[(d >> 10) & 63];
      encodedData[encodedData.length-3] = encodeMap[(d >> 4) & 63];
      encodedData[encodedData.length-2] = encodeMap[(d << 2) & 63];
      encodedData[encodedData.length-1] = PAD;
    }
    return new String(encodedData);
  }

  /**
   *  Decodes Base64 data.
   *  All line breaks or other characters not found in the encoding table will be ignored.
   *  @param encodedData string containing the Base64 encoded data with a length equal to 0 mod 4.
   *  @return raw byte data containing the decoded data.
   *  @throws IllegalArgumentException if the input is not valid Base64 encoded data.
  **/
  public static byte[] decode(String encodedData) {
    char[] encodedDataArray = encodedData.toCharArray();
    int encodedDataLength = encodedDataArray.length;
    // RFC 1521: all line breaks or other characters not found in the encoding table must be ignored by decoding software
    int countIgnoredCharacters = 0;
    for (int i = 0; i < encodedDataLength; ++i) {
      int b = encodedDataArray[i];
      if (b < 0 || b > 127 || decodeMap[b] < 0 && encodedDataArray[i] != PAD) {
        ++countIgnoredCharacters;
      }
    }
    if (countIgnoredCharacters > 0) {
      char[] c = new char[encodedDataLength-countIgnoredCharacters];
      for (int i = 0, j = 0; i < encodedDataLength; ++i) {
        int b = encodedDataArray[i];
        if (b >= 0 && b <= 127 && (decodeMap[b] >= 0 || encodedDataArray[i] == PAD)) {
          c[j++] = encodedDataArray[i];
        }
      }
      encodedDataArray = c;
      encodedDataLength = c.length;
    }
    if ((encodedDataLength&3) != 0) {
      throw new IllegalArgumentException("Length of Base64 encoded input string is " + encodedDataLength + " which is not a multiple of 4.");
    }
    int dataLength = 3*encodedDataLength/4;
    if (encodedDataLength > 0 && encodedDataArray[encodedDataLength-1] == PAD) {
      encodedDataArray[encodedDataLength-1] = encodeMap[0];
      dataLength = (3*(encodedDataLength-1))/4;
      if (encodedDataArray[encodedDataLength-2] == PAD) {
        dataLength = (3*(encodedDataLength-2))/4;
        encodedDataArray[encodedDataLength-2] = encodeMap[0];
        if (encodedDataArray[encodedDataLength-3] == PAD) {
          dataLength = (3*(encodedDataLength-3))/4;
          encodedDataArray[encodedDataLength-3] = encodeMap[0];
          if (encodedDataArray[encodedDataLength-4] == PAD) {
            throw new IllegalArgumentException("Base64 encoded input string contains too many padding characters.");
          }
        }
      }
    }
    byte[] data = new byte[dataLength];
    int j = 3;
    for (int i = 4; j <= dataLength; i += 4, j += 3) {
      int b = (decodeMap[encodedDataArray[i-4]] << 18) | (decodeMap[encodedDataArray[i-3]] << 12)
              | (decodeMap[encodedDataArray[i-2]] << 6) | decodeMap[encodedDataArray[i-1]];
      data[j-3] = (byte)((b >> 16) & 255);
      data[j-2] = (byte)((b >> 8) & 255);
      data[j-1] = (byte)(b & 255);
    }
    if (j-2 == dataLength) {
      int b = (decodeMap[encodedDataArray[encodedDataLength-4]] << 2) | (decodeMap[encodedDataArray[encodedDataLength-3]] >> 4);
      data[j-3] = (byte)(b & 255);
    } else if (j-1 == dataLength) {
      int b = (decodeMap[encodedDataArray[encodedDataLength-4]] << 10) | (decodeMap[encodedDataArray[encodedDataLength-3]] << 4)
              | (decodeMap[encodedDataArray[encodedDataLength-2]] >> 2);
      data[j-3] = (byte)((b >> 8) & 255);
      data[j-2] = (byte)(b & 255);
    }
    return data;
  }

  /**
   *  Decodes a character to an integer less than 64
   *  and returns -1 for a not defined character
  **/
  private static byte[] decodeMap = new byte[128];

  /**
   *  Converts an integer less than 64 to a character
  **/
  private static char[] encodeMap = new char[64];

  static {
    for (int i = 0; i <= 25; ++i) {
      encodeMap[i] = (char)('A' + i);
    }
    for (int i = 26; i <= 51; ++i) {
      encodeMap[i] = (char)('a' + i - 26);
    }
    for (int i = 52; i <= 61; ++i) {
      encodeMap[i] = (char)('0' + i - 52);
    }
    encodeMap[62] = ENCODING_62; encodeMap[63] = ENCODING_63;
    Arrays.fill(decodeMap, (byte)-1);
    for (int i = 0; i < 64; ++i) {
      decodeMap[encodeMap[i]] = (byte)i;
    }
  }

  public static void main(String[] args) {
    try {
      java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
      StreamUtils.writeData(new java.io.FileInputStream(args[0]), out, true, true);
      System.out.println(Arrays.equals(decode(encode(out.toByteArray())), out.toByteArray()));
    } catch (java.io.IOException ioe) {
      ioe.printStackTrace();
    }
  }
}