org.apache.xml.utils.XMLString

public interface XMLString
{

  /**
   * Directly call the
   * characters method on the passed ContentHandler for the
   * string-value. Multiple calls to the
   * ContentHandler's characters methods may well occur for a single call to
   * this method.
   *
   * @param ch A non-null reference to a ContentHandler.
   *
   * @throws org.xml.sax.SAXException
   */
  public abstract void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
    throws org.xml.sax.SAXException;

  /**
   * Directly call the
   * comment method on the passed LexicalHandler for the
   * string-value.
   *
   * @param lh A non-null reference to a LexicalHandler.
   *
   * @throws org.xml.sax.SAXException
   */
  public abstract void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh)
    throws org.xml.sax.SAXException;

  /**
   * Conditionally trim all leading and trailing whitespace in the specified String.
   * All strings of white space are
   * replaced by a single space character (#x20), except spaces after punctuation which
   * receive double spaces if doublePunctuationSpaces is true.
   * This function may be useful to a formatter, but to get first class
   * results, the formatter should probably do it's own white space handling
   * based on the semantics of the formatting object.
   *
   * @param   trimHead    Trim leading whitespace?
   * @param   trimTail    Trim trailing whitespace?
   * @param   doublePunctuationSpaces    Use double spaces for punctuation?
   * @return              The trimmed string.
   */
  public XMLString fixWhiteSpace(boolean trimHead,
                                 boolean trimTail,
                                 boolean doublePunctuationSpaces);

  /**
   * Returns the length of this string.
   *
   * @return  the length of the sequence of characters represented by this
   *          object.
   */
  public abstract int length();

  /**
   * Returns the character at the specified index. An index ranges
   * from 0 to length() - 1. The first character
   * of the sequence is at index 0, the next at index
   * 1, and so on, as for array indexing.
   *
   * @param      index   the index of the character.
   * @return     the character at the specified index of this string.
   *             The first character is at index 0.
   * @exception  IndexOutOfBoundsException  if the index
   *             argument is negative or not less than the length of this
   *             string.
   */
  public abstract char charAt(int index);

  /**
   * Copies characters from this string into the destination character
   * array.
   *
   * @param      srcBegin   index of the first character in the string
   *                        to copy.
   * @param      srcEnd     index after the last character in the string
   *                        to copy.
   * @param      dst        the destination array.
   * @param      dstBegin   the start offset in the destination array.
   * @exception IndexOutOfBoundsException If any of the following
   *            is true:
   *

srcBegin is negative.
   *
srcBegin is greater than srcEnd
   *
srcEnd is greater than the length of this
   *                string
   *
dstBegin is negative
   *
dstBegin+(srcEnd-srcBegin) is larger than
   *                dst.length

   * @exception NullPointerException if dst is null
   */
  public abstract void getChars(int srcBegin, int srcEnd, char dst[],
                                int dstBegin);

  /**
   * Compares this string to the specified object.
   * The result is true if and only if the argument is not
   * null and is a String object that represents
   * the same sequence of characters as this object.
   *
   * @param   anObject   the object to compare this String
   *                     against.
   * @return  true if the String are equal;
   *          false otherwise.
   * @see     java.lang.String#compareTo(java.lang.String)
   * @see     java.lang.String#equalsIgnoreCase(java.lang.String)
   */
  public abstract boolean equals(XMLString anObject);

  /**
   * Compares this string to the specified object.
   * The result is true if and only if the argument is not
   * null and is a String object that represents
   * the same sequence of characters as this object.
   *
   * @param   anObject   the object to compare this String
   *                     against.
   * @return  true if the String are equal;
   *          false otherwise.
   * @see     java.lang.String#compareTo(java.lang.String)
   * @see     java.lang.String#equalsIgnoreCase(java.lang.String)
   */
  public abstract boolean equals(Object anObject);

  /**
   * Compares this String to another String,
   * ignoring case considerations.  Two strings are considered equal
   * ignoring case if they are of the same length, and corresponding
   * characters in the two strings are equal ignoring case.
   *
   * @param   anotherString   the String to compare this
   *                          String against.
   * @return  true if the argument is not null
   *          and the Strings are equal,
   *          ignoring case; false otherwise.
   * @see     #equals(Object)
   * @see     java.lang.Character#toLowerCase(char)
   * @see java.lang.Character#toUpperCase(char)
   */
  public abstract boolean equalsIgnoreCase(String anotherString);

  /**
   * Compares two strings lexicographically.
   *
   * @param   anotherString   the String to be compared.
   * @return  the value 0 if the argument string is equal to
   *          this string; a value less than 0 if this string
   *          is lexicographically less than the string argument; and a
   *          value greater than 0 if this string is
   *          lexicographically greater than the string argument.
   * @exception java.lang.NullPointerException if anotherString
   *          is null.
   */
  public abstract int compareTo(XMLString anotherString);

  /**
   * Compares two strings lexicographically, ignoring case considerations.
   * This method returns an integer whose sign is that of
   * this.toUpperCase().toLowerCase().compareTo(
   * str.toUpperCase().toLowerCase()).
   *

   * Note that this method does not take locale into account,
   * and will result in an unsatisfactory ordering for certain locales.
   * The java.text package provides collators to allow
   * locale-sensitive ordering.
   *
   * @param   str   the String to be compared.
   * @return  a negative integer, zero, or a positive integer as the
   *          the specified String is greater than, equal to, or less
   *          than this String, ignoring case considerations.
   * @see     java.text.Collator#compare(String, String)
   * @since   1.2
   */
  public abstract int compareToIgnoreCase(XMLString str);

  /**
   * Tests if this string starts with the specified prefix beginning
   * a specified index.
   *
   * @param   prefix    the prefix.
   * @param   toffset   where to begin looking in the string.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the substring of this object starting
   *          at index toffset; false otherwise.
   *          The result is false if toffset is
   *          negative or greater than the length of this
   *          String object; otherwise the result is the same
   *          as the result of the expression
   *

   *          this.subString(toffset).startsWith(prefix)
   *

   * @exception java.lang.NullPointerException if prefix is
   *          null.
   */
  public abstract boolean startsWith(String prefix, int toffset);

  /**
   * Tests if this string starts with the specified prefix beginning
   * a specified index.
   *
   * @param   prefix    the prefix.
   * @param   toffset   where to begin looking in the string.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the substring of this object starting
   *          at index toffset; false otherwise.
   *          The result is false if toffset is
   *          negative or greater than the length of this
   *          String object; otherwise the result is the same
   *          as the result of the expression
   *

   *          this.subString(toffset).startsWith(prefix)
   *

   * @exception java.lang.NullPointerException if prefix is
   *          null.
   */
  public abstract boolean startsWith(XMLString prefix, int toffset);

  /**
   * Tests if this string starts with the specified prefix.
   *
   * @param   prefix   the prefix.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the character sequence represented by
   *          this string; false otherwise.
   *          Note also that true will be returned if the
   *          argument is an empty string or is equal to this
   *          String object as determined by the
   *          {@link #equals(Object)} method.
   * @exception java.lang.NullPointerException if prefix is
   *          null.
   * @since   JDK1. 0
   */
  public abstract boolean startsWith(String prefix);

  /**
   * Tests if this string starts with the specified prefix.
   *
   * @param   prefix   the prefix.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the character sequence represented by
   *          this string; false otherwise.
   *          Note also that true will be returned if the
   *          argument is an empty string or is equal to this
   *          String object as determined by the
   *          {@link #equals(Object)} method.
   * @exception java.lang.NullPointerException if prefix is
   *          null.
   * @since   JDK1. 0
   */
  public abstract boolean startsWith(XMLString prefix);

  /**
   * Tests if this string ends with the specified suffix.
   *
   * @param   suffix   the suffix.
   * @return  true if the character sequence represented by the
   *          argument is a suffix of the character sequence represented by
   *          this object; false otherwise. Note that the
   *          result will be true if the argument is the
   *          empty string or is equal to this String object
   *          as determined by the {@link #equals(Object)} method.
   * @exception java.lang.NullPointerException if suffix is
   *          null.
   */
  public abstract boolean endsWith(String suffix);

  /**
   * Returns a hashcode for this string. The hashcode for a
   * String object is computed as
   *

   * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
   *

   * using int arithmetic, where s[i] is the
   * ith character of the string, n is the length of
   * the string, and ^ indicates exponentiation.
   * (The hash value of the empty string is zero.)
   *
   * @return  a hash code value for this object.
   */
  public abstract int hashCode();

  /**
   * Returns the index within this string of the first occurrence of the
   * specified character. If a character with value ch occurs
   * in the character sequence represented by this String
   * object, then the index of the first such occurrence is returned --
   * that is, the smallest value k such that:
   *

   * this.charAt(k) == ch
   *

   * is true. If no such character occurs in this string,
   * then -1 is returned.
   *
   * @param   ch   a character.
   * @return  the index of the first occurrence of the character in the
   *          character sequence represented by this object, or
   *          -1 if the character does not occur.
   */
  public abstract int indexOf(int ch);

  /**
   * Returns the index within this string of the first occurrence of the
   * specified character, starting the search at the specified index.
   *

   * If a character with value ch occurs in the character
   * sequence represented by this String object at an index
   * no smaller than fromIndex, then the index of the first
   * such occurrence is returned--that is, the smallest value k
   * such that:
   *

   * (this.charAt(k) == ch) && (k >= fromIndex)
   *

   * is true. If no such character occurs in this string at or after
   * position fromIndex, then -1 is returned.
   *

   * There is no restriction on the value of fromIndex. If it
   * is negative, it has the same effect as if it were zero: this entire
   * string may be searched. If it is greater than the length of this
   * string, it has the same effect as if it were equal to the length of
   * this string: -1 is returned.
   *
   * @param   ch          a character.
   * @param   fromIndex   the index to start the search from.
   * @return  the index of the first occurrence of the character in the
   *          character sequence represented by this object that is greater
   *          than or equal to fromIndex, or -1
   *          if the character does not occur.
   */
  public abstract int indexOf(int ch, int fromIndex);

  /**
   * Returns the index within this string of the last occurrence of the
   * specified character. That is, the index returned is the largest
   * value k such that:
   *

   * this.charAt(k) == ch
   *

   * is true.
   * The String is searched backwards starting at the last character.
   *
   * @param   ch   a character.
   * @return  the index of the last occurrence of the character in the
   *          character sequence represented by this object, or
   *          -1 if the character does not occur.
   */
  public abstract int lastIndexOf(int ch);

  /**
   * Returns the index within this string of the last occurrence of the
   * specified character, searching backward starting at the specified
   * index. That is, the index returned is the largest value k
   * such that:
   *

   * this.charAt(k) == ch) && (k <= fromIndex)
   *

   * is true.
   *
   * @param   ch          a character.
   * @param   fromIndex   the index to start the search from. There is no
   *          restriction on the value of fromIndex. If it is
   *          greater than or equal to the length of this string, it has
   *          the same effect as if it were equal to one less than the
   *          length of this string: this entire string may be searched.
   *          If it is negative, it has the same effect as if it were -1:
   *          -1 is returned.
   * @return  the index of the last occurrence of the character in the
   *          character sequence represented by this object that is less
   *          than or equal to fromIndex, or -1
   *          if the character does not occur before that point.
   */
  public abstract int lastIndexOf(int ch, int fromIndex);

  /**
   * Returns the index within this string of the first occurrence of the
   * specified substring. The integer returned is the smallest value
   * k such that:
   *

   * this.startsWith(str, k)
   *

   * is true.
   *
   * @param   str   any string.
   * @return  if the string argument occurs as a substring within this
   *          object, then the index of the first character of the first
   *          such substring is returned; if it does not occur as a
   *          substring, -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public abstract int indexOf(String str);

  /**
   * Returns the index within this string of the first occurrence of the
   * specified substring. The integer returned is the smallest value
   * k such that:
   *

   * this.startsWith(str, k)
   *

   * is true.
   *
   * @param   str   any string.
   * @return  if the string argument occurs as a substring within this
   *          object, then the index of the first character of the first
   *          such substring is returned; if it does not occur as a
   *          substring, -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public abstract int indexOf(XMLString str);

  /**
   * Returns the index within this string of the first occurrence of the
   * specified substring, starting at the specified index. The integer
   * returned is the smallest value k such that:
   *

   * this.startsWith(str, k) && (k >= fromIndex)
   *

   * is true.
   *

   * There is no restriction on the value of fromIndex. If
   * it is negative, it has the same effect as if it were zero: this entire
   * string may be searched. If it is greater than the length of this
   * string, it has the same effect as if it were equal to the length of
   * this string: -1 is returned.
   *
   * @param   str         the substring to search for.
   * @param   fromIndex   the index to start the search from.
   * @return  If the string argument occurs as a substring within this
   *          object at a starting index no smaller than
   *          fromIndex, then the index of the first character
   *          of the first such substring is returned. If it does not occur
   *          as a substring starting at fromIndex or beyond,
   *          -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null
   */
  public abstract int indexOf(String str, int fromIndex);

  /**
   * Returns the index within this string of the rightmost occurrence
   * of the specified substring.  The rightmost empty string "" is
   * considered to occur at the index value this.length().
   * The returned index is the largest value k such that
   *

   * this.startsWith(str, k)
   *

   * is true.
   *
   * @param   str   the substring to search for.
   * @return  if the string argument occurs one or more times as a substring
   *          within this object, then the index of the first character of
   *          the last such substring is returned. If it does not occur as
   *          a substring, -1 is returned.
   * @exception java.lang.NullPointerException  if str is
   *          null.
   */
  public abstract int lastIndexOf(String str);

  /**
   * Returns the index within this string of the last occurrence of
   * the specified substring.
   *
   * @param   str         the substring to search for.
   * @param   fromIndex   the index to start the search from. There is no
   *          restriction on the value of fromIndex. If it is greater than
   *          the length of this string, it has the same effect as if it
   *          were equal to the length of this string: this entire string
   *          may be searched. If it is negative, it has the same effect
   *          as if it were -1: -1 is returned.
   * @return  If the string argument occurs one or more times as a substring
   *          within this object at a starting index no greater than
   *          fromIndex, then the index of the first character of
   *          the last such substring is returned. If it does not occur as a
   *          substring starting at fromIndex or earlier,
   *          -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public abstract int lastIndexOf(String str, int fromIndex);

  /**
   * Returns a new string that is a substring of this string. The
   * substring begins with the character at the specified index and
   * extends to the end of this string.

   * Examples:
   *

   * "unhappy".substring(2) returns "happy"
   * "Harbison".substring(3) returns "bison"
   * "emptiness".substring(9) returns "" (an empty string)
   *

   *
   * @param      beginIndex   the beginning index, inclusive.
   * @return     the specified substring.
   * @exception  IndexOutOfBoundsException  if
   *             beginIndex is negative or larger than the
   *             length of this String object.
   */
  public abstract XMLString substring(int beginIndex);

  /**
   * Returns a new string that is a substring of this string. The
   * substring begins at the specified beginIndex and
   * extends to the character at index endIndex - 1.
   * Thus the length of the substring is endIndex-beginIndex.
   *
   * @param      beginIndex   the beginning index, inclusive.
   * @param      endIndex     the ending index, exclusive.
   * @return     the specified substring.
   * @exception  IndexOutOfBoundsException  if the
   *             beginIndex is negative, or
   *             endIndex is larger than the length of
   *             this String object, or
   *             beginIndex is larger than
   *             endIndex.
   */
  public abstract XMLString substring(int beginIndex, int endIndex);

  /**
   * Concatenates the specified string to the end of this string.
   *
   * @param   str   the String that is concatenated to the end
   *                of this String.
   * @return  a string that represents the concatenation of this object's
   *          characters followed by the string argument's characters.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public abstract XMLString concat(String str);

  /**
   * Converts all of the characters in this String to lower
   * case using the rules of the given Locale.
   *
   * @param locale use the case transformation rules for this locale
   * @return the String, converted to lowercase.
   * @see     java.lang.Character#toLowerCase(char)
   * @see     java.lang.String#toUpperCase(Locale)
   */
  public abstract XMLString toLowerCase(Locale locale);

  /**
   * Converts all of the characters in this String to lower
   * case using the rules of the default locale, which is returned
   * by Locale.getDefault.
   *

   *
   * @return  the string, converted to lowercase.
   * @see     java.lang.Character#toLowerCase(char)
   * @see     java.lang.String#toLowerCase(Locale)
   */
  public abstract XMLString toLowerCase();

  /**
   * Converts all of the characters in this String to upper
   * case using the rules of the given locale.
   * @param locale use the case transformation rules for this locale
   * @return the String, converted to uppercase.
   * @see     java.lang.Character#toUpperCase(char)
   * @see     java.lang.String#toLowerCase(Locale)
   */
  public abstract XMLString toUpperCase(Locale locale);

  /**
   * Converts all of the characters in this String to upper
   * case using the rules of the default locale, which is returned
   * by Locale.getDefault.
   *
   *

   * If no character in this string has a different uppercase version,
   * based on calling the toUpperCase method defined by
   * Character, then the original string is returned.
   *

   * Otherwise, this method creates a new String object
   * representing a character sequence identical in length to the
   * character sequence represented by this String object and
   * with every character equal to the result of applying the method
   * Character.toUpperCase to the corresponding character of
   * this String object.

   * Examples:
   *

   * "Fahrvergnügen".toUpperCase() returns "FAHRVERGNÜGEN"
   * "Visit Ljubinje!".toUpperCase() returns "VISIT LJUBINJE!"
   *

   *
   * @return  the string, converted to uppercase.
   * @see     java.lang.Character#toUpperCase(char)
   * @see     java.lang.String#toUpperCase(Locale)
   */
  public abstract XMLString toUpperCase();

  /**
   * Removes white space from both ends of this string.
   *

   * If this String object represents an empty character
   * sequence, or the first and last characters of character sequence
   * represented by this String object both have codes
   * greater than '\u0020' (the space character), then a
   * reference to this String object is returned.
   *

   * Otherwise, if there is no character with a code greater than
   * '\u0020' in the string, then a new
   * String object representing an empty string is created
   * and returned.
   *

   * Otherwise, let k be the index of the first character in the
   * string whose code is greater than '\u0020', and let
   * m be the index of the last character in the string whose code
   * is greater than '\u0020'. A new String
   * object is created, representing the substring of this string that
   * begins with the character at index k and ends with the
   * character at index m-that is, the result of
   * this.substring(k, m+1).
   *

   * This method may be used to trim
   * {@link Character#isSpace(char) whitespace} from the beginning and end
   * of a string; in fact, it trims all ASCII control characters as well.
   *
   * @return  this string, with white space removed from the front and end.
   */
  public abstract XMLString trim();

  /**
   * This object (which is already a string!) is itself returned.
   *
   * @return  the string itself.
   */
  public abstract String toString();

  /**
   * Tell if this object contains a java String object.
   *
   * @return true if this XMLString can return a string without creating one.
   */
  public abstract boolean hasString();

  /**
   * Convert a string to a double -- Allowed input is in fixed
   * notation ddd.fff.
   *
   * @return A double value representation of the string, or return Double.NaN
   * if the string can not be converted.
   */
  public double toDouble();


public class UnicodeString
    extends Record
    implements Comparable
{
    public final static short sid = 0xFFF;
    private final int RICH_TEXT_BIT = 8;
    private final int EXT_BIT = 4;

    public UnicodeString()
    {
    }

    public int hashCode()
    {
        int stringHash = 0;
        if (field_3_string != null)
            stringHash = field_3_string.hashCode();
        return field_1_charCount + stringHash;
    }

    /**
     * Our handling of equals is inconsistent with compareTo.  The trouble is because we don't truely understand
     * rich text fields yet it's difficult to make a sound comparison.
     *
     * @param o     The object to compare.
     * @return      true if the object is actually equal.
     */
    public boolean equals(Object o)
    {
        if ((o == null) || (o.getClass() != this.getClass()))
        {
            return false;
        }
        UnicodeString other = ( UnicodeString ) o;

        return ((field_1_charCount == other.field_1_charCount)
                && (field_2_optionflags == other.field_2_optionflags)
                && field_3_string.equals(other.field_3_string));
    }

    /**
     * construct a unicode string record and fill its fields, ID is ignored
     * @param id - ignored
     * @param size - size of the data
     * @param data - the bytes of the string/fields
     */

    public UnicodeString(short id, short size, byte [] data)
    {
        super(id, size, data);
    }

    /**
     * construct a unicode string from a string fragment + data
     */

    public UnicodeString(short id, short size, byte [] data, String prefix)
    {
        this(id, size, data);
        field_3_string = prefix + field_3_string;
        setCharCount();
    }

    /**
     * NO OP
     */

    protected void validateSid(short id)
    {

    }

    protected void fillFields(byte [] data, short size)
    {
        field_1_charCount   = LittleEndian.getShort(data, 0);
        field_2_optionflags = data[ 2 ];
        if ((field_2_optionflags & 1) == 0)
        {
            try {
                field_3_string = new String(data, 3, getCharCount(),
                                        StringUtil.getPreferredEncoding());
            } catch (UnsupportedEncodingException e) {
            	String errorMessage = e.getMessage();

            	if (errorMessage == null) {
            		errorMessage = e.toString();
           	}
                throw new RuntimeException(errorMessage);
            }
        }
        else
        {
            char[] array = new char[ getCharCount() ];

            for (int j = 0; j < array.length; j++)
            {
                array[ j ] = ( char ) LittleEndian.getShort(data,
                                                            3 + (j * 2));
            }
            field_3_string = new String(array);
        }
    }

    /**
     * get the number of characters in the string
     *
     *
     * @return number of characters
     *
     */

    public short getCharCount()
    {
        return field_1_charCount;
    }

    /**
     * set the number of characters in the string
     * @param cc - number of characters
     */

    public void setCharCount(short cc)
    {
        field_1_charCount = cc;
    }

    /**
     * sets the number of characters to whaterver number of characters is in the string
     * currently.  effectively setCharCount(getString.length()).
     * @see #setString(String)
     * @see #getString()
     */

    public void setCharCount()
    {
        field_1_charCount = ( short ) field_3_string.length();
    }

    /**
     * get the option flags which among other things return if this is a 16-bit or
     * 8 bit string
     *
     * @return optionflags bitmask
     *
     */

    public byte getOptionFlags()
    {
        return field_2_optionflags;
    }

    /**
     * set the option flags which among other things return if this is a 16-bit or
     * 8 bit string
     *
     * @param of  optionflags bitmask
     *
     */

    public void setOptionFlags(byte of)
    {
        field_2_optionflags = of;
    }

    /**
     * get the actual string this contains as a java String object
     *
     *
     * @return String
     *
     */

    public String getString()
    {
        return field_3_string;
    }

    /**
     * set the actual string this contains
     * @param string  the text
     */

    public void setString(String string)
    {
        field_3_string = string;
        if (getCharCount() < field_3_string.length())
        {
            setCharCount();
        }
    }

    /**
     * unlike the real records we return the same as "getString()" rather than debug info
     * @see #getDebugInfo()
     * @return String value of the record
     */

    public String toString()
    {
        return getString();
    }

    /**
     * return a character representation of the fields of this record
     *
     *
     * @return String of output for biffviewer etc.
     *
     */

    public String getDebugInfo()
    {
        StringBuffer buffer = new StringBuffer();

        buffer.append("[UNICODESTRING]\n");
        buffer.append("    .charcount       = ")
            .append(Integer.toHexString(getCharCount())).append("\n");
        buffer.append("    .optionflags     = ")
            .append(Integer.toHexString(getOptionFlags())).append("\n");
        buffer.append("    .string          = ").append(getString())
            .append("\n");
        buffer.append("[/UNICODESTRING]\n");
        return buffer.toString();
    }

    public int serialize(int offset, byte [] data)
    {
        int charsize = 1;

        if (getOptionFlags() == 1)
        {
            charsize = 2;
        }

        LittleEndian.putShort(data, 0 + offset, getCharCount());
        data[ 2 + offset ] = getOptionFlags();

        try {
            String unicodeString = new
String(getString().getBytes("Unicode"),"Unicode");
            if (getOptionFlags() == 0)
            {
                StringUtil.putCompressedUnicode(unicodeString, data, 0x3 +
offset);
            }
            else
            {
                StringUtil.putUncompressedUnicode(unicodeString, data,
                                                    0x3 + offset);
            }
        }
        catch (Exception e) {
            if (getOptionFlags() == 0)
            {
                StringUtil.putCompressedUnicode(getString(), data, 0x3 +
                                                offset);
            }
            else
            {
                StringUtil.putUncompressedUnicode(getString(), data,
                                                  0x3 + offset);
            }
        }
        return getRecordSize();
    }

    private boolean isUncompressedUnicode()
    {
        return (getOptionFlags() & 0x01) == 1;
    }

    public int getRecordSize()
    {
        int charsize = isUncompressedUnicode() ? 2 : 1;
        return 3 + (getString().length() * charsize);
    }

    public short getSid()
    {
        return this.sid;
    }

    /**
     * called by the constructor, should set class level fields.  Should throw
     * runtime exception for bad/icomplete data.
     *
     * @param data raw data
     * @param size size of data
     * @param offset of the records data (provided a big array of the file)
     */

    protected void fillFields(byte [] data, short size, int offset)
    {
    }

    public int compareTo(Object obj)
    {
        UnicodeString str = ( UnicodeString ) obj;

        return this.getString().compareTo(str.getString());
    }

    public boolean isRichText()
    {
        return (getOptionFlags() & RICH_TEXT_BIT) != 0;
    }

    int maxBrokenLength(final int proposedBrokenLength)
    {
        int rval = proposedBrokenLength;

        if (isUncompressedUnicode())
        {
            int proposedStringLength = proposedBrokenLength - 3;

            if ((proposedStringLength % 2) == 1)
            {
                proposedStringLength--;
            }
            rval = proposedStringLength + 3;
        }
        return rval;
    }

    public boolean isExtendedText()
    {
        return (getOptionFlags() & EXT_BIT) != 0;

FUNC_DECL IF PARAM BINARY_OP ASSIGN CALL CALL CALL

FUNC_DECL RETURN VAR_DECL PARAM CALL CALL CALL

FUNC_DECL PARAM PARAM PARAM PARAM CALL ASSIGN BINARY_OP


public class IBatisComponent extends DefaultComponent {
    public static final String DEFAULT_CONFIG_URI = "SqlMapConfig.xml";
    private static final transient Log LOG = LogFactory.getLog(IBatisComponent.class);

    private SqlMapClient sqlMapClient;
    private Resource sqlMapResource;

    public IBatisComponent() {
    }

    public IBatisComponent(SqlMapClient sqlMapClient) {
        this.sqlMapClient = sqlMapClient;
    }

    public SqlMapClient getSqlMapClient() throws IOException {
        if (sqlMapClient == null) {
            sqlMapClient = createSqlMapClient();
        }
        return sqlMapClient;
    }

    public void setSqlMapClient(SqlMapClient sqlMapClient) {
        this.sqlMapClient = sqlMapClient;
    }

    public Resource getSqlMapResource() {
        if (sqlMapResource == null) {
            sqlMapResource = new ClassPathResource(DEFAULT_CONFIG_URI);
            LOG.debug("Defaulting to use the iBatis configuration from: " + sqlMapResource);
        }
        return sqlMapResource;
    }

    public void setSqlMapResource(Resource sqlMapResource) {
        this.sqlMapResource = sqlMapResource;
    }

    protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception {
        return new IBatisEndpoint(uri, this, remaining);
    }

    protected SqlMapClient createSqlMapClient() throws IOException {
        InputStream in = getSqlMapResource().getInputStream();
        return SqlMapClientBuilder.buildSqlMapClient(in);

FUNC_DECL RETURN VAR_DECL CALL CALL CALL


public class CompositeProcessor extends ServiceSupport implements Processor {
    private final Collection<Processor> processors;

    public CompositeProcessor(Collection<Processor> processors) {
        this.processors = processors;
    }

    public void process(Exchange exchange) throws Exception {
        for (Processor processor : processors) {
            processor.process(exchange);
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder("[ ");
        boolean first = true;
        for (Processor processor : processors) {
            if (first) {
                first = false;
            } else {
                builder.append(", ");
            }
            builder.append(processor.toString());
        }
        builder.append(" ]");
        return builder.toString();
    }

    public Collection<Processor> getProcessors() {
        return processors;
    }

    protected void doStart() throws Exception {
        ServiceHelper.startServices(processors);
    }

    protected void doStop() throws Exception {
        ServiceHelper.stopServices(processors);


public class PaneInformation
{
	/** Constant for active pane being the lower right*/
    public static final byte PANE_LOWER_RIGHT = (byte)0;
    /** Constant for active pane being the upper right*/
    public static final byte PANE_UPPER_RIGHT = (byte)1;
    /** Constant for active pane being the lower left*/
    public static final byte PANE_LOWER_LEFT = (byte)2;
    /** Constant for active pane being the upper left*/
    public static final byte PANE_UPPER_LEFT = (byte)3;

	private short x;
	private short y;
	private short topRow;
	private short leftColumn;
	private byte activePane;
	private boolean frozen = false;

	public PaneInformation(short x, short y, short top, short left, byte active, boolean frozen) {
		this.x = x;
		this.y = y;
		this.topRow = top;
		this.leftColumn = left;
		this.activePane = active;
		this.frozen = frozen;
	}

	/**
	 * Returns the vertical position of the split.
	 * @return 0 if there is no vertical spilt,
	 *         or for a freeze pane the number of columns in the TOP pane,
	 *         or for a split plane the position of the split in 1/20th of a point.
	 */
	public short getVerticalSplitPosition() {
	  return x;
	}

	/**
	 * Returns the horizontal position of the split.
	 * @return 0 if there is no horizontal spilt,
	 *         or for a freeze pane the number of rows in the LEFT pane,
	 *         or for a split plane the position of the split in 1/20th of a point.
	 */
	public short getHorizontalSplitPosition() {
	  return y;
	}

	/**
	 * For a horizontal split returns the top row in the BOTTOM pane.
	 * @return 0 if there is no horizontal split, or the top row of the bottom pane.
	 */
	public short getHorizontalSplitTopRow() {
	  return topRow;
	}

	/**
	 * For a vertical split returns the left column in the RIGHT pane.
	 * @return 0 if there is no vertical split, or the left column in the RIGHT pane.
	 */
	public short getVerticalSplitLeftColumn() {
	  return leftColumn;
	}

	/**
	 * Returns the active pane
	 * @see PANE_LOWER_RIGHT
	 * @see PANE_UPPER_RIGHT
	 * @see PANE_LOWER_LEFT
	 * @see PANE_UPPER_LEFT
	 * @return the active pane.
	 */
	public byte getActivePane() {
	  return activePane;
	}

	/** Returns true if this is a Freeze pane, false if it is a split pane.
	 */
	public boolean isFreezePane() {
		return frozen;

FUNC_DECL PARAM PARAM PARAM PARAM PARAM PARAM ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN


public class CBZip2InputStream extends InputStream implements BZip2Constants {
    private static void cadvise() {
        System.out.println("CRC Error");
    }

    private static void badBGLengths() {
        cadvise();
    }

    private static void bitStreamEOF() {
        cadvise();
    }

    private static void compressedStreamEOF() {
        cadvise();
    }

    private void makeMaps() {
        int i;
        nInUse = 0;
        for (i = 0; i < 256; i++) {
            if (inUse[i]) {
                seqToUnseq[nInUse] = (char) i;
                unseqToSeq[i] = (char) nInUse;
                nInUse++;
            }
        }
    }

    /*
      index of the last char in the block, so
      the block size == last + 1.
    */
    private int  last;

    /*
      index in zptr[] of original string after sorting.
    */
    private int  origPtr;

    /*
      always: in the range 0 .. 9.
      The current block size is 100000 * this number.
    */
    private int blockSize100k;

    private boolean blockRandomised;

    private int bytesIn;
    private int bytesOut;
    private int bsBuff;
    private int bsLive;
    private CRC mCrc = new CRC();

    private boolean[] inUse = new boolean[256];
    private int nInUse;

    private char[] seqToUnseq = new char[256];
    private char[] unseqToSeq = new char[256];

    private char[] selector = new char[MAX_SELECTORS];
    private char[] selectorMtf = new char[MAX_SELECTORS];

    private int[] tt;
    private char[] ll8;

    /*
      freq table collected to save a pass over the data
      during decompression.
    */
    private int unzftab[] = new int[256];

    private int limit[][] = new int[N_GROUPS][MAX_ALPHA_SIZE];
    private int base[][] = new int[N_GROUPS][MAX_ALPHA_SIZE];
    private int perm[][] = new int[N_GROUPS][MAX_ALPHA_SIZE];
    private int minLens[] = new int[N_GROUPS];

    private InputStream bsStream;

    private boolean streamEnd = false;

    private int currentChar = -1;

    private static final int START_BLOCK_STATE = 1;
    private static final int RAND_PART_A_STATE = 2;
    private static final int RAND_PART_B_STATE = 3;
    private static final int RAND_PART_C_STATE = 4;
    private static final int NO_RAND_PART_A_STATE = 5;
    private static final int NO_RAND_PART_B_STATE = 6;
    private static final int NO_RAND_PART_C_STATE = 7;

    private int currentState = START_BLOCK_STATE;

    private int storedBlockCRC, storedCombinedCRC;
    private int computedBlockCRC, computedCombinedCRC;

    int i2, count, chPrev, ch2;
    int i, tPos;
    int rNToGo = 0;
    int rTPos  = 0;
    int j2;
    char z;

    public CBZip2InputStream(InputStream zStream) {
        ll8 = null;
        tt = null;
        bsSetStream(zStream);
        initialize();
        initBlock();
        setupBlock();
    }

    public int read() {
        if (streamEnd) {
            return -1;
        } else {
            int retChar = currentChar;
            switch(currentState) {
            case START_BLOCK_STATE:
                break;
            case RAND_PART_A_STATE:
                break;
            case RAND_PART_B_STATE:
                setupRandPartB();
                break;
            case RAND_PART_C_STATE:
                setupRandPartC();
                break;
            case NO_RAND_PART_A_STATE:
                break;
            case NO_RAND_PART_B_STATE:
                setupNoRandPartB();
                break;
            case NO_RAND_PART_C_STATE:
                setupNoRandPartC();
                break;
            default:
                break;
            }
            return retChar;
        }
    }

    private void initialize() {
        char magic3, magic4;
        magic3 = bsGetUChar();
        magic4 = bsGetUChar();
        if (magic3 != 'h' || magic4 < '1' || magic4 > '9') {
            bsFinishedWithStream();
            streamEnd = true;
            return;
        }

        setDecompressStructureSizes(magic4 - '0');
        computedCombinedCRC = 0;
    }

    private void initBlock() {
        char magic1, magic2, magic3, magic4;
        char magic5, magic6;
        magic1 = bsGetUChar();
        magic2 = bsGetUChar();
        magic3 = bsGetUChar();
        magic4 = bsGetUChar();
        magic5 = bsGetUChar();
        magic6 = bsGetUChar();
        if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45
            && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) {
            complete();
            return;
        }

        if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59
            || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) {
            badBlockHeader();
            streamEnd = true;
            return;
        }

        storedBlockCRC = bsGetInt32();

        if (bsR(1) == 1) {
            blockRandomised = true;
        } else {
            blockRandomised = false;
        }

        getAndMoveToFrontDecode();

        mCrc.initialiseCRC();
        currentState = START_BLOCK_STATE;
    }

    private void endBlock() {
        computedBlockCRC = mCrc.getFinalCRC();
        /* A bad CRC is considered a fatal error. */
        if (storedBlockCRC != computedBlockCRC) {
            crcError();
        }

        computedCombinedCRC = (computedCombinedCRC << 1)
            | (computedCombinedCRC >>> 31);
        computedCombinedCRC ^= computedBlockCRC;
    }

    private void complete() {
        storedCombinedCRC = bsGetInt32();
        if (storedCombinedCRC != computedCombinedCRC) {
            crcError();
        }

        bsFinishedWithStream();
        streamEnd = true;
    }

    private static void blockOverrun() {
        cadvise();
    }

    private static void badBlockHeader() {
        cadvise();
    }

    private static void crcError() {
        cadvise();
    }

    private void bsFinishedWithStream() {
        try {
            if (this.bsStream != null) {
                if (this.bsStream != System.in) {
                    this.bsStream.close();
                    this.bsStream= null;
                }
            }
        } catch (IOException ioe) {
        }
    }

    private void bsSetStream(InputStream f) {
        bsStream = f;
        bsLive = 0;
        bsBuff = 0;
        bytesOut = 0;
        bytesIn = 0;
    }

    private int bsR(int n) {
        int v;
        {
            while (bsLive < n) {
                int zzi;
                char thech = 0;
                try {
                    thech = (char) bsStream.read();
                } catch (IOException e) {
                    compressedStreamEOF();
                }
                if (thech == -1) {
                    compressedStreamEOF();
                }
                zzi = thech;
                bsBuff = (bsBuff << 8) | (zzi & 0xff);
                bsLive += 8;
            }
        }

        v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1);
        bsLive -= n;
        return v;
    }

    private char bsGetUChar() {
        return (char) bsR(8);
    }

    private int bsGetint() {
        int u = 0;
        u = (u << 8) | bsR(8);
        u = (u << 8) | bsR(8);
        u = (u << 8) | bsR(8);
        u = (u << 8) | bsR(8);
        return u;
    }

    private int bsGetIntVS(int numBits) {
        return (int) bsR(numBits);
    }

    private int bsGetInt32() {
        return (int) bsGetint();
    }

    private void hbCreateDecodeTables(int[] limit, int[] base,
                                      int[] perm, char[] length,
                                      int minLen, int maxLen, int alphaSize) {
        int pp, i, j, vec;

        pp = 0;
        for (i = minLen; i <= maxLen; i++) {
            for (j = 0; j < alphaSize; j++) {
                if (length[j] == i) {
                    perm[pp] = j;
                    pp++;
                }
            }
        };

        for (i = 0; i < MAX_CODE_LEN; i++) {
            base[i] = 0;
        }
        for (i = 0; i < alphaSize; i++) {
            base[length[i] + 1]++;
        }

        for (i = 1; i < MAX_CODE_LEN; i++) {
            base[i] += base[i - 1];
        }

        for (i = 0; i < MAX_CODE_LEN; i++) {
            limit[i] = 0;
        }
        vec = 0;

        for (i = minLen; i <= maxLen; i++) {
            vec += (base[i + 1] - base[i]);
            limit[i] = vec - 1;
            vec <<= 1;
        }
        for (i = minLen + 1; i <= maxLen; i++) {
            base[i] = ((limit[i - 1] + 1) << 1) - base[i];
        }
    }

    private void recvDecodingTables() {
        char len[][] = new char[N_GROUPS][MAX_ALPHA_SIZE];
        int i, j, t, nGroups, nSelectors, alphaSize;
        int minLen, maxLen;
        boolean[] inUse16 = new boolean[16];

        /* Receive the mapping table */
        for (i = 0; i < 16; i++) {
            if (bsR(1) == 1) {
                inUse16[i] = true;
            } else {
                inUse16[i] = false;
            }
        }

        for (i = 0; i < 256; i++) {
            inUse[i] = false;
        }

        for (i = 0; i < 16; i++) {
            if (inUse16[i]) {
                for (j = 0; j < 16; j++) {
                    if (bsR(1) == 1) {
                        inUse[i * 16 + j] = true;
                    }
                }
            }
        }

        makeMaps();
        alphaSize = nInUse + 2;

        /* Now the selectors */
        nGroups = bsR(3);
        nSelectors = bsR(15);
        for (i = 0; i < nSelectors; i++) {
            j = 0;
            while (bsR(1) == 1) {
                j++;
            }
            selectorMtf[i] = (char) j;
        }

        /* Undo the MTF values for the selectors. */
        {
            char[] pos = new char[N_GROUPS];
            char tmp, v;
            for (v = 0; v < nGroups; v++) {
                pos[v] = v;
            }

            for (i = 0; i < nSelectors; i++) {
                v = selectorMtf[i];
                tmp = pos[v];
                while (v > 0) {
                    pos[v] = pos[v - 1];
                    v--;
                }
                pos[0] = tmp;
                selector[i] = tmp;
            }
        }

        /* Now the coding tables */
        for (t = 0; t < nGroups; t++) {
            int curr = bsR(5);
            for (i = 0; i < alphaSize; i++) {
                while (bsR(1) == 1) {
                    if (bsR(1) == 0) {
                        curr++;
                    } else {
                        curr--;
                    }
                }
                len[t][i] = (char) curr;
            }
        }

        /* Create the Huffman decoding tables */
        for (t = 0; t < nGroups; t++) {
            minLen = 32;
            maxLen = 0;
            for (i = 0; i < alphaSize; i++) {
                if (len[t][i] > maxLen) {
                    maxLen = len[t][i];
                }
                if (len[t][i] < minLen) {
                    minLen = len[t][i];
                }
            }
            hbCreateDecodeTables(limit[t], base[t], perm[t], len[t], minLen,
                                 maxLen, alphaSize);
            minLens[t] = minLen;
        }
    }

    private void getAndMoveToFrontDecode() {
        char[] yy = new char[256];
        int i, j, nextSym, limitLast;
        int EOB, groupNo, groupPos;

        limitLast = baseBlockSize * blockSize100k;
        origPtr = bsGetIntVS(24);

        recvDecodingTables();
        EOB = nInUse + 1;
        groupNo = -1;
        groupPos = 0;

        /*
          Setting up the unzftab entries here is not strictly
          necessary, but it does save having to do it later
          in a separate pass, and so saves a block's worth of
          cache misses.
        */
        for (i = 0; i <= 255; i++) {
            unzftab[i] = 0;
        }

        for (i = 0; i <= 255; i++) {
            yy[i] = (char) i;
        }

        last = -1;

        {
            int zt, zn, zvec, zj;
            if (groupPos == 0) {
                groupNo++;
                groupPos = G_SIZE;
            }
            groupPos--;
            zt = selector[groupNo];
            zn = minLens[zt];
            zvec = bsR(zn);
            while (zvec > limit[zt][zn]) {
                zn++;
                {
                    {
                        while (bsLive < 1) {
                            int zzi;
                            char thech = 0;
                            try {
                                thech = (char) bsStream.read();
                            } catch (IOException e) {
                                compressedStreamEOF();
                            }
                            if (thech == -1) {
                                compressedStreamEOF();
                            }
                            zzi = thech;
                            bsBuff = (bsBuff << 8) | (zzi & 0xff);
                            bsLive += 8;
                        }
                    }
                    zj = (bsBuff >> (bsLive - 1)) & 1;
                    bsLive--;
                }
                zvec = (zvec << 1) | zj;
            }
            nextSym = perm[zt][zvec - base[zt][zn]];
        }

        while (true) {

            if (nextSym == EOB) {
                break;
            }

            if (nextSym == RUNA || nextSym == RUNB) {
                char ch;
                int s = -1;
                int N = 1;
                do {
                    if (nextSym == RUNA) {
                        s = s + (0 + 1) * N;
                    } else if (nextSym == RUNB) {
                        s = s + (1 + 1) * N;
                           }
                    N = N * 2;
                    {
                        int zt, zn, zvec, zj;
                        if (groupPos == 0) {
                            groupNo++;
                            groupPos = G_SIZE;
                        }
                        groupPos--;
                        zt = selector[groupNo];
                        zn = minLens[zt];
                        zvec = bsR(zn);
                        while (zvec > limit[zt][zn]) {
                            zn++;
                            {
                                {
                                    while (bsLive < 1) {
                                        int zzi;
                                        char thech = 0;
                                        try {
                                            thech = (char) bsStream.read();
                                        } catch (IOException e) {
                                            compressedStreamEOF();
                                        }
                                        if (thech == -1) {
                                            compressedStreamEOF();
                                        }
                                        zzi = thech;
                                        bsBuff = (bsBuff << 8) | (zzi & 0xff);
                                        bsLive += 8;
                                    }
                                }
                                zj = (bsBuff >> (bsLive - 1)) & 1;
                                bsLive--;
                            }
                            zvec = (zvec << 1) | zj;
                        };
                        nextSym = perm[zt][zvec - base[zt][zn]];
                    }
                } while (nextSym == RUNA || nextSym == RUNB);

                s++;
                ch = seqToUnseq[yy[0]];
                unzftab[ch] += s;

                while (s > 0) {
                    last++;
                    ll8[last] = ch;
                    s--;
                };

                if (last >= limitLast) {
                    blockOverrun();
                }
                continue;
            } else {
                char tmp;
                last++;
                if (last >= limitLast) {
                    blockOverrun();
                }

                tmp = yy[nextSym - 1];
                unzftab[seqToUnseq[tmp]]++;
                ll8[last] = seqToUnseq[tmp];

                /*
                  This loop is hammered during decompression,
                  hence the unrolling.

                  for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1];
                */

                j = nextSym - 1;
                for (; j > 3; j -= 4) {
                    yy[j]     = yy[j - 1];
                    yy[j - 1] = yy[j - 2];
                    yy[j - 2] = yy[j - 3];
                    yy[j - 3] = yy[j - 4];
                }
                for (; j > 0; j--) {
                    yy[j] = yy[j - 1];
                }

                yy[0] = tmp;
                {
                    int zt, zn, zvec, zj;
                    if (groupPos == 0) {
                        groupNo++;
                        groupPos = G_SIZE;
                    }
                    groupPos--;
                    zt = selector[groupNo];
                    zn = minLens[zt];
                    zvec = bsR(zn);
                    while (zvec > limit[zt][zn]) {
                        zn++;
                        {
                            {
                                while (bsLive < 1) {
                                    int zzi;
                                    char thech = 0;
                                    try {
                                        thech = (char) bsStream.read();
                                    } catch (IOException e) {
                                        compressedStreamEOF();
                                    }
                                    zzi = thech;
                                    bsBuff = (bsBuff << 8) | (zzi & 0xff);
                                    bsLive += 8;
                                }
                            }
                            zj = (bsBuff >> (bsLive - 1)) & 1;
                            bsLive--;
                        }
                        zvec = (zvec << 1) | zj;
                    };
                    nextSym = perm[zt][zvec - base[zt][zn]];
                }
                continue;
            }
        }
    }

    private void setupBlock() {
        int[] cftab = new int[257];
        char ch;

        cftab[0] = 0;
        for (i = 1; i <= 256; i++) {
            cftab[i] = unzftab[i - 1];
        }
        for (i = 1; i <= 256; i++) {
            cftab[i] += cftab[i - 1];
        }

        for (i = 0; i <= last; i++) {
            ch = (char) ll8[i];
            tt[cftab[ch]] = i;
            cftab[ch]++;
        }
        cftab = null;

        tPos = tt[origPtr];

        count = 0;
        i2 = 0;
        ch2 = 256;   /* not a char and not EOF */

        if (blockRandomised) {
            rNToGo = 0;
            rTPos = 0;
            setupRandPartA();
        } else {
            setupNoRandPartA();
        }
    }

    private void setupRandPartA() {
        if (i2 <= last) {
            chPrev = ch2;
            ch2 = ll8[tPos];
            tPos = tt[tPos];
            if (rNToGo == 0) {
                rNToGo = rNums[rTPos];
                rTPos++;
                if (rTPos == 512) {
                    rTPos = 0;
                }
            }
            rNToGo--;
            ch2 ^= (int) ((rNToGo == 1) ? 1 : 0);
            i2++;

            currentChar = ch2;
            currentState = RAND_PART_B_STATE;
            mCrc.updateCRC(ch2);
        } else {
            endBlock();
            initBlock();
            setupBlock();
        }
    }

    private void setupNoRandPartA() {
        if (i2 <= last) {
            chPrev = ch2;
            ch2 = ll8[tPos];
            tPos = tt[tPos];
            i2++;

            currentChar = ch2;
            currentState = NO_RAND_PART_B_STATE;
            mCrc.updateCRC(ch2);
        } else {
            endBlock();
            initBlock();
            setupBlock();
        }
    }

    private void setupRandPartB() {
        if (ch2 != chPrev) {
            currentState = RAND_PART_A_STATE;
            count = 1;
            setupRandPartA();
        } else {
            count++;
            if (count >= 4) {
                z = ll8[tPos];
                tPos = tt[tPos];
                if (rNToGo == 0) {
                    rNToGo = rNums[rTPos];
                    rTPos++;
                    if (rTPos == 512) {
                        rTPos = 0;
                    }
                }
                rNToGo--;
                z ^= ((rNToGo == 1) ? 1 : 0);
                j2 = 0;
                currentState = RAND_PART_C_STATE;
                setupRandPartC();
            } else {
                currentState = RAND_PART_A_STATE;
                setupRandPartA();
            }
        }
    }

    private void setupRandPartC() {
        if (j2 < (int) z) {
            currentChar = ch2;
            mCrc.updateCRC(ch2);
            j2++;
        } else {
            currentState = RAND_PART_A_STATE;
            i2++;
            count = 0;
            setupRandPartA();
        }
    }

    private void setupNoRandPartB() {
        if (ch2 != chPrev) {
            currentState = NO_RAND_PART_A_STATE;
            count = 1;
            setupNoRandPartA();
        } else {
            count++;
            if (count >= 4) {
                z = ll8[tPos];
                tPos = tt[tPos];
                currentState = NO_RAND_PART_C_STATE;
                j2 = 0;
                setupNoRandPartC();
            } else {
                currentState = NO_RAND_PART_A_STATE;
                setupNoRandPartA();
            }
        }
    }

    private void setupNoRandPartC() {
        if (j2 < (int) z) {
            currentChar = ch2;
            mCrc.updateCRC(ch2);
            j2++;
        } else {
            currentState = NO_RAND_PART_A_STATE;
            i2++;
            count = 0;
            setupNoRandPartA();
        }
    }

    private void setDecompressStructureSizes(int newSize100k) {
        if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k
               && blockSize100k <= 9)) {
        }

        blockSize100k = newSize100k;

        if (newSize100k == 0) {
            return;
        }

        int n = baseBlockSize * newSize100k;
        ll8 = new char[n];
        tt = new int[n];

FUNC_DECL IF ASSIGN CALL BINARY_OP ASSIGN LITERAL_ANCHOR CALL CALL

FUNC_DECL IF BINARY_OP CALL CALL CALL CALL ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN

FUNC_DECL IF BINARY_OP CALL ASSIGN ASSIGN CALL ASSIGN LITERAL_ANCHOR

FUNC_DECL IF BINARY_OP IF BINARY_OP CALL ASSIGN ASSIGN LITERAL_ANCHOR LITERAL_ANCHOR CALL ASSIGN CALL ASSIGN ASSIGN ASSIGN ASSIGN LITERAL_ANCHOR

FUNC_DECL PARAM CALL CALL CALL CALL ASSIGN ASSIGN LITERAL_ANCHOR LITERAL_ANCHOR


public class Content extends ResourceComparator {

    private boolean binary = true;

    /**
     * Set binary mode for this Content ResourceComparator. If this
     * attribute is set to false, Resource content will be compared
     * ignoring platform line-ending conventions.
     * Default is true.
     * @param b whether to compare content in binary mode.
     */
    public void setBinary(boolean b) {
        binary = b;
    }

    /**
     * Learn whether this Content ResourceComparator is operating in binary mode.
     * @return boolean binary flag.
     */
    public boolean isBinary() {
        return binary;
    }

    /**
     * Compare two Resources by content.
     * @param foo the first Resource.
     * @param bar the second Resource.
     * @return a negative integer, zero, or a positive integer as the first
     *         argument is less than, equal to, or greater than the second.
     * @throws BuildException if I/O errors occur.
     * @see org.apache.tools.ant.util.ResourceUtils#compareContent(Resource, Resource, boolean).
     */
    protected int resourceCompare(Resource foo, Resource bar) {
        try {
            return ResourceUtils.compareContent(foo, bar, !binary);
        } catch (IOException e) {
            throw new BuildException(e);

FUNC_DECL TRY PARAM PARAM CATCH RETURN THROW_RAISE CALL CALL


org.apache.tools.ant.taskdefs.Expand

public class Expand extends Task {
    private boolean overwrite = true;
    private Vector patternsets = new Vector();
    private Vector filesets = new Vector();

    /**
     * Do the work.
     *
     * @exception BuildException Thrown in unrecoverable error.
     */
    public void execute() throws BuildException {
        if ("expand".equals(taskType)) {
            log("!! expand is deprecated. Use unzip instead. !!");
        }

        if (source == null && filesets.size() == 0) {
            throw new BuildException("src attribute and/or filesets must be "
                                     + "specified");
        }

        if (dest == null) {
            throw new BuildException(
                "Dest attribute must be specified");
        }

        if (dest.exists() && !dest.isDirectory()) {
            throw new BuildException("Dest must be a directory.", location);
        }

        FileUtils fileUtils = FileUtils.newFileUtils();

        if (source != null) {
            if (source.isDirectory()) {
                throw new BuildException("Src must not be a directory." +
                    " Use nested filesets instead.", location);
            } else {
                expandFile(fileUtils, source, dest);
            }
        }
        if (filesets.size() > 0) {
            for (int j = 0; j < filesets.size(); j++) {
                FileSet fs = (FileSet) filesets.elementAt(j);
                DirectoryScanner ds = fs.getDirectoryScanner(getProject());
                File fromDir = fs.getDir(getProject());

                String[] files = ds.getIncludedFiles();
                for (int i = 0; i < files.length; ++i) {
                    File file = new File(fromDir, files[i]);
                    expandFile(fileUtils, file, dest);
                }
            }
        }
    }

    /*
     * This method is to be overridden by extending unarchival tasks.
     */
    protected void expandFile(FileUtils fileUtils, File srcF, File dir) {
        log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO);
        ZipInputStream zis = null;
        try {
            zis = new ZipInputStream(new FileInputStream(srcF));
            ZipEntry ze = null;

            while ((ze = zis.getNextEntry()) != null) {
                extractFile(fileUtils, srcF, dir, zis,
                            ze.getName(), new Date(ze.getTime()),
                            ze.isDirectory());
            }

            log("expand complete", Project.MSG_VERBOSE);
        } catch (IOException ioe) {
            throw new BuildException("Error while expanding " + srcF.getPath(),
                                     ioe);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (IOException e) {}
            }
        }
    }

    protected void extractFile(FileUtils fileUtils, File srcF, File dir,
                               InputStream compressedInputStream,
                               String entryName,
                               Date entryDate, boolean isDirectory)
                               throws IOException {

        if (patternsets != null && patternsets.size() > 0) {
            String name = entryName;
            boolean included = false;
            for (int v = 0; v < patternsets.size(); v++) {
                PatternSet p = (PatternSet) patternsets.elementAt(v);
                String[] incls = p.getIncludePatterns(getProject());
                if (incls == null || incls.length == 0) {
                    incls = new String[] {"**"};
                }

                for (int w = 0; w < incls.length; w++) {
                    included = DirectoryScanner.match(incls[w], name);
                    if (included) {
                        break;
                    }
                }

                if (!included) {
                    break;
                }

                String[] excls = p.getExcludePatterns(getProject());
                if (excls != null) {
                    for (int w = 0; w < excls.length; w++) {
                        included = !(DirectoryScanner.match(excls[w], name));
                        if (!included) {
                            break;
                        }
                    }
                }
            }
            if (!included) {
                return;
            }
        }

        File f = fileUtils.resolveFile(dir, entryName);
        try {
            if (!overwrite && f.exists()
                && f.lastModified() >= entryDate.getTime()) {
                log("Skipping " + f + " as it is up-to-date",
                    Project.MSG_DEBUG);
                return;
            }

            log("expanding " + entryName + " to " + f,
                Project.MSG_VERBOSE);
            File dirF = fileUtils.getParentFile(f);
            if ( dirF != null ) {
                dirF.mkdirs();
            }

            if (isDirectory) {
                f.mkdirs();
            } else {
                byte[] buffer = new byte[1024];
                int length = 0;
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(f);

                    while ((length =
                            compressedInputStream.read(buffer)) >= 0) {
                        fos.write(buffer, 0, length);
                    }

                    fos.close();
                    fos = null;
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {}
                    }
                }
            }

            fileUtils.setFileLastModified(f, entryDate.getTime());
        } catch (FileNotFoundException ex) {
            log("Unable to expand to file " + f.getPath(), Project.MSG_WARN);
        }

    }

    /**
     * Set the destination directory. File will be unzipped into the
     * destination directory.
     *
     * @param d Path to the directory.
     */
    public void setDest(File d) {
        this.dest = d;
    }

    /**
     * Set the path to zip-file.
     *
     * @param s Path to zip-file.
     */
    public void setSrc(File s) {
        this.source = s;
    }

    /**
     * Should we overwrite files in dest, even if they are newer than
     * the corresponding entries in the archive?
     */
    public void setOverwrite(boolean b) {
        overwrite = b;
    }

    /**
     * Add a patternset
     */
    public void addPatternset(PatternSet set) {
        patternsets.addElement(set);
    }

    /**
     * Add a fileset
     */
    public void addFileset(FileSet set) {
        filesets.addElement(set);


org.apache.tools.tar.TarEntry

public class TarEntry implements TarConstants {

    private StringBuffer name;      /** The entry's name. */
    private int          mode;      /** The entry's permission mode. */
    private int          userId;    /** The entry's user id. */
    private int          groupId;   /** The entry's group id. */
    private long         size;      /** The entry's size. */
    private long         modTime;   /** The entry's modification time. */
    private int          checkSum;  /** The entry's checksum. */
    private byte         linkFlag;  /** The entry's link flag. */
    private StringBuffer linkName;  /** The entry's link name. */
    private StringBuffer magic;     /** The entry's magic tag. */
    private StringBuffer userName;  /** The entry's user name. */
    private StringBuffer groupName; /** The entry's group name. */
    private int          devMajor;  /** The entry's major device number. */
    private int          devMinor;  /** The entry's minor device number. */
    private File         file;      /** The entry's file reference */

    /**
     * Construct an empty entry and prepares the header values.
     */
    private TarEntry () {
        this.magic = new StringBuffer(TMAGIC);
        this.name = new StringBuffer();
        this.linkName = new StringBuffer();

        String user = System.getProperty("user.name", "");

        if (user.length() > 31) {
            user = user.substring(0, 31);
        }

        this.userId = 0;
        this.groupId = 0;
        this.userName = new StringBuffer(user);
        this.groupName = new StringBuffer("");
        this.file = null;
    }

    /**
     * Construct an entry with only a name. This allows the programmer
     * to construct the entry's header "by hand". File is set to null.
     */
    public TarEntry(String name) {
        this();

        boolean isDir = name.endsWith("/");

        this.checkSum = 0;
        this.devMajor = 0;
        this.devMinor = 0;
        this.name = new StringBuffer(name);
        this.mode = isDir ? 040755 : 0100644;
        this.linkFlag = isDir ? LF_DIR : LF_NORMAL;
        this.userId = 0;
        this.groupId = 0;
        this.size = 0;
        this.checkSum = 0;
        this.modTime = (new Date()).getTime() / 1000;
        this.linkName = new StringBuffer("");
        this.userName = new StringBuffer("");
        this.groupName = new StringBuffer("");
        this.devMajor = 0;
        this.devMinor = 0;

    }

    /**
     * Construct an entry with a name an a link flag.
     */
    public TarEntry(String name, byte linkFlag) {
        this(name);
        this.linkFlag = linkFlag;
    }

    /**
     * Construct an entry for a file. File is set to file, and the
     * header is constructed from information from the file.
     *
     * @param file The file that the entry represents.
     */
    public TarEntry(File file) {
        this();

        this.file = file;

        String name = file.getPath();
        String osname = System.getProperty("os.name");

        if (osname != null) {

            String Win32Prefix = "Windows";
            String prefix = osname.substring(0, Win32Prefix.length());

            if (prefix.equalsIgnoreCase(Win32Prefix)) {
                if (name.length() > 2) {
                    char ch1 = name.charAt(0);
                    char ch2 = name.charAt(1);

                    if (ch2 == ':'
                            && ((ch1 >= 'a' && ch1 <= 'z')
                                || (ch1 >= 'A' && ch1 <= 'Z'))) {
                        name = name.substring(2);
                    }
                }
            }
        }

        name = name.replace(File.separatorChar, '/');

        while (name.startsWith("/")) {
            name = name.substring(1);
        }

        this.linkName = new StringBuffer("");
        this.name = new StringBuffer(name);

        if (file.isDirectory()) {
            this.mode = 040755;
            this.linkFlag = LF_DIR;

            if (this.name.charAt(this.name.length() - 1) != '/') {
                this.name.append("/");
            }
        } else {
            this.mode = 0100644;
            this.linkFlag = LF_NORMAL;
        }

        this.size = file.length();
        this.modTime = file.lastModified() / 1000;
        this.checkSum = 0;
        this.devMajor = 0;
        this.devMinor = 0;
    }

    /**
     * Construct an entry from an archive's header bytes. File is set
     * to null.
     *
     * @param headerBuf The header bytes from a tar archive entry.
     */
    public TarEntry(byte[] headerBuf) {
        this();
        this.parseTarHeader(headerBuf);
    }

    /**
     * Determine if the two entries are equal. Equality is determined
     * by the header names being equal.
     *
     * @return it Entry to be checked for equality.
     * @return True if the entries are equal.
     */
    public boolean equals(TarEntry it) {
        return this.getName().equals(it.getName());
    }

    /**
     * Determine if the given entry is a descendant of this entry.
     * Descendancy is determined by the name of the descendant
     * starting with this entry's name.
     *
     * @param desc Entry to be checked as a descendent of this.
     * @return True if entry is a descendant of this.
     */
    public boolean isDescendent(TarEntry desc) {
        return desc.getName().startsWith(this.getName());
    }

    /**
     * Get this entry's name.
     *
     * @return This entry's name.
     */
    public String getName() {
        return this.name.toString();
    }

    /**
     * Set this entry's name.
     *
     * @param name This entry's new name.
     */
    public void setName(String name) {
        this.name = new StringBuffer(name);
    }

    /**
     * Set the mode for this entry
     */
    public void setMode(int mode) {
        this.mode = mode;
    }

    /**
     * Get this entry's user id.
     *
     * @return This entry's user id.
     */
    public int getUserId() {
        return this.userId;
    }

    /**
     * Set this entry's user id.
     *
     * @param userId This entry's new user id.
     */
    public void setUserId(int userId) {
        this.userId = userId;
    }

    /**
     * Get this entry's group id.
     *
     * @return This entry's group id.
     */
    public int getGroupId() {
        return this.groupId;
    }

    /**
     * Set this entry's group id.
     *
     * @param groupId This entry's new group id.
     */
    public void setGroupId(int groupId) {
        this.groupId = groupId;
    }

    /**
     * Get this entry's user name.
     *
     * @return This entry's user name.
     */
    public String getUserName() {
        return this.userName.toString();
    }

    /**
     * Set this entry's user name.
     *
     * @param userName This entry's new user name.
     */
    public void setUserName(String userName) {
        this.userName = new StringBuffer(userName);
    }

    /**
     * Get this entry's group name.
     *
     * @return This entry's group name.
     */
    public String getGroupName() {
        return this.groupName.toString();
    }

    /**
     * Set this entry's group name.
     *
     * @param groupName This entry's new group name.
     */
    public void setGroupName(String groupName) {
        this.groupName = new StringBuffer(groupName);
    }

    /**
     * Convenience method to set this entry's group and user ids.
     *
     * @param userId This entry's new user id.
     * @param groupId This entry's new group id.
     */
    public void setIds(int userId, int groupId) {
        this.setUserId(userId);
        this.setGroupId(groupId);
    }

    /**
     * Convenience method to set this entry's group and user names.
     *
     * @param userName This entry's new user name.
     * @param groupName This entry's new group name.
     */
    public void setNames(String userName, String groupName) {
        this.setUserName(userName);
        this.setGroupName(groupName);
    }

    /**
     * Set this entry's modification time. The parameter passed
     * to this method is in "Java time".
     *
     * @param time This entry's new modification time.
     */
    public void setModTime(long time) {
        this.modTime = time / 1000;
    }

    /**
     * Set this entry's modification time.
     *
     * @param time This entry's new modification time.
     */
    public void setModTime(Date time) {
        this.modTime = time.getTime() / 1000;
    }

    /**
     * Set this entry's modification time.
     *
     * @param time This entry's new modification time.
     */
    public Date getModTime() {
        return new Date(this.modTime * 1000);
    }

    /**
     * Get this entry's file.
     *
     * @return This entry's file.
     */
    public File getFile() {
        return this.file;
    }

    /**
     * Get this entry's file size.
     *
     * @return This entry's file size.
     */
    public long getSize() {
        return this.size;
    }

    /**
     * Set this entry's file size.
     *
     * @param size This entry's new file size.
     */
    public void setSize(long size) {
        this.size = size;
    }

    /**
     * Indicate if this entry is a GNU long name block
     *
     * @return true if this is a long name extension provided by GNU tar
     */
    public boolean isGNULongNameEntry() {
        return linkFlag == LF_GNUTYPE_LONGNAME &&
               name.toString().equals(GNU_LONGLINK);
    }

    /**
     * Return whether or not this entry represents a directory.
     *
     * @return True if this entry is a directory.
     */
    public boolean isDirectory() {
        if (this.file != null) {
            return this.file.isDirectory();
        }

        if (this.linkFlag == LF_DIR) {
            return true;
        }

        if (this.getName().endsWith("/")) {
            return true;
        }

        return false;
    }

    /**
     * If this entry represents a file, and the file is a directory, return
     * an array of TarEntries for this entry's children.
     *
     * @return An array of TarEntry's for this entry's children.
     */
    public TarEntry[] getDirectoryEntries() {
        if (this.file == null ||!this.file.isDirectory()) {
            return new TarEntry[0];
        }

        String[]   list = this.file.list();
        TarEntry[] result = new TarEntry[list.length];

        for (int i = 0; i < list.length; ++i) {
            result[i] = new TarEntry(new File(this.file, list[i]));
        }

        return result;
    }

    /**
     * Write an entry's header information to a header buffer.
     *
     * @param outbuf The tar entry header buffer to fill in.
     */
    public void writeEntryHeader(byte[] outbuf) {
        int offset = 0;

        offset = TarUtils.getNameBytes(this.name, outbuf, offset, NAMELEN);
        offset = TarUtils.getOctalBytes(this.mode, outbuf, offset, MODELEN);
        offset = TarUtils.getOctalBytes(this.userId, outbuf, offset, UIDLEN);
        offset = TarUtils.getOctalBytes(this.groupId, outbuf, offset, GIDLEN);
        offset = TarUtils.getLongOctalBytes(this.size, outbuf, offset, SIZELEN);
        offset = TarUtils.getLongOctalBytes(this.modTime, outbuf, offset, MODTIMELEN);

        int csOffset = offset;

        for (int c = 0; c < CHKSUMLEN; ++c) {
            outbuf[offset++] = (byte) ' ';
        }

        outbuf[offset++] = this.linkFlag;
        offset = TarUtils.getNameBytes(this.linkName, outbuf, offset, NAMELEN);
        offset = TarUtils.getNameBytes(this.magic, outbuf, offset, MAGICLEN);
        offset = TarUtils.getNameBytes(this.userName, outbuf, offset, UNAMELEN);
        offset = TarUtils.getNameBytes(this.groupName, outbuf, offset, GNAMELEN);
        offset = TarUtils.getOctalBytes(this.devMajor, outbuf, offset, DEVLEN);
        offset = TarUtils.getOctalBytes(this.devMinor, outbuf, offset, DEVLEN);

        while (offset < outbuf.length) {
            outbuf[offset++] = 0;
        }

        long checkSum = TarUtils.computeCheckSum(outbuf);

        TarUtils.getCheckSumOctalBytes(checkSum, outbuf, csOffset, CHKSUMLEN);
    }

    /**
     * Parse an entry's header information from a header buffer.
     *
     * @param header The tar entry header buffer to get information from.
     */
    public void parseTarHeader(byte[] header) {
        int offset = 0;

        this.name = TarUtils.parseName(header, offset, NAMELEN);
        offset += NAMELEN;
        this.mode = (int) TarUtils.parseOctal(header, offset, MODELEN);
        offset += MODELEN;
        this.userId = (int) TarUtils.parseOctal(header, offset, UIDLEN);
        offset += UIDLEN;
        this.groupId = (int) TarUtils.parseOctal(header, offset, GIDLEN);
        offset += GIDLEN;
        this.size = TarUtils.parseOctal(header, offset, SIZELEN);
        offset += SIZELEN;
        this.modTime = TarUtils.parseOctal(header, offset, MODTIMELEN);
        offset += MODTIMELEN;
        this.checkSum = (int) TarUtils.parseOctal(header, offset, CHKSUMLEN);
        offset += CHKSUMLEN;
        this.linkFlag = header[offset++];
        this.linkName = TarUtils.parseName(header, offset, NAMELEN);
        offset += NAMELEN;
        this.magic = TarUtils.parseName(header, offset, MAGICLEN);
        offset += MAGICLEN;
        this.userName = TarUtils.parseName(header, offset, UNAMELEN);
        offset += UNAMELEN;
        this.groupName = TarUtils.parseName(header, offset, GNAMELEN);
        offset += GNAMELEN;
        this.devMajor = (int) TarUtils.parseOctal(header, offset, DEVLEN);
        offset += DEVLEN;
        this.devMinor = (int) TarUtils.parseOctal(header, offset, DEVLEN);

FUNC_DECL VAR_DECL LOOP LOOP VAR_DECL VAR_DECL PARAM CALL BINARY_OP ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN BINARY_OP ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR ASSIGN ASSIGN LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR

FUNC_DECL VAR_DECL PARAM ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN ASSIGN CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL


public class RecordFactory
{
    private static int           NUM_RECORDS = 10000;
    private static final Class[] records;

    static {
        if (FormulaRecord.EXPERIMENTAL_FORMULA_SUPPORT_ENABLED) {
            records = new Class[]
            {
                BOFRecord.class, InterfaceHdrRecord.class, MMSRecord.class,
                InterfaceEndRecord.class, WriteAccessRecord.class,
                CodepageRecord.class, DSFRecord.class, TabIdRecord.class,
                FnGroupCountRecord.class, WindowProtectRecord.class,
                ProtectRecord.class, PasswordRecord.class, ProtectionRev4Record.class,
                PasswordRev4Record.class, WindowOneRecord.class, BackupRecord.class,
                HideObjRecord.class, DateWindow1904Record.class,
                PrecisionRecord.class, RefreshAllRecord.class, BookBoolRecord.class,
                FontRecord.class, FormatRecord.class, ExtendedFormatRecord.class,
                StyleRecord.class, UseSelFSRecord.class, BoundSheetRecord.class,
                CountryRecord.class, SSTRecord.class, ExtSSTRecord.class,
                EOFRecord.class, IndexRecord.class, CalcModeRecord.class,
                CalcCountRecord.class, RefModeRecord.class, IterationRecord.class,
                DeltaRecord.class, SaveRecalcRecord.class, PrintHeadersRecord.class,
                PrintGridlinesRecord.class, GridsetRecord.class, GutsRecord.class,
                DefaultRowHeightRecord.class, WSBoolRecord.class, HeaderRecord.class,
                FooterRecord.class, HCenterRecord.class, VCenterRecord.class,
                PrintSetupRecord.class, DefaultColWidthRecord.class,
                DimensionsRecord.class, RowRecord.class, LabelSSTRecord.class,
                RKRecord.class, NumberRecord.class, DBCellRecord.class,
                WindowTwoRecord.class, SelectionRecord.class, ContinueRecord.class,
                LabelRecord.class, BlankRecord.class, ColumnInfoRecord.class,
                MulRKRecord.class, MulBlankRecord.class, MergeCellsRecord.class,
                FormulaRecord.class, BoolErrRecord.class, ExternSheetRecord.class,
                NameRecord.class, LeftMarginRecord.class, RightMarginRecord.class,
                TopMarginRecord.class, BottomMarginRecord.class,
                DrawingRecord.class, DrawingGroupRecord.class, DrawingSelectionRecord.class,
                ObjRecord.class, TextObjectRecord.class,
                PaletteRecord.class, StringRecord.class, RecalcIdRecord.class, SharedFormulaRecord.class,
                HorizontalPageBreakRecord.class, VerticalPageBreakRecord.class
            };
        } else {
            records = new Class[]
            {
                BOFRecord.class, InterfaceHdrRecord.class, MMSRecord.class,
                InterfaceEndRecord.class, WriteAccessRecord.class,
                CodepageRecord.class, DSFRecord.class, TabIdRecord.class,
                FnGroupCountRecord.class, WindowProtectRecord.class,
                ProtectRecord.class, PasswordRecord.class, ProtectionRev4Record.class,
                PasswordRev4Record.class, WindowOneRecord.class, BackupRecord.class,
                HideObjRecord.class, DateWindow1904Record.class,
                PrecisionRecord.class, RefreshAllRecord.class, BookBoolRecord.class,
                FontRecord.class, FormatRecord.class, ExtendedFormatRecord.class,
                StyleRecord.class, UseSelFSRecord.class, BoundSheetRecord.class,
                CountryRecord.class, SSTRecord.class, ExtSSTRecord.class,
                EOFRecord.class, IndexRecord.class, CalcModeRecord.class,
                CalcCountRecord.class, RefModeRecord.class, IterationRecord.class,
                DeltaRecord.class, SaveRecalcRecord.class, PrintHeadersRecord.class,
                PrintGridlinesRecord.class, GridsetRecord.class, GutsRecord.class,
                DefaultRowHeightRecord.class, WSBoolRecord.class, HeaderRecord.class,
                FooterRecord.class, HCenterRecord.class, VCenterRecord.class,
                PrintSetupRecord.class, DefaultColWidthRecord.class,
                DimensionsRecord.class, RowRecord.class, LabelSSTRecord.class,
                RKRecord.class, NumberRecord.class, DBCellRecord.class,
                WindowTwoRecord.class, SelectionRecord.class, ContinueRecord.class,
                LabelRecord.class, BlankRecord.class, ColumnInfoRecord.class,
                MulRKRecord.class, MulBlankRecord.class, MergeCellsRecord.class,
                BoolErrRecord.class, ExternSheetRecord.class, NameRecord.class,
                LeftMarginRecord.class, RightMarginRecord.class,
                TopMarginRecord.class, BottomMarginRecord.class,
                PaletteRecord.class, StringRecord.class, RecalcIdRecord.class, SharedFormulaRecord.class,
                DrawingRecord.class, DrawingGroupRecord.class, DrawingSelectionRecord.class,
                ObjRecord.class, TextObjectRecord.class,
                HorizontalPageBreakRecord.class, VerticalPageBreakRecord.class
            };

        }
    }
    private static Map           recordsMap  = recordsToMap(records);

    /**
     * changes the default capacity (10000) to handle larger files
     */

    public static void setCapacity(int capacity)
    {
        NUM_RECORDS = capacity;
    }

    /**
     * Create an array of records from an input stream
     *
     * @param in the InputStream from which the records will be
     *           obtained
     *
     * @return an array of Records created from the InputStream
     *
     * @exception RecordFormatException on error processing the
     *            InputStream
     */

    public static List createRecords(InputStream in)
        throws RecordFormatException
    {
        ArrayList records     = new ArrayList(NUM_RECORDS);
        Record    last_record = null;

        try
        {
            short rectype = 0;

            do
            {
                rectype = LittleEndian.readShort(in);
                if (rectype != 0)
                {
                    short  recsize = LittleEndian.readShort(in);
                    byte[] data    = new byte[ ( int ) recsize ];

                    in.read(data);
                    Record[] recs = createRecord(rectype, recsize);

                    if (recs.length > 1)
                    {
                        for (int k = 0; k < recs.length; k++)
                        {
                            records.add();
						}
                    }
                    else
                    {
                        Record record = recs[ 0 ];

                        if (record != null)
                        {
                            if (rectype == ContinueRecord.sid)
                            {
                                if (last_record == null)
                                {
                                    throw new RecordFormatException(
                                        "First record is a ContinueRecord??");
                                }
                                last_record.processContinueRecord(data);
                            }
                            else
                            {
                                last_record = record;
                                records.add(record);
                            }
                        }
                    }
                }
            }
            while (rectype != 0);
        }
        catch (IOException e)
        {
            throw new RecordFormatException("Error reading bytes");
        }

        return records;
    }

    public static Record [] createRecord(short rectype, short size,
                                         byte [] data)
    {
        Record   retval     = null;
        Record[] realretval = null;

        try
        {
            Constructor constructor =
                ( Constructor ) recordsMap.get(new Short(rectype));

            if (constructor != null)
            {
                retval = ( Record ) constructor.newInstance(new Object[]
                {
                    new Short(rectype), new Short(size), data
                });
            }
            else
            {
                retval = new UnknownRecord(rectype, size, data);
            }
        }
        catch (Exception introspectionException)
        {
            introspectionException.printStackTrace();
            throw new RecordFormatException(
                "Unable to construct record instance, the following exception occured: " + introspectionException.getMessage());
        }
        if (retval instanceof RKRecord)
        {
            RKRecord     rk  = ( RKRecord ) retval;
            NumberRecord num = new NumberRecord();

            num.setColumn(rk.getColumn());
            num.setRow(rk.getRow());
            num.setXFIndex(rk.getXFIndex());
            num.setValue(rk.getRKNumber());
            retval = num;
        }
        else if (retval instanceof DBCellRecord)
        {
            retval = null;
        }
        else if (retval instanceof MulRKRecord)
        {
            MulRKRecord mrk = ( MulRKRecord ) retval;

            realretval = new Record[ mrk.getNumColumns() ];
            for (int k = 0; k < mrk.getNumColumns(); k++)
            {
                NumberRecord nr = new NumberRecord();

                nr.setColumn(( short ) (k + mrk.getFirstColumn()));
                nr.setRow(mrk.getRow());
                nr.setXFIndex(mrk.getXFAt(k));
                nr.setValue(mrk.getRKNumberAt(k));
                realretval[ k ] = nr;
            }
        }
        else if (retval instanceof MulBlankRecord)
        {
            MulBlankRecord mb = ( MulBlankRecord ) retval;

            realretval = new Record[ mb.getNumColumns() ];
            for (int k = 0; k < mb.getNumColumns(); k++)
            {
                BlankRecord br = new BlankRecord();

                br.setColumn(( short ) (k + mb.getFirstColumn()));
                br.setRow(mb.getRow());
                br.setXFIndex(mb.getXFAt(k));
                realretval[ k ] = br;
            }
        }
        if (realretval == null)
        {
            realretval      = new Record[ 1 ];
            realretval[ 0 ] = retval;
        }
        return realretval;
    }

    public static short [] getAllKnownRecordSIDs()
    {
        short[] results = new short[ recordsMap.size() ];
        int     i       = 0;

        for (Iterator iterator = recordsMap.keySet().iterator();
                iterator.hasNext(); )
        {
            Short sid = ( Short ) iterator.next();

            results[ i++ ] = sid.shortValue();
        }
        return results;
    }

    private static Map recordsToMap(Class [] records)
    {
        Map         result = new HashMap();
        Constructor constructor;

        for (int i = 0; i < records.length; i++)
        {
            Class record = null;
            short sid    = 0;

            record = records[ i ];
            try
            {
                sid         = record.getField("sid").getShort(null);
                constructor = record.getConstructor(new Class[]
                {
                    short.class, short.class, byte [].class
                });
            }
            catch (Exception illegalArgumentException)
            {
                illegalArgumentException.printStackTrace();
                throw new RecordFormatException(
                    "Unable to determine record types");
            }
            result.put(new Short(sid), constructor);
        }
        return result;