changeset 1713:1b1bec45c3bf

more 1.4+ support
author bachmann
date Fri, 18 Mar 2011 07:28:23 +0000
parents 17d97948ff34
children 8b336ea39b7d
files make/tools/src/build/tools/charsetmapping/InputMismatchException.java make/tools/src/build/tools/charsetmapping/NoSuchElementException.java make/tools/src/build/tools/charsetmapping/Scanner.java make/tools/src/build/tools/compilefontconfig/CompositeFontDescriptor.java make/tools/src/build/tools/compilefontconfig/FontConfiguration.java
diffstat 5 files changed, 5181 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/tools/src/build/tools/charsetmapping/InputMismatchException.java	Fri Mar 18 07:28:23 2011 +0000
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package build.tools.charsetmapping;
+
+/**
+ * Thrown by a <code>Scanner</code> to indicate that the token
+ * retrieved does not match the pattern for the expected type, or
+ * that the token is out of range for the expected type.
+ *
+ * @author  unascribed
+ * @see     java.util.Scanner
+ * @since   1.5
+ */
+public
+class InputMismatchException extends NoSuchElementException {
+    private static final long serialVersionUID = 8811230760997066428L;
+
+    /**
+     * Constructs an <code>InputMismatchException</code> with <tt>null</tt>
+     * as its error message string.
+     */
+    public InputMismatchException() {
+        super();
+    }
+
+    /**
+     * Constructs an <code>InputMismatchException</code>, saving a reference
+     * to the error message string <tt>s</tt> for later retrieval by the
+     * <tt>getMessage</tt> method.
+     *
+     * @param   s   the detail message.
+     */
+    public InputMismatchException(String s) {
+        super(s);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/tools/src/build/tools/charsetmapping/NoSuchElementException.java	Fri Mar 18 07:28:23 2011 +0000
@@ -0,0 +1,60 @@
+/*
+ * Copyright 1994-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package build.tools.charsetmapping;
+
+/**
+ * Thrown by the <code>nextElement</code> method of an
+ * <code>Enumeration</code> to indicate that there are no more
+ * elements in the enumeration.
+ *
+ * @author  unascribed
+ * @see     java.util.Enumeration
+ * @see     java.util.Enumeration#nextElement()
+ * @since   JDK1.0
+ */
+public
+class NoSuchElementException extends RuntimeException {
+    private static final long serialVersionUID = 6769829250639411880L;
+
+    /**
+     * Constructs a <code>NoSuchElementException</code> with <tt>null</tt>
+     * as its error message string.
+     */
+    public NoSuchElementException() {
+        super();
+    }
+
+    /**
+     * Constructs a <code>NoSuchElementException</code>, saving a reference
+     * to the error message string <tt>s</tt> for later retrieval by the
+     * <tt>getMessage</tt> method.
+     *
+     * @param   s   the detail message.
+     */
+    public NoSuchElementException(String s) {
+        super(s);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/tools/src/build/tools/charsetmapping/Scanner.java	Fri Mar 18 07:28:23 2011 +0000
@@ -0,0 +1,2611 @@
+/*
+ * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package build.tools.charsetmapping;
+
+import java.util.regex.*;
+import java.io.*;
+import java.math.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+import java.text.*;
+import java.util.Locale;
+import sun.misc.LRUCache;
+import java.util.Iterator;
+
+/**
+ * A simple text scanner which can parse primitive types and strings using
+ * regular expressions.
+ *
+ * <p>A <code>Scanner</code> breaks its input into tokens using a
+ * delimiter pattern, which by default matches whitespace. The resulting
+ * tokens may then be converted into values of different types using the
+ * various <tt>next</tt> methods.
+ *
+ * <p>For example, this code allows a user to read a number from
+ * <tt>System.in</tt>:
+ * <blockquote><pre>
+ *     Scanner sc = new Scanner(System.in);
+ *     int i = sc.nextInt();
+ * </pre></blockquote>
+ *
+ * <p>As another example, this code allows <code>long</code> types to be
+ * assigned from entries in a file <code>myNumbers</code>:
+ * <blockquote><pre>
+ *      Scanner sc = new Scanner(new File("myNumbers"));
+ *      while (sc.hasNextLong()) {
+ *          long aLong = sc.nextLong();
+ *      }</pre></blockquote>
+ *
+ * <p>The scanner can also use delimiters other than whitespace. This
+ * example reads several items in from a string:
+ *<blockquote><pre>
+ *     String input = "1 fish 2 fish red fish blue fish";
+ *     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
+ *     System.out.println(s.nextInt());
+ *     System.out.println(s.nextInt());
+ *     System.out.println(s.next());
+ *     System.out.println(s.next());
+ *     s.close(); </pre></blockquote>
+ * <p>
+ * prints the following output:
+ * <blockquote><pre>
+ *     1
+ *     2
+ *     red
+ *     blue </pre></blockquote>
+ *
+ * <p>The same output can be generated with this code, which uses a regular
+ * expression to parse all four tokens at once:
+ *<blockquote><pre>
+ *     String input = "1 fish 2 fish red fish blue fish";
+ *     Scanner s = new Scanner(input);
+ *     s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
+ *     MatchResult result = s.match();
+ *     for (int i=1; i<=result.groupCount(); i++)
+ *         System.out.println(result.group(i));
+ *     s.close(); </pre></blockquote>
+ *
+ * <p>The <a name="default-delimiter">default whitespace delimiter</a> used
+ * by a scanner is as recognized by {@link java.lang.Character}.{@link
+ * java.lang.Character#isWhitespace(char) isWhitespace}. The {@link #reset}
+ * method will reset the value of the scanner's delimiter to the default
+ * whitespace delimiter regardless of whether it was previously changed.
+ *
+ * <p>A scanning operation may block waiting for input.
+ *
+ * <p>The {@link #next} and {@link #hasNext} methods and their
+ * primitive-type companion methods (such as {@link #nextInt} and
+ * {@link #hasNextInt}) first skip any input that matches the delimiter
+ * pattern, and then attempt to return the next token. Both <tt>hasNext</tt>
+ * and <tt>next</tt> methods may block waiting for further input.  Whether a
+ * <tt>hasNext</tt> method blocks has no connection to whether or not its
+ * associated <tt>next</tt> method will block.
+ *
+ * <p> The {@link #findInLine}, {@link #findWithinHorizon}, and {@link #skip}
+ * methods operate independently of the delimiter pattern. These methods will
+ * attempt to match the specified pattern with no regard to delimiters in the
+ * input and thus can be used in special circumstances where delimiters are
+ * not relevant. These methods may block waiting for more input.
+ *
+ * <p>When a scanner throws an {@link InputMismatchException}, the scanner
+ * will not pass the token that caused the exception, so that it may be
+ * retrieved or skipped via some other method.
+ *
+ * <p>Depending upon the type of delimiting pattern, empty tokens may be
+ * returned. For example, the pattern <tt>"\\s+"</tt> will return no empty
+ * tokens since it matches multiple instances of the delimiter. The delimiting
+ * pattern <tt>"\\s"</tt> could return empty tokens since it only passes one
+ * space at a time.
+ *
+ * <p> A scanner can read text from any object which implements the {@link
+ * java.lang.Readable} interface.  If an invocation of the underlying
+ * readable's {@link java.lang.Readable#read} method throws an {@link
+ * java.io.IOException} then the scanner assumes that the end of the input
+ * has been reached.  The most recent <tt>IOException</tt> thrown by the
+ * underlying readable can be retrieved via the {@link #ioException} method.
+ *
+ * <p>When a <code>Scanner</code> is closed, it will close its input source
+ * if the source implements the {@link java.io.Closeable} interface.
+ *
+ * <p>A <code>Scanner</code> is not safe for multithreaded use without
+ * external synchronization.
+ *
+ * <p>Unless otherwise mentioned, passing a <code>null</code> parameter into
+ * any method of a <code>Scanner</code> will cause a
+ * <code>NullPointerException</code> to be thrown.
+ *
+ * <p>A scanner will default to interpreting numbers as decimal unless a
+ * different radix has been set by using the {@link #useRadix} method. The
+ * {@link #reset} method will reset the value of the scanner's radix to
+ * <code>10</code> regardless of whether it was previously changed.
+ *
+ * <a name="localized-numbers">
+ * <h4> Localized numbers </h4>
+ *
+ * <p> An instance of this class is capable of scanning numbers in the standard
+ * formats as well as in the formats of the scanner's locale. A scanner's
+ * <a name="initial-locale">initial locale </a>is the value returned by the {@link
+ * java.util.Locale#getDefault} method; it may be changed via the {@link
+ * #useLocale} method. The {@link #reset} method will reset the value of the
+ * scanner's locale to the initial locale regardless of whether it was
+ * previously changed.
+ *
+ * <p>The localized formats are defined in terms of the following parameters,
+ * which for a particular locale are taken from that locale's {@link
+ * java.text.DecimalFormat DecimalFormat} object, <tt>df</tt>, and its and
+ * {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object,
+ * <tt>dfs</tt>.
+ *
+ * <blockquote><table>
+ * <tr><td valign="top"><i>LocalGroupSeparator&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The character used to separate thousands groups,
+ *                      <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
+ *                      java.text.DecimalFormatSymbols#getGroupingSeparator
+ *                      getGroupingSeparator()}</td></tr>
+ * <tr><td valign="top"><i>LocalDecimalSeparator&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The character used for the decimal point,
+ *                      <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
+ *                      java.text.DecimalFormatSymbols#getDecimalSeparator
+ *                      getDecimalSeparator()}</td></tr>
+ * <tr><td valign="top"><i>LocalPositivePrefix&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The string that appears before a positive number (may
+ *                      be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
+ *                      java.text.DecimalFormat#getPositivePrefix
+ *                      getPositivePrefix()}</td></tr>
+ * <tr><td valign="top"><i>LocalPositiveSuffix&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The string that appears after a positive number (may be
+ *                      empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
+ *                      java.text.DecimalFormat#getPositiveSuffix
+ *                      getPositiveSuffix()}</td></tr>
+ * <tr><td valign="top"><i>LocalNegativePrefix&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The string that appears before a negative number (may
+ *                      be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
+ *                      java.text.DecimalFormat#getNegativePrefix
+ *                      getNegativePrefix()}</td></tr>
+ * <tr><td valign="top"><i>LocalNegativeSuffix&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The string that appears after a negative number (may be
+ *                      empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
+ *                      java.text.DecimalFormat#getNegativeSuffix
+ *                      getNegativeSuffix()}</td></tr>
+ * <tr><td valign="top"><i>LocalNaN&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The string that represents not-a-number for
+ *                      floating-point values,
+ *                      <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
+ *                      java.text.DecimalFormatSymbols#getNaN
+ *                      getNaN()}</td></tr>
+ * <tr><td valign="top"><i>LocalInfinity&nbsp;&nbsp;</i></td>
+ *     <td valign="top">The string that represents infinity for floating-point
+ *                      values, <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
+ *                      java.text.DecimalFormatSymbols#getInfinity
+ *                      getInfinity()}</td></tr>
+ * </table></blockquote>
+ *
+ * <a name="number-syntax">
+ * <h4> Number syntax </h4>
+ *
+ * <p> The strings that can be parsed as numbers by an instance of this class
+ * are specified in terms of the following regular-expression grammar, where
+ * Rmax is the highest digit in the radix being used (for example, Rmax is 9
+ * in base 10).
+ *
+ * <p>
+ * <table cellspacing=0 cellpadding=0 align=center>
+ *
+ *   <tr><td valign=top align=right><i>NonASCIIDigit</i>&nbsp;&nbsp;::</td>
+ *       <td valign=top>= A non-ASCII character c for which
+ *            {@link java.lang.Character#isDigit Character.isDigit}<tt>(c)</tt>
+ *                        returns&nbsp;true</td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>Non0Digit</i>&nbsp;&nbsp;::</td>
+ *   <td><tt>= [1-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>Digit</i>&nbsp;&nbsp;::</td>
+ *   <td><tt>= [0-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td valign=top align=right><i>GroupedNumeral</i>&nbsp;&nbsp;::</td>
+ *       <td valign=top>
+ *         <table cellpadding=0 cellspacing=0>
+ *           <tr><td><tt>= (&nbsp;</tt></td>
+ *               <td><i>Non0Digit</i><tt>
+ *                   </tt><i>Digit</i><tt>?
+ *                   </tt><i>Digit</i><tt>?</tt></td></tr>
+ *           <tr><td></td>
+ *               <td><tt>(&nbsp;</tt><i>LocalGroupSeparator</i><tt>
+ *                         </tt><i>Digit</i><tt>
+ *                         </tt><i>Digit</i><tt>
+ *                         </tt><i>Digit</i><tt> )+ )</tt></td></tr>
+ *         </table></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>Numeral</i>&nbsp;&nbsp;::</td>
+ *       <td><tt>= ( ( </tt><i>Digit</i><tt>+ )
+ *               | </tt><i>GroupedNumeral</i><tt> )</tt></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td valign=top align=right>
+ *         <a name="Integer-regex"><i>Integer</i>&nbsp;&nbsp;::</td>
+ *       <td valign=top><tt>= ( [-+]? ( </tt><i>Numeral</i><tt>
+ *                               ) )</tt></td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>LocalPositivePrefix</i><tt> </tt><i>Numeral</i><tt>
+ *                      </tt><i>LocalPositiveSuffix</i></td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>LocalNegativePrefix</i><tt> </tt><i>Numeral</i><tt>
+ *                 </tt><i>LocalNegativeSuffix</i></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>DecimalNumeral</i>&nbsp;&nbsp;::</td>
+ *       <td><tt>= </tt><i>Numeral</i></td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>Numeral</i><tt>
+ *                 </tt><i>LocalDecimalSeparator</i><tt>
+ *                 </tt><i>Digit</i><tt>*</tt></td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>LocalDecimalSeparator</i><tt>
+ *                 </tt><i>Digit</i><tt>+</tt></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>Exponent</i>&nbsp;&nbsp;::</td>
+ *       <td><tt>= ( [eE] [+-]? </tt><i>Digit</i><tt>+ )</tt></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right>
+ *         <a name="Decimal-regex"><i>Decimal</i>&nbsp;&nbsp;::</td>
+ *       <td><tt>= ( [-+]? </tt><i>DecimalNumeral</i><tt>
+ *                         </tt><i>Exponent</i><tt>? )</tt></td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>LocalPositivePrefix</i><tt>
+ *                 </tt><i>DecimalNumeral</i><tt>
+ *                 </tt><i>LocalPositiveSuffix</i>
+ *                 </tt><i>Exponent</i><tt>?</td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>LocalNegativePrefix</i><tt>
+ *                 </tt><i>DecimalNumeral</i><tt>
+ *                 </tt><i>LocalNegativeSuffix</i>
+ *                 </tt><i>Exponent</i><tt>?</td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>HexFloat</i>&nbsp;&nbsp;::</td>
+ *       <td><tt>= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+
+ *                 ([pP][-+]?[0-9]+)?</tt></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>NonNumber</i>&nbsp;&nbsp;::</td>
+ *       <td valign=top><tt>= NaN
+ *                          | </tt><i>LocalNan</i><tt>
+ *                          | Infinity
+ *                          | </tt><i>LocalInfinity</i></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td align=right><i>SignedNonNumber</i>&nbsp;&nbsp;::</td>
+ *       <td><tt>= ( [-+]? </tt><i>NonNumber</i><tt> )</tt></td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>LocalPositivePrefix</i><tt>
+ *                 </tt><i>NonNumber</i><tt>
+ *                 </tt><i>LocalPositiveSuffix</i></td></tr>
+ *   <tr><td></td>
+ *       <td><tt>| </tt><i>LocalNegativePrefix</i><tt>
+ *                 </tt><i>NonNumber</i><tt>
+ *                 </tt><i>LocalNegativeSuffix</i></td></tr>
+ *
+ *   <tr><td>&nbsp;</td></tr>
+ *
+ *   <tr><td valign=top align=right>
+ *         <a name="Float-regex"><i>Float</i>&nbsp;&nbsp;::</td>
+ *       <td valign=top><tt>= </tt><i>Decimal</i><tt></td></tr>
+ *       <tr><td></td>
+ *           <td><tt>| </tt><i>HexFloat</i><tt></td></tr>
+ *       <tr><td></td>
+ *           <td><tt>| </tt><i>SignedNonNumber</i><tt></td></tr>
+ *
+ * </table>
+ * </center>
+ *
+ * <p> Whitespace is not significant in the above regular expressions.
+ *
+ * @since   1.5
+ */
+public final class Scanner implements Iterator {
+
+    // Internal buffer used to hold input
+    private CharBuffer buf;
+
+    // Size of internal character buffer
+    private static final int BUFFER_SIZE = 1024; // change to 1024;
+
+    // The index into the buffer currently held by the Scanner
+    private int position;
+
+    // Internal matcher used for finding delimiters
+    private Matcher matcher;
+
+    // Pattern used to delimit tokens
+    private Pattern delimPattern;
+
+    // Pattern found in last hasNext operation
+    private Pattern hasNextPattern;
+
+    // Position after last hasNext operation
+    private int hasNextPosition;
+
+    // Result after last hasNext operation
+    private String hasNextResult;
+
+    // The input source
+    private Readable source;
+
+    // Boolean is true if source is done
+    private boolean sourceClosed = false;
+
+    // Boolean indicating more input is required
+    private boolean needInput = false;
+
+    // Boolean indicating if a delim has been skipped this operation
+    private boolean skipped = false;
+
+    // A store of a position that the scanner may fall back to
+    private int savedScannerPosition = -1;
+
+    // A cache of the last primitive type scanned
+    private Object typeCache = null;
+
+    // Boolean indicating if a match result is available
+    private boolean matchValid = false;
+
+    // Boolean indicating if this scanner has been closed
+    private boolean closed = false;
+
+    // The current radix used by this scanner
+    private int radix = 10;
+
+    // The default radix for this scanner
+    private int defaultRadix = 10;
+
+    // The locale used by this scanner
+    private Locale locale = null;
+
+    // A cache of the last few recently used Patterns
+    private LRUCache patternCache =
+    new LRUCache(7) {
+        protected Object create(Object s) {
+            return Pattern.compile((String)s);
+        }
+        protected boolean hasName(Object o1, Object o2) {
+        	Pattern p = (Pattern)o1;
+        	String s = (String)o2;
+            return p.pattern().equals(s);
+        }
+    };
+
+    // A holder of the last IOException encountered
+    private IOException lastException;
+
+    // A pattern for java whitespace
+    private static Pattern WHITESPACE_PATTERN = Pattern.compile(
+                                                "\\p{javaWhitespace}+");
+
+    // A pattern for any token
+    private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*");
+
+    // A pattern for non-ASCII digits
+    private static Pattern NON_ASCII_DIGIT = Pattern.compile(
+        "[\\p{javaDigit}&&[^0-9]]");
+
+    // Fields and methods to support scanning primitive types
+
+    /**
+     * Locale dependent values used to scan numbers
+     */
+    private String groupSeparator = "\\,";
+    private String decimalSeparator = "\\.";
+    private String nanString = "NaN";
+    private String infinityString = "Infinity";
+    private String positivePrefix = "";
+    private String negativePrefix = "\\-";
+    private String positiveSuffix = "";
+    private String negativeSuffix = "";
+
+    /**
+     * Fields and an accessor method to match booleans
+     */
+    private static volatile Pattern boolPattern;
+    private static final String BOOLEAN_PATTERN = "true|false";
+    private static Pattern boolPattern() {
+        Pattern bp = boolPattern;
+        if (bp == null)
+            boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN,
+                                          Pattern.CASE_INSENSITIVE);
+        return bp;
+    }
+
+    /**
+     * Fields and methods to match bytes, shorts, ints, and longs
+     */
+    private Pattern integerPattern;
+    private String digits = "0123456789abcdefghijklmnopqrstuvwxyz";
+    private String non0Digit = "[\\p{javaDigit}&&[^0]]";
+    private int SIMPLE_GROUP_INDEX = 5;
+    private String buildIntegerPatternString() {
+        String radixDigits = digits.substring(0, radix);
+        // \\p{javaDigit} is not guaranteed to be appropriate
+        // here but what can we do? The final authority will be
+        // whatever parse method is invoked, so ultimately the
+        // Scanner will do the right thing
+        String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})";
+        String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
+                                groupSeparator+digit+digit+digit+")+)";
+        // digit++ is the possessive form which is necessary for reducing
+        // backtracking that would otherwise cause unacceptable performance
+        String numeral = "(("+ digit+"++)|"+groupedNumeral+")";
+        String javaStyleInteger = "([-+]?(" + numeral + "))";
+        String negativeInteger = negativePrefix + numeral + negativeSuffix;
+        String positiveInteger = positivePrefix + numeral + positiveSuffix;
+        return "("+ javaStyleInteger + ")|(" +
+            positiveInteger + ")|(" +
+            negativeInteger + ")";
+    }
+    private Pattern integerPattern() {
+        if (integerPattern == null) {
+            integerPattern = (Pattern)patternCache.forName(buildIntegerPatternString());
+        }
+        return integerPattern;
+    }
+
+    /**
+     * Fields and an accessor method to match line separators
+     */
+    private static volatile Pattern separatorPattern;
+    private static volatile Pattern linePattern;
+    private static final String LINE_SEPARATOR_PATTERN =
+                                           "\r\n|[\n\r\u2028\u2029\u0085]";
+    private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$";
+
+    private static Pattern separatorPattern() {
+        Pattern sp = separatorPattern;
+        if (sp == null)
+            separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN);
+        return sp;
+    }
+
+    private static Pattern linePattern() {
+        Pattern lp = linePattern;
+        if (lp == null)
+            linePattern = lp = Pattern.compile(LINE_PATTERN);
+        return lp;
+    }
+
+    /**
+     * Fields and methods to match floats and doubles
+     */
+    private Pattern floatPattern;
+    private Pattern decimalPattern;
+    private void buildFloatAndDecimalPattern() {
+        // \\p{javaDigit} may not be perfect, see above
+        String digit = "([0-9]|(\\p{javaDigit}))";
+        String exponent = "([eE][+-]?"+digit+"+)?";
+        String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
+                                groupSeparator+digit+digit+digit+")+)";
+        // Once again digit++ is used for performance, as above
+        String numeral = "(("+digit+"++)|"+groupedNumeral+")";
+        String decimalNumeral = "("+numeral+"|"+numeral +
+            decimalSeparator + digit + "*+|"+ decimalSeparator +
+            digit + "++)";
+        String nonNumber = "(NaN|"+nanString+"|Infinity|"+
+                               infinityString+")";
+        String positiveFloat = "(" + positivePrefix + decimalNumeral +
+                            positiveSuffix + exponent + ")";
+        String negativeFloat = "(" + negativePrefix + decimalNumeral +
+                            negativeSuffix + exponent + ")";
+        String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+
+            positiveFloat + "|" + negativeFloat + ")";
+        String hexFloat =
+            "[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?";
+        String positiveNonNumber = "(" + positivePrefix + nonNumber +
+                            positiveSuffix + ")";
+        String negativeNonNumber = "(" + negativePrefix + nonNumber +
+                            negativeSuffix + ")";
+        String signedNonNumber = "(([-+]?"+nonNumber+")|" +
+                                 positiveNonNumber + "|" +
+                                 negativeNonNumber + ")";
+        floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" +
+                                       signedNonNumber);
+        decimalPattern = Pattern.compile(decimal);
+    }
+    private Pattern floatPattern() {
+        if (floatPattern == null) {
+            buildFloatAndDecimalPattern();
+        }
+        return floatPattern;
+    }
+    private Pattern decimalPattern() {
+        if (decimalPattern == null) {
+            buildFloatAndDecimalPattern();
+        }
+        return decimalPattern;
+    }
+
+    // Constructors
+
+    /**
+     * Constructs a <code>Scanner</code> that returns values scanned
+     * from the specified source delimited by the specified pattern.
+     *
+     * @param  source A character source implementing the Readable interface
+     * @param pattern A delimiting pattern
+     * @return A scanner with the specified source and pattern
+     */
+    private Scanner(Readable source, Pattern pattern) {
+        if (source == null)
+            throw new NullPointerException("source");
+        if (pattern == null)
+            throw new NullPointerException("pattern");
+        this.source = source;
+        delimPattern = pattern;
+        buf = CharBuffer.allocate(BUFFER_SIZE);
+        buf.limit(0);
+        matcher = delimPattern.matcher(buf);
+        matcher.useTransparentBounds(true);
+        matcher.useAnchoringBounds(false);
+        useLocale(Locale.getDefault());
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified source.
+     *
+     * @param  source A character source implementing the {@link Readable}
+     *         interface
+     */
+    public Scanner(Readable source) {
+        this(source, WHITESPACE_PATTERN);
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified input stream. Bytes from the stream are converted
+     * into characters using the underlying platform's
+     * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
+     *
+     * @param  source An input stream to be scanned
+     */
+    public Scanner(InputStream source) {
+        this(new InputStreamReader(source), WHITESPACE_PATTERN);
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified input stream. Bytes from the stream are converted
+     * into characters using the specified charset.
+     *
+     * @param  source An input stream to be scanned
+     * @param charsetName The encoding type used to convert bytes from the
+     *        stream into characters to be scanned
+     * @throws IllegalArgumentException if the specified character set
+     *         does not exist
+     */
+    public Scanner(InputStream source, String charsetName) {
+        this(makeReadable(source, charsetName), WHITESPACE_PATTERN);
+    }
+
+    private static Readable makeReadable(InputStream source,
+                                         String charsetName)
+    {
+        if (source == null)
+            throw new NullPointerException("source");
+        InputStreamReader isr = null;
+        try {
+            isr = new InputStreamReader(source, charsetName);
+        } catch (UnsupportedEncodingException uee) {
+            IllegalArgumentException iae = new IllegalArgumentException();
+            iae.initCause(uee);
+            throw iae;
+        }
+        return isr;
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified file. Bytes from the file are converted into
+     * characters using the underlying platform's
+     * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
+     *
+     * @param  source A file to be scanned
+     * @throws FileNotFoundException if source is not found
+     */
+    public Scanner(File source)
+        throws FileNotFoundException
+    {
+        this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified file. Bytes from the file are converted into
+     * characters using the specified charset.
+     *
+     * @param  source A file to be scanned
+     * @param charsetName The encoding type used to convert bytes from the file
+     *        into characters to be scanned
+     * @throws FileNotFoundException if source is not found
+     * @throws IllegalArgumentException if the specified encoding is
+     *         not found
+     */
+    public Scanner(File source, String charsetName)
+        throws FileNotFoundException
+    {
+        this((ReadableByteChannel)(new FileInputStream(source).getChannel()),
+             charsetName);
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified string.
+     *
+     * @param  source A string to scan
+     */
+    public Scanner(String source) {
+        this(new StringReader(source), WHITESPACE_PATTERN);
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified channel. Bytes from the source are converted into
+     * characters using the underlying platform's
+     * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
+     *
+     * @param  source A channel to scan
+     */
+    public Scanner(ReadableByteChannel source) {
+        this(makeReadable(source), WHITESPACE_PATTERN);
+    }
+
+    private static Readable makeReadable(ReadableByteChannel source) {
+        if (source == null)
+            throw new NullPointerException("source");
+        String defaultCharsetName =
+            java.nio.charset.Charset.defaultCharset().name();
+        return Channels.newReader(source,
+                           java.nio.charset.Charset.defaultCharset().name());
+    }
+
+    /**
+     * Constructs a new <code>Scanner</code> that produces values scanned
+     * from the specified channel. Bytes from the source are converted into
+     * characters using the specified charset.
+     *
+     * @param  source A channel to scan
+     * @param charsetName The encoding type used to convert bytes from the
+     *        channel into characters to be scanned
+     * @throws IllegalArgumentException if the specified character set
+     *         does not exist
+     */
+    public Scanner(ReadableByteChannel source, String charsetName) {
+        this(makeReadable(source, charsetName), WHITESPACE_PATTERN);
+    }
+
+    private static Readable makeReadable(ReadableByteChannel source,
+                                  String charsetName)
+    {
+        if (source == null)
+            throw new NullPointerException("source");
+        if (!Charset.isSupported(charsetName))
+            throw new IllegalArgumentException(charsetName);
+        return Channels.newReader(source, charsetName);
+    }
+
+    // Private primitives used to support scanning
+
+    private void saveState() {
+        savedScannerPosition = position;
+    }
+
+    private void revertState() {
+        this.position = savedScannerPosition;
+        savedScannerPosition = -1;
+        skipped = false;
+    }
+
+    private boolean revertState(boolean b) {
+        this.position = savedScannerPosition;
+        savedScannerPosition = -1;
+        skipped = false;
+        return b;
+    }
+
+    private void cacheResult() {
+        hasNextResult = matcher.group();
+        hasNextPosition = matcher.end();
+        hasNextPattern = matcher.pattern();
+    }
+
+    private void cacheResult(String result) {
+        hasNextResult = result;
+        hasNextPosition = matcher.end();
+        hasNextPattern = matcher.pattern();
+    }
+
+    // Clears both regular cache and type cache
+    private void clearCaches() {
+        hasNextPattern = null;
+        typeCache = null;
+    }
+
+    // Also clears both the regular cache and the type cache
+    private String getCachedResult() {
+        position = hasNextPosition;
+        hasNextPattern = null;
+        typeCache = null;
+        return hasNextResult;
+    }
+
+    // Also clears both the regular cache and the type cache
+    private void useTypeCache() {
+        if (closed)
+            throw new IllegalStateException("Scanner closed");
+        position = hasNextPosition;
+        hasNextPattern = null;
+        typeCache = null;
+    }
+
+    // Tries to read more input. May block.
+    private void readInput() {
+        if (buf.limit() == buf.capacity())
+            makeSpace();
+
+        // Prepare to receive data
+        int p = buf.position();
+        buf.position(buf.limit());
+        buf.limit(buf.capacity());
+
+        int n = 0;
+        try {
+            n = source.read(buf);
+        } catch (IOException ioe) {
+            lastException = ioe;
+            n = -1;
+        }
+
+        if (n == -1) {
+            sourceClosed = true;
+            needInput = false;
+        }
+
+        if (n > 0)
+            needInput = false;
+
+        // Restore current position and limit for reading
+        buf.limit(buf.position());
+        buf.position(p);
+    }
+
+    // After this method is called there will either be an exception
+    // or else there will be space in the buffer
+    private boolean makeSpace() {
+        clearCaches();
+        int offset = savedScannerPosition == -1 ?
+            position : savedScannerPosition;
+        buf.position(offset);
+        // Gain space by compacting buffer
+        if (offset > 0) {
+            buf.compact();
+            translateSavedIndexes(offset);
+            position -= offset;
+            buf.flip();
+            return true;
+        }
+        // Gain space by growing buffer
+        int newSize = buf.capacity() * 2;
+        CharBuffer newBuf = CharBuffer.allocate(newSize);
+        newBuf.put(buf);
+        newBuf.flip();
+        translateSavedIndexes(offset);
+        position -= offset;
+        buf = newBuf;
+        matcher.reset(buf);
+        return true;
+    }
+
+    // When a buffer compaction/reallocation occurs the saved indexes must
+    // be modified appropriately
+    private void translateSavedIndexes(int offset) {
+        if (savedScannerPosition != -1)
+            savedScannerPosition -= offset;
+    }
+
+    // If we are at the end of input then NoSuchElement;
+    // If there is still input left then InputMismatch
+    private void throwFor() {
+        skipped = false;
+        if ((sourceClosed) && (position == buf.limit()))
+            throw new NoSuchElementException();
+        else
+            throw new InputMismatchException();
+    }
+
+    // Returns true if a complete token or partial token is in the buffer.
+    // It is not necessary to find a complete token since a partial token
+    // means that there will be another token with or without more input.
+    private boolean hasTokenInBuffer() {
+        matchValid = false;
+        matcher.usePattern(delimPattern);
+        matcher.region(position, buf.limit());
+
+        // Skip delims first
+        if (matcher.lookingAt())
+            position = matcher.end();
+
+        // If we are sitting at the end, no more tokens in buffer
+        if (position == buf.limit())
+            return false;
+
+        return true;
+    }
+
+    /*
+     * Returns a "complete token" that matches the specified pattern
+     *
+     * A token is complete if surrounded by delims; a partial token
+     * is prefixed by delims but not postfixed by them
+     *
+     * The position is advanced to the end of that complete token
+     *
+     * Pattern == null means accept any token at all
+     *
+     * Triple return:
+     * 1. valid string means it was found
+     * 2. null with needInput=false means we won't ever find it
+     * 3. null with needInput=true means try again after readInput
+     */
+    private String getCompleteTokenInBuffer(Pattern pattern) {
+        matchValid = false;
+
+        // Skip delims first
+        matcher.usePattern(delimPattern);
+        if (!skipped) { // Enforcing only one skip of leading delims
+            matcher.region(position, buf.limit());
+            if (matcher.lookingAt()) {
+                // If more input could extend the delimiters then we must wait
+                // for more input
+                if (matcher.hitEnd() && !sourceClosed) {
+                    needInput = true;
+                    return null;
+                }
+                // The delims were whole and the matcher should skip them
+                skipped = true;
+                position = matcher.end();
+            }
+        }
+
+        // If we are sitting at the end, no more tokens in buffer
+        if (position == buf.limit()) {
+            if (sourceClosed)
+                return null;
+            needInput = true;
+            return null;
+        }
+
+        // Must look for next delims. Simply attempting to match the
+        // pattern at this point may find a match but it might not be
+        // the first longest match because of missing input, or it might
+        // match a partial token instead of the whole thing.
+
+        // Then look for next delims
+        matcher.region(position, buf.limit());
+        boolean foundNextDelim = matcher.find();
+        if (foundNextDelim && (matcher.end() == position)) {
+            // Zero length delimiter match; we should find the next one
+            // using the automatic advance past a zero length match;
+            // Otherwise we have just found the same one we just skipped
+            foundNextDelim = matcher.find();
+        }
+        if (foundNextDelim) {
+            // In the rare case that more input could cause the match
+            // to be lost and there is more input coming we must wait
+            // for more input. Note that hitting the end is okay as long
+            // as the match cannot go away. It is the beginning of the
+            // next delims we want to be sure about, we don't care if
+            // they potentially extend further.
+            if (matcher.requireEnd() && !sourceClosed) {
+                needInput = true;
+                return null;
+            }
+            int tokenEnd = matcher.start();
+            // There is a complete token.
+            if (pattern == null) {
+                // Must continue with match to provide valid MatchResult
+                pattern = FIND_ANY_PATTERN;
+            }
+            //  Attempt to match against the desired pattern
+            matcher.usePattern(pattern);
+            matcher.region(position, tokenEnd);
+            if (matcher.matches()) {
+                String s = matcher.group();
+                position = matcher.end();
+                return s;
+            } else { // Complete token but it does not match
+                return null;
+            }
+        }
+
+        // If we can't find the next delims but no more input is coming,
+        // then we can treat the remainder as a whole token
+        if (sourceClosed) {
+            if (pattern == null) {
+                // Must continue with match to provide valid MatchResult
+                pattern = FIND_ANY_PATTERN;
+            }
+            // Last token; Match the pattern here or throw
+            matcher.usePattern(pattern);
+            matcher.region(position, buf.limit());
+            if (matcher.matches()) {
+                String s = matcher.group();
+                position = matcher.end();
+                return s;
+            }
+            // Last piece does not match
+            return null;
+        }
+
+        // There is a partial token in the buffer; must read more
+        // to complete it
+        needInput = true;
+        return null;
+    }
+
+    // Finds the specified pattern in the buffer up to horizon.
+    // Returns a match for the specified input pattern.
+    private String findPatternInBuffer(Pattern pattern, int horizon) {
+        matchValid = false;
+        matcher.usePattern(pattern);
+        int bufferLimit = buf.limit();
+        int horizonLimit = -1;
+        int searchLimit = bufferLimit;
+        if (horizon > 0) {
+            horizonLimit = position + horizon;
+            if (horizonLimit < bufferLimit)
+                searchLimit = horizonLimit;
+        }
+        matcher.region(position, searchLimit);
+        if (matcher.find()) {
+            if (matcher.hitEnd() && (!sourceClosed)) {
+                // The match may be longer if didn't hit horizon or real end
+                if (searchLimit != horizonLimit) {
+                     // Hit an artificial end; try to extend the match
+                    needInput = true;
+                    return null;
+                }
+                // The match could go away depending on what is next
+                if ((searchLimit == horizonLimit) && matcher.requireEnd()) {
+                    // Rare case: we hit the end of input and it happens
+                    // that it is at the horizon and the end of input is
+                    // required for the match.
+                    needInput = true;
+                    return null;
+                }
+            }
+            // Did not hit end, or hit real end, or hit horizon
+            position = matcher.end();
+            return matcher.group();
+        }
+
+        if (sourceClosed)
+            return null;
+
+        // If there is no specified horizon, or if we have not searched
+        // to the specified horizon yet, get more input
+        if ((horizon == 0) || (searchLimit != horizonLimit))
+            needInput = true;
+        return null;
+    }
+
+    // Returns a match for the specified input pattern anchored at
+    // the current position
+    private String matchPatternInBuffer(Pattern pattern) {
+        matchValid = false;
+        matcher.usePattern(pattern);
+        matcher.region(position, buf.limit());
+        if (matcher.lookingAt()) {
+            if (matcher.hitEnd() && (!sourceClosed)) {
+                // Get more input and try again
+                needInput = true;
+                return null;
+            }
+            position = matcher.end();
+            return matcher.group();
+        }
+
+        if (sourceClosed)
+            return null;
+
+        // Read more to find pattern
+        needInput = true;
+        return null;
+    }
+
+    // Throws if the scanner is closed
+    private void ensureOpen() {
+        if (closed)
+            throw new IllegalStateException("Scanner closed");
+    }
+
+    // Public methods
+
+    /**
+     * Closes this scanner.
+     *
+     * <p> If this scanner has not yet been closed then if its underlying
+     * {@linkplain java.lang.Readable readable} also implements the {@link
+     * java.io.Closeable} interface then the readable's <tt>close</tt> method
+     * will be invoked.  If this scanner is already closed then invoking this
+     * method will have no effect.
+     *
+     * <p>Attempting to perform search operations after a scanner has
+     * been closed will result in an {@link IllegalStateException}.
+     *
+     */
+    public void close() {
+        if (closed)
+            return;
+        if (source instanceof Closeable) {
+            try {
+                ((Closeable)source).close();
+            } catch (IOException ioe) {
+                lastException = ioe;
+            }
+        }
+        sourceClosed = true;
+        source = null;
+        closed = true;
+    }
+
+    /**
+     * Returns the <code>IOException</code> last thrown by this
+     * <code>Scanner</code>'s underlying <code>Readable</code>. This method
+     * returns <code>null</code> if no such exception exists.
+     *
+     * @return the last exception thrown by this scanner's readable
+     */
+    public IOException ioException() {
+        return lastException;
+    }
+
+    /**
+     * Returns the <code>Pattern</code> this <code>Scanner</code> is currently
+     * using to match delimiters.
+     *
+     * @return this scanner's delimiting pattern.
+     */
+    public Pattern delimiter() {
+        return delimPattern;
+    }
+
+    /**
+     * Sets this scanner's delimiting pattern to the specified pattern.
+     *
+     * @param pattern A delimiting pattern
+     * @return this scanner
+     */
+    public Scanner useDelimiter(Pattern pattern) {
+        delimPattern = pattern;
+        return this;
+    }
+
+    /**
+     * Sets this scanner's delimiting pattern to a pattern constructed from
+     * the specified <code>String</code>.
+     *
+     * <p> An invocation of this method of the form
+     * <tt>useDelimiter(pattern)</tt> behaves in exactly the same way as the
+     * invocation <tt>useDelimiter(Pattern.compile(pattern))</tt>.
+     *
+     * <p> Invoking the {@link #reset} method will set the scanner's delimiter
+     * to the <a href= "#default-delimiter">default</a>.
+     *
+     * @param pattern A string specifying a delimiting pattern
+     * @return this scanner
+     */
+    public Scanner useDelimiter(String pattern) {
+        delimPattern = (Pattern)patternCache.forName(pattern);
+        return this;
+    }
+
+    /**
+     * Returns this scanner's locale.
+     *
+     * <p>A scanner's locale affects many elements of its default
+     * primitive matching regular expressions; see
+     * <a href= "#localized-numbers">localized numbers</a> above.
+     *
+     * @return this scanner's locale
+     */
+    public Locale locale() {
+        return this.locale;
+    }
+
+    /**
+     * Sets this scanner's locale to the specified locale.
+     *
+     * <p>A scanner's locale affects many elements of its default
+     * primitive matching regular expressions; see
+     * <a href= "#localized-numbers">localized numbers</a> above.
+     *
+     * <p>Invoking the {@link #reset} method will set the scanner's locale to
+     * the <a href= "#initial-locale">initial locale</a>.
+     *
+     * @param locale A string specifying the locale to use
+     * @return this scanner
+     */
+    public Scanner useLocale(Locale locale) {
+        if (locale.equals(this.locale))
+            return this;
+
+        this.locale = locale;
+        DecimalFormat df =
+            (DecimalFormat)NumberFormat.getNumberInstance(locale);
+        DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
+
+        // These must be literalized to avoid collision with regex
+        // metacharacters such as dot or parenthesis
+        groupSeparator =   "\\" + dfs.getGroupingSeparator();
+        decimalSeparator = "\\" + dfs.getDecimalSeparator();
+
+        // Quoting the nonzero length locale-specific things
+        // to avoid potential conflict with metacharacters
+        nanString = "\\Q" + dfs.getNaN() + "\\E";
+        infinityString = "\\Q" + dfs.getInfinity() + "\\E";
+        positivePrefix = df.getPositivePrefix();
+        if (positivePrefix.length() > 0)
+            positivePrefix = "\\Q" + positivePrefix + "\\E";
+        negativePrefix = df.getNegativePrefix();
+        if (negativePrefix.length() > 0)
+            negativePrefix = "\\Q" + negativePrefix + "\\E";
+        positiveSuffix = df.getPositiveSuffix();
+        if (positiveSuffix.length() > 0)
+            positiveSuffix = "\\Q" + positiveSuffix + "\\E";
+        negativeSuffix = df.getNegativeSuffix();
+        if (negativeSuffix.length() > 0)
+            negativeSuffix = "\\Q" + negativeSuffix + "\\E";
+
+        // Force rebuilding and recompilation of locale dependent
+        // primitive patterns
+        integerPattern = null;
+        floatPattern = null;
+
+        return this;
+    }
+
+    /**
+     * Returns this scanner's default radix.
+     *
+     * <p>A scanner's radix affects elements of its default
+     * number matching regular expressions; see
+     * <a href= "#localized-numbers">localized numbers</a> above.
+     *
+     * @return the default radix of this scanner
+     */
+    public int radix() {
+        return this.defaultRadix;
+    }
+
+    /**
+     * Sets this scanner's default radix to the specified radix.
+     *
+     * <p>A scanner's radix affects elements of its default
+     * number matching regular expressions; see
+     * <a href= "#localized-numbers">localized numbers</a> above.
+     *
+     * <p>If the radix is less than <code>Character.MIN_RADIX</code>
+     * or greater than <code>Character.MAX_RADIX</code>, then an
+     * <code>IllegalArgumentException</code> is thrown.
+     *
+     * <p>Invoking the {@link #reset} method will set the scanner's radix to
+     * <code>10</code>.
+     *
+     * @param radix The radix to use when scanning numbers
+     * @return this scanner
+     * @throws IllegalArgumentException if radix is out of range
+     */
+    public Scanner useRadix(int radix) {
+        if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX))
+            throw new IllegalArgumentException("radix:"+radix);
+
+        if (this.defaultRadix == radix)
+            return this;
+        this.defaultRadix = radix;
+        // Force rebuilding and recompilation of radix dependent patterns
+        integerPattern = null;
+        return this;
+    }
+
+    // The next operation should occur in the specified radix but
+    // the default is left untouched.
+    private void setRadix(int radix) {
+        if (this.radix != radix) {
+            // Force rebuilding and recompilation of radix dependent patterns
+            integerPattern = null;
+            this.radix = radix;
+        }
+    }
+
+    /**
+     * Returns the match result of the last scanning operation performed
+     * by this scanner. This method throws <code>IllegalStateException</code>
+     * if no match has been performed, or if the last match was
+     * not successful.
+     *
+     * <p>The various <code>next</code>methods of <code>Scanner</code>
+     * make a match result available if they complete without throwing an
+     * exception. For instance, after an invocation of the {@link #nextInt}
+     * method that returned an int, this method returns a
+     * <code>MatchResult</code> for the search of the
+     * <a href="#Integer-regex"><i>Integer</i></a> regular expression
+     * defined above. Similarly the {@link #findInLine},
+     * {@link #findWithinHorizon}, and {@link #skip} methods will make a
+     * match available if they succeed.
+     *
+     * @return a match result for the last match operation
+     * @throws IllegalStateException  If no match result is available
+     */
+    public MatchResult match() {
+        if (!matchValid)
+            throw new IllegalStateException("No match result available");
+        return matcher.toMatchResult();
+    }
+
+    /**
+     * <p>Returns the string representation of this <code>Scanner</code>. The
+     * string representation of a <code>Scanner</code> contains information
+     * that may be useful for debugging. The exact format is unspecified.
+     *
+     * @return  The string representation of this scanner
+     */
+    public String toString() {
+        StringBuffer sb = new StringBuffer();
+        sb.append("java.util.Scanner");
+        sb.append("[delimiters=" + delimPattern + "]");
+        sb.append("[position=" + position + "]");
+        sb.append("[match valid=" + matchValid + "]");
+        sb.append("[need input=" + needInput + "]");
+        sb.append("[source closed=" + sourceClosed + "]");
+        sb.append("[skipped=" + skipped + "]");
+        sb.append("[group separator=" + groupSeparator + "]");
+        sb.append("[decimal separator=" + decimalSeparator + "]");
+        sb.append("[positive prefix=" + positivePrefix + "]");
+        sb.append("[negative prefix=" + negativePrefix + "]");
+        sb.append("[positive suffix=" + positiveSuffix + "]");
+        sb.append("[negative suffix=" + negativeSuffix + "]");
+        sb.append("[NaN string=" + nanString + "]");
+        sb.append("[infinity string=" + infinityString + "]");
+        return sb.toString();
+    }
+
+    /**
+     * Returns true if this scanner has another token in its input.
+     * This method may block while waiting for input to scan.
+     * The scanner does not advance past any input.
+     *
+     * @return true if and only if this scanner has another token
+     * @throws IllegalStateException if this scanner is closed
+     * @see java.util.Iterator
+     */
+    public boolean hasNext() {
+        ensureOpen();
+        saveState();
+        while (!sourceClosed) {
+            if (hasTokenInBuffer())
+                return revertState(true);
+            readInput();
+        }
+        boolean result = hasTokenInBuffer();
+        return revertState(result);
+    }
+
+    /**
+     * Finds and returns the next complete token from this scanner.
+     * A complete token is preceded and followed by input that matches
+     * the delimiter pattern. This method may block while waiting for input
+     * to scan, even if a previous invocation of {@link #hasNext} returned
+     * <code>true</code>.
+     *
+     * @return the next token
+     * @throws NoSuchElementException if no more tokens are available
+     * @throws IllegalStateException if this scanner is closed
+     * @see java.util.Iterator
+     */
+    public String next() {
+        ensureOpen();
+        clearCaches();
+
+        while (true) {
+            String token = getCompleteTokenInBuffer(null);
+            if (token != null) {
+                matchValid = true;
+                skipped = false;
+                return token;
+            }
+            if (needInput)
+                readInput();
+            else
+                throwFor();
+        }
+    }
+
+    /**
+     * The remove operation is not supported by this implementation of
+     * <code>Iterator</code>.
+     *
+     * @throws UnsupportedOperationException if this method is invoked.
+     * @see java.util.Iterator
+     */
+    public void remove() {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Returns true if the next token matches the pattern constructed from the
+     * specified string. The scanner does not advance past any input.
+     *
+     * <p> An invocation of this method of the form <tt>hasNext(pattern)</tt>
+     * behaves in exactly the same way as the invocation
+     * <tt>hasNext(Pattern.compile(pattern))</tt>.
+     *
+     * @param pattern a string specifying the pattern to scan
+     * @return true if and only if this scanner has another token matching
+     *         the specified pattern
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNext(String pattern)  {
+        return hasNext((Pattern)patternCache.forName(pattern));
+    }
+
+    /**
+     * Returns the next token if it matches the pattern constructed from the
+     * specified string.  If the match is successful, the scanner advances
+     * past the input that matched the pattern.
+     *
+     * <p> An invocation of this method of the form <tt>next(pattern)</tt>
+     * behaves in exactly the same way as the invocation
+     * <tt>next(Pattern.compile(pattern))</tt>.
+     *
+     * @param pattern a string specifying the pattern to scan
+     * @return the next token
+     * @throws NoSuchElementException if no such tokens are available
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public String next(String pattern)  {
+        return next((Pattern)patternCache.forName(pattern));
+    }
+
+    /**
+     * Returns true if the next complete token matches the specified pattern.
+     * A complete token is prefixed and postfixed by input that matches
+     * the delimiter pattern. This method may block while waiting for input.
+     * The scanner does not advance past any input.
+     *
+     * @param pattern the pattern to scan for
+     * @return true if and only if this scanner has another token matching
+     *         the specified pattern
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNext(Pattern pattern) {
+        ensureOpen();
+        if (pattern == null)
+            throw new NullPointerException();
+        hasNextPattern = null;
+        saveState();
+
+        while (true) {
+            if (getCompleteTokenInBuffer(pattern) != null) {
+                matchValid = true;
+                cacheResult();
+                return revertState(true);
+            }
+            if (needInput)
+                readInput();
+            else
+                return revertState(false);
+        }
+    }
+
+    /**
+     * Returns the next token if it matches the specified pattern. This
+     * method may block while waiting for input to scan, even if a previous
+     * invocation of {@link #hasNext(Pattern)} returned <code>true</code>.
+     * If the match is successful, the scanner advances past the input that
+     * matched the pattern.
+     *
+     * @param pattern the pattern to scan for
+     * @return the next token
+     * @throws NoSuchElementException if no more tokens are available
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public String next(Pattern pattern) {
+        ensureOpen();
+        if (pattern == null)
+            throw new NullPointerException();
+
+        // Did we already find this pattern?
+        if (hasNextPattern == pattern)
+            return getCachedResult();
+        clearCaches();
+
+        // Search for the pattern
+        while (true) {
+            String token = getCompleteTokenInBuffer(pattern);
+            if (token != null) {
+                matchValid = true;
+                skipped = false;
+                return token;
+            }
+            if (needInput)
+                readInput();
+            else
+                throwFor();
+        }
+    }
+
+    /**
+     * Returns true if there is another line in the input of this scanner.
+     * This method may block while waiting for input. The scanner does not
+     * advance past any input.
+     *
+     * @return true if and only if this scanner has another line of input
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextLine() {
+        saveState();
+
+        String result = findWithinHorizon(linePattern(), 0);
+        if (result != null) {
+            MatchResult mr = this.match();
+            String lineSep = mr.group(1);
+            if (lineSep != null) {
+                result = result.substring(0, result.length() -
+                                          lineSep.length());
+                cacheResult(result);
+
+            } else {
+                cacheResult();
+            }
+        }
+        revertState();
+        return (result != null);
+    }
+
+    /**
+     * Advances this scanner past the current line and returns the input
+     * that was skipped.
+     *
+     * This method returns the rest of the current line, excluding any line
+     * separator at the end. The position is set to the beginning of the next
+     * line.
+     *
+     * <p>Since this method continues to search through the input looking
+     * for a line separator, it may buffer all of the input searching for
+     * the line to skip if no line separators are present.
+     *
+     * @return the line that was skipped
+     * @throws NoSuchElementException if no line was found
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public String nextLine() {
+        if (hasNextPattern == linePattern())
+            return getCachedResult();
+        clearCaches();
+
+        String result = findWithinHorizon(linePattern, 0);
+        if (result == null)
+            throw new NoSuchElementException("No line found");
+        MatchResult mr = this.match();
+        String lineSep = mr.group(1);
+        if (lineSep != null)
+            result = result.substring(0, result.length() - lineSep.length());
+        if (result == null)
+            throw new NoSuchElementException();
+        else
+            return result;
+    }
+
+    // Public methods that ignore delimiters
+
+    /**
+     * Attempts to find the next occurrence of a pattern constructed from the
+     * specified string, ignoring delimiters.
+     *
+     * <p>An invocation of this method of the form <tt>findInLine(pattern)</tt>
+     * behaves in exactly the same way as the invocation
+     * <tt>findInLine(Pattern.compile(pattern))</tt>.
+     *
+     * @param pattern a string specifying the pattern to search for
+     * @return the text that matched the specified pattern
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public String findInLine(String pattern) {
+        return findInLine((Pattern)patternCache.forName(pattern));
+    }
+
+    /**
+     * Attempts to find the next occurrence of the specified pattern ignoring
+     * delimiters. If the pattern is found before the next line separator, the
+     * scanner advances past the input that matched and returns the string that
+     * matched the pattern.
+     * If no such pattern is detected in the input up to the next line
+     * separator, then <code>null</code> is returned and the scanner's
+     * position is unchanged. This method may block waiting for input that
+     * matches the pattern.
+     *
+     * <p>Since this method continues to search through the input looking
+     * for the specified pattern, it may buffer all of the input searching for
+     * the desired token if no line separators are present.
+     *
+     * @param pattern the pattern to scan for
+     * @return the text that matched the specified pattern
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public String findInLine(Pattern pattern) {
+        ensureOpen();
+        if (pattern == null)
+            throw new NullPointerException();
+        clearCaches();
+        // Expand buffer to include the next newline or end of input
+        int endPosition = 0;
+        saveState();
+        while (true) {
+            String token = findPatternInBuffer(separatorPattern(), 0);
+            if (token != null) {
+                endPosition = matcher.start();
+                break; // up to next newline
+            }
+            if (needInput) {
+                readInput();
+            } else {
+                endPosition = buf.limit();
+                break; // up to end of input
+            }
+        }
+        revertState();
+        int horizonForLine = endPosition - position;
+        // If there is nothing between the current pos and the next
+        // newline simply return null, invoking findWithinHorizon
+        // with "horizon=0" will scan beyond the line bound.
+        if (horizonForLine == 0)
+            return null;
+        // Search for the pattern
+        return findWithinHorizon(pattern, horizonForLine);
+    }
+
+    /**
+     * Attempts to find the next occurrence of a pattern constructed from the
+     * specified string, ignoring delimiters.
+     *
+     * <p>An invocation of this method of the form
+     * <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as
+     * the invocation
+     * <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>.
+     *
+     * @param pattern a string specifying the pattern to search for
+     * @return the text that matched the specified pattern
+     * @throws IllegalStateException if this scanner is closed
+     * @throws IllegalArgumentException if horizon is negative
+     */
+    public String findWithinHorizon(String pattern, int horizon) {
+        return findWithinHorizon((Pattern)patternCache.forName(pattern), horizon);
+    }
+
+    /**
+     * Attempts to find the next occurrence of the specified pattern.
+     *
+     * <p>This method searches through the input up to the specified
+     * search horizon, ignoring delimiters. If the pattern is found the
+     * scanner advances past the input that matched and returns the string
+     * that matched the pattern. If no such pattern is detected then the
+     * null is returned and the scanner's position remains unchanged. This
+     * method may block waiting for input that matches the pattern.
+     *
+     * <p>A scanner will never search more than <code>horizon</code> code
+     * points beyond its current position. Note that a match may be clipped
+     * by the horizon; that is, an arbitrary match result may have been
+     * different if the horizon had been larger. The scanner treats the
+     * horizon as a transparent, non-anchoring bound (see {@link
+     * Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}).
+     *
+     * <p>If horizon is <code>0</code>, then the horizon is ignored and
+     * this method continues to search through the input looking for the
+     * specified pattern without bound. In this case it may buffer all of
+     * the input searching for the pattern.
+     *
+     * <p>If horizon is negative, then an IllegalArgumentException is
+     * thrown.
+     *
+     * @param pattern the pattern to scan for
+     * @return the text that matched the specified pattern
+     * @throws IllegalStateException if this scanner is closed
+     * @throws IllegalArgumentException if horizon is negative
+     */
+    public String findWithinHorizon(Pattern pattern, int horizon) {
+        ensureOpen();
+        if (pattern == null)
+            throw new NullPointerException();
+        if (horizon < 0)
+            throw new IllegalArgumentException("horizon < 0");
+        clearCaches();
+
+        // Search for the pattern
+        while (true) {
+            String token = findPatternInBuffer(pattern, horizon);
+            if (token != null) {
+                matchValid = true;
+                return token;
+            }
+            if (needInput)
+                readInput();
+            else
+                break; // up to end of input
+        }
+        return null;
+    }
+
+    /**
+     * Skips input that matches the specified pattern, ignoring delimiters.
+     * This method will skip input if an anchored match of the specified
+     * pattern succeeds.
+     *
+     * <p>If a match to the specified pattern is not found at the
+     * current position, then no input is skipped and a
+     * <tt>NoSuchElementException</tt> is thrown.
+     *
+     * <p>Since this method seeks to match the specified pattern starting at
+     * the scanner's current position, patterns that can match a lot of
+     * input (".*", for example) may cause the scanner to buffer a large
+     * amount of input.
+     *
+     * <p>Note that it is possible to skip something without risking a
+     * <code>NoSuchElementException</code> by using a pattern that can
+     * match nothing, e.g., <code>sc.skip("[ \t]*")</code>.
+     *
+     * @param pattern a string specifying the pattern to skip over
+     * @return this scanner
+     * @throws NoSuchElementException if the specified pattern is not found
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public Scanner skip(Pattern pattern) {
+        ensureOpen();
+        if (pattern == null)
+            throw new NullPointerException();
+        clearCaches();
+
+        // Search for the pattern
+        while (true) {
+            String token = matchPatternInBuffer(pattern);
+            if (token != null) {
+                matchValid = true;
+                position = matcher.end();
+                return this;
+            }
+            if (needInput)
+                readInput();
+            else
+                throw new NoSuchElementException();
+        }
+    }
+
+    /**
+     * Skips input that matches a pattern constructed from the specified
+     * string.
+     *
+     * <p> An invocation of this method of the form <tt>skip(pattern)</tt>
+     * behaves in exactly the same way as the invocation
+     * <tt>skip(Pattern.compile(pattern))</tt>.
+     *
+     * @param pattern a string specifying the pattern to skip over
+     * @return this scanner
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public Scanner skip(String pattern) {
+        return skip((Pattern)patternCache.forName(pattern));
+    }
+
+    // Convenience methods for scanning primitives
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a boolean value using a case insensitive pattern
+     * created from the string "true|false".  The scanner does not
+     * advance past the input that matched.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         boolean value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextBoolean()  {
+        return hasNext(boolPattern());
+    }
+
+    /**
+     * Scans the next token of the input into a boolean value and returns
+     * that value. This method will throw <code>InputMismatchException</code>
+     * if the next token cannot be translated into a valid boolean value.
+     * If the match is successful, the scanner advances past the input that
+     * matched.
+     *
+     * @return the boolean scanned from the input
+     * @throws InputMismatchException if the next token is not a valid boolean
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean nextBoolean()  {
+        clearCaches();
+        return Boolean.parseBoolean(next(boolPattern()));
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a byte value in the default radix using the
+     * {@link #nextByte} method. The scanner does not advance past any input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         byte value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextByte() {
+        return hasNextByte(defaultRadix);
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a byte value in the specified radix using the
+     * {@link #nextByte} method. The scanner does not advance past any input.
+     *
+     * @param radix the radix used to interpret the token as a byte value
+     * @return true if and only if this scanner's next token is a valid
+     *         byte value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextByte(int radix) {
+        setRadix(radix);
+        boolean result = hasNext(integerPattern());
+        if (result) { // Cache it
+            try {
+                String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
+                    processIntegerToken(hasNextResult) :
+                    hasNextResult;
+                typeCache = Byte.valueOf(Byte.parseByte(s, radix));
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>byte</tt>.
+     *
+     * <p> An invocation of this method of the form
+     * <tt>nextByte()</tt> behaves in exactly the same way as the
+     * invocation <tt>nextByte(radix)</tt>, where <code>radix</code>
+     * is the default radix of this scanner.
+     *
+     * @return the <tt>byte</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public byte nextByte() {
+         return nextByte(defaultRadix);
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>byte</tt>.
+     * This method will throw <code>InputMismatchException</code>
+     * if the next token cannot be translated into a valid byte value as
+     * described below. If the translation is successful, the scanner advances
+     * past the input that matched.
+     *
+     * <p> If the next token matches the <a
+     * href="#Integer-regex"><i>Integer</i></a> regular expression defined
+     * above then the token is converted into a <tt>byte</tt> value as if by
+     * removing all locale specific prefixes, group separators, and locale
+     * specific suffixes, then mapping non-ASCII digits into ASCII
+     * digits via {@link Character#digit Character.digit}, prepending a
+     * negative sign (-) if the locale specific negative prefixes and suffixes
+     * were present, and passing the resulting string to
+     * {@link Byte#parseByte(String, int) Byte.parseByte} with the
+     * specified radix.
+     *
+     * @param radix the radix used to interpret the token as a byte value
+     * @return the <tt>byte</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public byte nextByte(int radix) {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof Byte)
+            && this.radix == radix) {
+            byte val = ((Byte)typeCache).byteValue();
+            useTypeCache();
+            return val;
+        }
+        setRadix(radix);
+        clearCaches();
+        // Search for next byte
+        try {
+            String s = next(integerPattern());
+            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
+                s = processIntegerToken(s);
+            return Byte.parseByte(s, radix);
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a short value in the default radix using the
+     * {@link #nextShort} method. The scanner does not advance past any input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         short value in the default radix
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextShort() {
+        return hasNextShort(defaultRadix);
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a short value in the specified radix using the
+     * {@link #nextShort} method. The scanner does not advance past any input.
+     *
+     * @param radix the radix used to interpret the token as a short value
+     * @return true if and only if this scanner's next token is a valid
+     *         short value in the specified radix
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextShort(int radix) {
+        setRadix(radix);
+        boolean result = hasNext(integerPattern());
+        if (result) { // Cache it
+            try {
+                String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
+                    processIntegerToken(hasNextResult) :
+                    hasNextResult;
+                typeCache = Short.valueOf(Short.parseShort(s, radix));
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>short</tt>.
+     *
+     * <p> An invocation of this method of the form
+     * <tt>nextShort()</tt> behaves in exactly the same way as the
+     * invocation <tt>nextShort(radix)</tt>, where <code>radix</code>
+     * is the default radix of this scanner.
+     *
+     * @return the <tt>short</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public short nextShort() {
+        return nextShort(defaultRadix);
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>short</tt>.
+     * This method will throw <code>InputMismatchException</code>
+     * if the next token cannot be translated into a valid short value as
+     * described below. If the translation is successful, the scanner advances
+     * past the input that matched.
+     *
+     * <p> If the next token matches the <a
+     * href="#Integer-regex"><i>Integer</i></a> regular expression defined
+     * above then the token is converted into a <tt>short</tt> value as if by
+     * removing all locale specific prefixes, group separators, and locale
+     * specific suffixes, then mapping non-ASCII digits into ASCII
+     * digits via {@link Character#digit Character.digit}, prepending a
+     * negative sign (-) if the locale specific negative prefixes and suffixes
+     * were present, and passing the resulting string to
+     * {@link Short#parseShort(String, int) Short.parseShort} with the
+     * specified radix.
+     *
+     * @param radix the radix used to interpret the token as a short value
+     * @return the <tt>short</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public short nextShort(int radix) {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof Short)
+            && this.radix == radix) {
+            short val = ((Short)typeCache).shortValue();
+            useTypeCache();
+            return val;
+        }
+        setRadix(radix);
+        clearCaches();
+        // Search for next short
+        try {
+            String s = next(integerPattern());
+            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
+                s = processIntegerToken(s);
+            return Short.parseShort(s, radix);
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as an int value in the default radix using the
+     * {@link #nextInt} method. The scanner does not advance past any input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         int value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextInt() {
+        return hasNextInt(defaultRadix);
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as an int value in the specified radix using the
+     * {@link #nextInt} method. The scanner does not advance past any input.
+     *
+     * @param radix the radix used to interpret the token as an int value
+     * @return true if and only if this scanner's next token is a valid
+     *         int value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextInt(int radix) {
+        setRadix(radix);
+        boolean result = hasNext(integerPattern());
+        if (result) { // Cache it
+            try {
+                String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
+                    processIntegerToken(hasNextResult) :
+                    hasNextResult;
+                typeCache = new Integer(Integer.parseInt(s, radix));
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * The integer token must be stripped of prefixes, group separators,
+     * and suffixes, non ascii digits must be converted into ascii digits
+     * before parse will accept it.
+     */
+    private String processIntegerToken(String token) {
+        String result = token.replaceAll(""+groupSeparator, "");
+        boolean isNegative = false;
+        int preLen = negativePrefix.length();
+        if ((preLen > 0) && result.startsWith(negativePrefix)) {
+            isNegative = true;
+            result = result.substring(preLen);
+        }
+        int sufLen = negativeSuffix.length();
+        if ((sufLen > 0) && result.endsWith(negativeSuffix)) {
+            isNegative = true;
+            result = result.substring(result.length() - sufLen,
+                                      result.length());
+        }
+        if (isNegative)
+            result = "-" + result;
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as an <tt>int</tt>.
+     *
+     * <p> An invocation of this method of the form
+     * <tt>nextInt()</tt> behaves in exactly the same way as the
+     * invocation <tt>nextInt(radix)</tt>, where <code>radix</code>
+     * is the default radix of this scanner.
+     *
+     * @return the <tt>int</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public int nextInt() {
+        return nextInt(defaultRadix);
+    }
+
+    /**
+     * Scans the next token of the input as an <tt>int</tt>.
+     * This method will throw <code>InputMismatchException</code>
+     * if the next token cannot be translated into a valid int value as
+     * described below. If the translation is successful, the scanner advances
+     * past the input that matched.
+     *
+     * <p> If the next token matches the <a
+     * href="#Integer-regex"><i>Integer</i></a> regular expression defined
+     * above then the token is converted into an <tt>int</tt> value as if by
+     * removing all locale specific prefixes, group separators, and locale
+     * specific suffixes, then mapping non-ASCII digits into ASCII
+     * digits via {@link Character#digit Character.digit}, prepending a
+     * negative sign (-) if the locale specific negative prefixes and suffixes
+     * were present, and passing the resulting string to
+     * {@link Integer#parseInt(String, int) Integer.parseInt} with the
+     * specified radix.
+     *
+     * @param radix the radix used to interpret the token as an int value
+     * @return the <tt>int</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public int nextInt(int radix) {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof Integer)
+            && this.radix == radix) {
+            int val = ((Integer)typeCache).intValue();
+            useTypeCache();
+            return val;
+        }
+        setRadix(radix);
+        clearCaches();
+        // Search for next int
+        try {
+            String s = next(integerPattern());
+            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
+                s = processIntegerToken(s);
+            return Integer.parseInt(s, radix);
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a long value in the default radix using the
+     * {@link #nextLong} method. The scanner does not advance past any input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         long value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextLong() {
+        return hasNextLong(defaultRadix);
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a long value in the specified radix using the
+     * {@link #nextLong} method. The scanner does not advance past any input.
+     *
+     * @param radix the radix used to interpret the token as a long value
+     * @return true if and only if this scanner's next token is a valid
+     *         long value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextLong(int radix) {
+        setRadix(radix);
+        boolean result = hasNext(integerPattern());
+        if (result) { // Cache it
+            try {
+                String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
+                    processIntegerToken(hasNextResult) :
+                    hasNextResult;
+                typeCache = new Long(Long.parseLong(s, radix));
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>long</tt>.
+     *
+     * <p> An invocation of this method of the form
+     * <tt>nextLong()</tt> behaves in exactly the same way as the
+     * invocation <tt>nextLong(radix)</tt>, where <code>radix</code>
+     * is the default radix of this scanner.
+     *
+     * @return the <tt>long</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public long nextLong() {
+        return nextLong(defaultRadix);
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>long</tt>.
+     * This method will throw <code>InputMismatchException</code>
+     * if the next token cannot be translated into a valid long value as
+     * described below. If the translation is successful, the scanner advances
+     * past the input that matched.
+     *
+     * <p> If the next token matches the <a
+     * href="#Integer-regex"><i>Integer</i></a> regular expression defined
+     * above then the token is converted into a <tt>long</tt> value as if by
+     * removing all locale specific prefixes, group separators, and locale
+     * specific suffixes, then mapping non-ASCII digits into ASCII
+     * digits via {@link Character#digit Character.digit}, prepending a
+     * negative sign (-) if the locale specific negative prefixes and suffixes
+     * were present, and passing the resulting string to
+     * {@link Long#parseLong(String, int) Long.parseLong} with the
+     * specified radix.
+     *
+     * @param radix the radix used to interpret the token as an int value
+     * @return the <tt>long</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public long nextLong(int radix) {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof Long)
+            && this.radix == radix) {
+            long val = ((Long)typeCache).longValue();
+            useTypeCache();
+            return val;
+        }
+        setRadix(radix);
+        clearCaches();
+        try {
+            String s = next(integerPattern());
+            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
+                s = processIntegerToken(s);
+            return Long.parseLong(s, radix);
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    /**
+     * The float token must be stripped of prefixes, group separators,
+     * and suffixes, non ascii digits must be converted into ascii digits
+     * before parseFloat will accept it.
+     *
+     * If there are non-ascii digits in the token these digits must
+     * be processed before the token is passed to parseFloat.
+     */
+    private String processFloatToken(String token) {
+        String result = token.replaceAll(groupSeparator, "");
+        if (!decimalSeparator.equals("\\."))
+            result = result.replaceAll(decimalSeparator, ".");
+        boolean isNegative = false;
+        int preLen = negativePrefix.length();
+        if ((preLen > 0) && result.startsWith(negativePrefix)) {
+            isNegative = true;
+            result = result.substring(preLen);
+        }
+        int sufLen = negativeSuffix.length();
+        if ((sufLen > 0) && result.endsWith(negativeSuffix)) {
+            isNegative = true;
+            result = result.substring(result.length() - sufLen,
+                                      result.length());
+        }
+        if (result.equals(nanString))
+            result = "NaN";
+        if (result.equals(infinityString))
+            result = "Infinity";
+        if (isNegative)
+            result = "-" + result;
+
+        // Translate non-ASCII digits
+        Matcher m = NON_ASCII_DIGIT.matcher(result);
+        if (m.find()) {
+            StringBuffer inASCII = new StringBuffer();
+            for (int i=0; i<result.length(); i++) {
+                char nextChar = result.charAt(i);
+                if (Character.isDigit(nextChar)) {
+                    int d = Character.digit(nextChar, 10);
+                    if (d != -1)
+                        inASCII.append(d);
+                    else
+                        inASCII.append(nextChar);
+                } else {
+                    inASCII.append(nextChar);
+                }
+            }
+            result = inASCII.toString();
+        }
+
+        return result;
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a float value using the {@link #nextFloat}
+     * method. The scanner does not advance past any input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         float value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextFloat() {
+        setRadix(10);
+        boolean result = hasNext(floatPattern());
+        if (result) { // Cache it
+            try {
+                String s = processFloatToken(hasNextResult);
+                typeCache = Float.valueOf(Float.parseFloat(s));
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>float</tt>.
+     * This method will throw <code>InputMismatchException</code>
+     * if the next token cannot be translated into a valid float value as
+     * described below. If the translation is successful, the scanner advances
+     * past the input that matched.
+     *
+     * <p> If the next token matches the <a
+     * href="#Float-regex"><i>Float</i></a> regular expression defined above
+     * then the token is converted into a <tt>float</tt> value as if by
+     * removing all locale specific prefixes, group separators, and locale
+     * specific suffixes, then mapping non-ASCII digits into ASCII
+     * digits via {@link Character#digit Character.digit}, prepending a
+     * negative sign (-) if the locale specific negative prefixes and suffixes
+     * were present, and passing the resulting string to
+     * {@link Float#parseFloat Float.parseFloat}. If the token matches
+     * the localized NaN or infinity strings, then either "Nan" or "Infinity"
+     * is passed to {@link Float#parseFloat(String) Float.parseFloat} as
+     * appropriate.
+     *
+     * @return the <tt>float</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Float</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public float nextFloat() {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof Float)) {
+            float val = ((Float)typeCache).floatValue();
+            useTypeCache();
+            return val;
+        }
+        setRadix(10);
+        clearCaches();
+        try {
+            return Float.parseFloat(processFloatToken(next(floatPattern())));
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a double value using the {@link #nextDouble}
+     * method. The scanner does not advance past any input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         double value
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextDouble() {
+        setRadix(10);
+        boolean result = hasNext(floatPattern());
+        if (result) { // Cache it
+            try {
+                String s = processFloatToken(hasNextResult);
+                typeCache = Double.valueOf(Double.parseDouble(s));
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as a <tt>double</tt>.
+     * This method will throw <code>InputMismatchException</code>
+     * if the next token cannot be translated into a valid double value.
+     * If the translation is successful, the scanner advances past the input
+     * that matched.
+     *
+     * <p> If the next token matches the <a
+     * href="#Float-regex"><i>Float</i></a> regular expression defined above
+     * then the token is converted into a <tt>double</tt> value as if by
+     * removing all locale specific prefixes, group separators, and locale
+     * specific suffixes, then mapping non-ASCII digits into ASCII
+     * digits via {@link Character#digit Character.digit}, prepending a
+     * negative sign (-) if the locale specific negative prefixes and suffixes
+     * were present, and passing the resulting string to
+     * {@link Double#parseDouble Double.parseDouble}. If the token matches
+     * the localized NaN or infinity strings, then either "Nan" or "Infinity"
+     * is passed to {@link Double#parseDouble(String) Double.parseDouble} as
+     * appropriate.
+     *
+     * @return the <tt>double</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Float</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if the input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public double nextDouble() {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof Double)) {
+            double val = ((Double)typeCache).doubleValue();
+            useTypeCache();
+            return val;
+        }
+        setRadix(10);
+        clearCaches();
+        // Search for next float
+        try {
+            return Double.parseDouble(processFloatToken(next(floatPattern())));
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    // Convenience methods for scanning multi precision numbers
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a <code>BigInteger</code> in the default radix using the
+     * {@link #nextBigInteger} method. The scanner does not advance past any
+     * input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         <code>BigInteger</code>
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextBigInteger() {
+        return hasNextBigInteger(defaultRadix);
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a <code>BigInteger</code> in the specified radix using
+     * the {@link #nextBigInteger} method. The scanner does not advance past
+     * any input.
+     *
+     * @param radix the radix used to interpret the token as an integer
+     * @return true if and only if this scanner's next token is a valid
+     *         <code>BigInteger</code>
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextBigInteger(int radix) {
+        setRadix(radix);
+        boolean result = hasNext(integerPattern());
+        if (result) { // Cache it
+            try {
+                String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
+                    processIntegerToken(hasNextResult) :
+                    hasNextResult;
+                typeCache = new BigInteger(s, radix);
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as a {@link java.math.BigInteger
+     * BigInteger}.
+     *
+     * <p> An invocation of this method of the form
+     * <tt>nextBigInteger()</tt> behaves in exactly the same way as the
+     * invocation <tt>nextBigInteger(radix)</tt>, where <code>radix</code>
+     * is the default radix of this scanner.
+     *
+     * @return the <tt>BigInteger</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if the input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public BigInteger nextBigInteger() {
+        return nextBigInteger(defaultRadix);
+    }
+
+    /**
+     * Scans the next token of the input as a {@link java.math.BigInteger
+     * BigInteger}.
+     *
+     * <p> If the next token matches the <a
+     * href="#Integer-regex"><i>Integer</i></a> regular expression defined
+     * above then the token is converted into a <tt>BigInteger</tt> value as if
+     * by removing all group separators, mapping non-ASCII digits into ASCII
+     * digits via the {@link Character#digit Character.digit}, and passing the
+     * resulting string to the {@link
+     * java.math.BigInteger#BigInteger(java.lang.String)
+     * BigInteger(String, int)} constructor with the specified radix.
+     *
+     * @param radix the radix used to interpret the token
+     * @return the <tt>BigInteger</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Integer</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if the input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public BigInteger nextBigInteger(int radix) {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof BigInteger)
+            && this.radix == radix) {
+            BigInteger val = (BigInteger)typeCache;
+            useTypeCache();
+            return val;
+        }
+        setRadix(radix);
+        clearCaches();
+        // Search for next int
+        try {
+            String s = next(integerPattern());
+            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
+                s = processIntegerToken(s);
+            return new BigInteger(s, radix);
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    /**
+     * Returns true if the next token in this scanner's input can be
+     * interpreted as a <code>BigDecimal</code> using the
+     * {@link #nextBigDecimal} method. The scanner does not advance past any
+     * input.
+     *
+     * @return true if and only if this scanner's next token is a valid
+     *         <code>BigDecimal</code>
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public boolean hasNextBigDecimal() {
+        setRadix(10);
+        boolean result = hasNext(decimalPattern());
+        if (result) { // Cache it
+            try {
+                String s = processFloatToken(hasNextResult);
+                typeCache = new BigDecimal(s);
+            } catch (NumberFormatException nfe) {
+                result = false;
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Scans the next token of the input as a {@link java.math.BigDecimal
+     * BigDecimal}.
+     *
+     * <p> If the next token matches the <a
+     * href="#Decimal-regex"><i>Decimal</i></a> regular expression defined
+     * above then the token is converted into a <tt>BigDecimal</tt> value as if
+     * by removing all group separators, mapping non-ASCII digits into ASCII
+     * digits via the {@link Character#digit Character.digit}, and passing the
+     * resulting string to the {@link
+     * java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)}
+     * constructor.
+     *
+     * @return the <tt>BigDecimal</tt> scanned from the input
+     * @throws InputMismatchException
+     *         if the next token does not match the <i>Decimal</i>
+     *         regular expression, or is out of range
+     * @throws NoSuchElementException if the input is exhausted
+     * @throws IllegalStateException if this scanner is closed
+     */
+    public BigDecimal nextBigDecimal() {
+        // Check cached result
+        if ((typeCache != null) && (typeCache instanceof BigDecimal)) {
+            BigDecimal val = (BigDecimal)typeCache;
+            useTypeCache();
+            return val;
+        }
+        setRadix(10);
+        clearCaches();
+        // Search for next float
+        try {
+            String s = processFloatToken(next(decimalPattern()));
+            return new BigDecimal(s);
+        } catch (NumberFormatException nfe) {
+            position = matcher.start(); // don't skip bad token
+            throw new InputMismatchException(nfe.getMessage());
+        }
+    }
+
+    /**
+     * Resets this scanner.
+     *
+     * <p> Resetting a scanner discards all of its explicit state
+     * information which may have been changed by invocations of {@link
+     * #useDelimiter}, {@link #useLocale}, or {@link #useRadix}.
+     *
+     * <p> An invocation of this method of the form
+     * <tt>scanner.reset()</tt> behaves in exactly the same way as the
+     * invocation
+     *
+     * <blockquote><pre>
+     *   scanner.useDelimiter("\\p{javaWhitespace}+")
+     *          .useLocale(Locale.getDefault())
+     *          .useRadix(10);
+     * </pre></blockquote>
+     *
+     * @return this scanner
+     *
+     * @since 1.6
+     */
+    public Scanner reset() {
+        delimPattern = WHITESPACE_PATTERN;
+        useLocale(Locale.getDefault());
+        useRadix(10);
+        clearCaches();
+        return this;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/tools/src/build/tools/compilefontconfig/CompositeFontDescriptor.java	Fri Mar 18 07:28:23 2011 +0000
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package build.tools.compilefontconfig;
+
+/**
+ * Encapsulates the information that 2D needs to create a composite font,
+ * the runtime representation of a logical font.
+ */
+public class CompositeFontDescriptor {
+
+    private String faceName;
+    private int coreComponentCount;
+    private String[] componentFaceNames;
+    private String[] componentFileNames;
+    private int[] exclusionRanges;
+    private int[] exclusionRangeLimits;
+
+    /**
+     * Constructs a composite font descriptor.
+     * @param faceName the font face name, i.e., the family name suffixed
+     *                 with ".plain", ".bold", ".italic", ".bolditalic".
+     * @param coreComponentCount the number of core fonts, i.e., the ones
+     *                 derived from a non-fallback sequence.
+     * @param componentFaceNames the face names for the component fonts
+     * @param componentFileNames the file names for the component fonts
+     * @param exclusionRanges an array holding lower and upper boundaries
+     *                 for all exclusion ranges for all component fonts
+     * @param exclusionRangeLimits an array holding the limits of the
+     *                 sections for each component font within the previous
+     *                 array
+     */
+    public CompositeFontDescriptor(String faceName,
+            int coreComponentCount,
+            String[] componentFaceNames,
+            String[] componentFileNames,
+            int[] exclusionRanges,
+            int[] exclusionRangeLimits) {
+        this.faceName = faceName;
+        this.coreComponentCount = coreComponentCount;
+        this.componentFaceNames = componentFaceNames;
+        this.componentFileNames = componentFileNames;
+        this.exclusionRanges = exclusionRanges;
+        this.exclusionRangeLimits = exclusionRangeLimits;
+    }
+
+    public String getFaceName() {
+        return faceName;
+    }
+
+    public int getCoreComponentCount() {
+        return coreComponentCount;
+    }
+
+    public String[] getComponentFaceNames() {
+        return componentFaceNames;
+    }
+
+    public String[] getComponentFileNames() {
+        return componentFileNames;
+    }
+
+    public int[] getExclusionRanges() {
+        return exclusionRanges;
+    }
+
+    public int[] getExclusionRangeLimits() {
+        return exclusionRangeLimits;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/tools/src/build/tools/compilefontconfig/FontConfiguration.java	Fri Mar 18 07:28:23 2011 +0000
@@ -0,0 +1,2359 @@
+/*
+ * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package build.tools.compilefontconfig;
+
+import java.awt.Font;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.logging.Logger;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map.Entry;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Vector;
+import sun.awt.FontDescriptor;
+import sun.java2d.SunGraphicsEnvironment;
+
+/**
+ * Provides the definitions of the five logical fonts: Serif, SansSerif,
+ * Monospaced, Dialog, and DialogInput. The necessary information
+ * is obtained from fontconfig files.
+ */
+public abstract class FontConfiguration {
+
+    /**
+     * A String constant for the canonical family name of the
+     * logical font "Dialog". It is useful in Font construction
+     * to provide compile-time verification of the name.
+     * @since 1.6
+     */
+    public static final String DIALOG = "Dialog";
+
+    /**
+     * A String constant for the canonical family name of the
+     * logical font "DialogInput". It is useful in Font construction
+     * to provide compile-time verification of the name.
+     * @since 1.6
+     */
+    public static final String DIALOG_INPUT = "DialogInput";
+
+    /**
+     * A String constant for the canonical family name of the
+     * logical font "SansSerif". It is useful in Font construction
+     * to provide compile-time verification of the name.
+     * @since 1.6
+     */
+    public static final String SANS_SERIF = "SansSerif";
+
+    /**
+     * A String constant for the canonical family name of the
+     * logical font "Serif". It is useful in Font construction
+     * to provide compile-time verification of the name.
+     * @since 1.6
+     */
+    public static final String SERIF = "Serif";
+
+    /**
+     * A String constant for the canonical family name of the
+     * logical font "Monospaced". It is useful in Font construction
+     * to provide compile-time verification of the name.
+     * @since 1.6
+     */
+    public static final String MONOSPACED = "Monospaced";
+
+    /*
+     * Constants to be used for styles. Can be combined to mix
+     * styles.
+     */
+
+    //static global runtime env
+    protected static String osVersion;
+    protected static String osName;
+    protected static String encoding; // canonical name of default nio charset
+    protected static Locale startupLocale = null;
+    protected static Hashtable localeMap = null;
+    private static FontConfiguration fontConfig;
+    private static Logger logger;
+    protected static boolean isProperties = true;
+
+    protected SunGraphicsEnvironment environment;
+    protected boolean preferLocaleFonts;
+    protected boolean preferPropFonts;
+
+    private File fontConfigFile;
+    private boolean foundOsSpecificFile;
+    private boolean inited;
+    private String javaLib;
+
+    /* A default FontConfiguration must be created before an alternate
+     * one to ensure proper static initialisation takes place.
+     */
+    public FontConfiguration(SunGraphicsEnvironment environment) {
+        if (logger == null) {
+            logger = Logger.getLogger("compilefontconfig.FontConfiguration");
+        }
+        this.environment = environment;
+        setOsNameAndVersion();  /* static initialization */
+        setEncoding();          /* static initialization */
+        /* Separating out the file location from the rest of the
+         * initialisation, so the caller has the option of doing
+         * something else if a suitable file isn't found.
+         */
+        findFontConfigFile();
+    }
+
+    public synchronized boolean init() {
+        if (!inited) {
+            this.preferLocaleFonts = false;
+            this.preferPropFonts = false;
+            setFontConfiguration();
+            readFontConfigFile(fontConfigFile);
+            initFontConfig();
+            inited = true;
+        }
+        return true;
+    }
+
+    public FontConfiguration(SunGraphicsEnvironment environment,
+                             boolean preferLocaleFonts,
+                             boolean preferPropFonts) {
+        this.environment = environment;
+        this.preferLocaleFonts = preferLocaleFonts;
+        this.preferPropFonts = preferPropFonts;
+        /* fontConfig should be initialised by default constructor, and
+         * its data tables can be shared, since readFontConfigFile doesn't
+         * update any other state. Also avoid a doPrivileged block.
+         */
+        initFontConfig();
+    }
+
+    /**
+     * Fills in this instance's osVersion and osName members. By
+     * default uses the system properties os.name and os.version;
+     * subclasses may override.
+     */
+    protected void setOsNameAndVersion() {
+        osName = System.getProperty("os.name");
+        osVersion = System.getProperty("os.version");
+    }
+
+    private void setEncoding() {
+        encoding = Charset.forName("UTF-8").name();
+        if (startupLocale == null) {
+            String language, region, country, variant;
+            language = "en";
+            // for compatibility, check for old user.region property
+            region = null;
+            if (region != null) {
+                // region can be of form country, country_variant, or _variant
+                int i = region.indexOf('_');
+                if (i >= 0) {
+                    country = region.substring(0, i);
+                    variant = region.substring(i + 1);
+                } else {
+                    country = region;
+                    variant = "";
+                }
+            } else {
+                country = "";
+                variant = "";
+            }
+            startupLocale = new Locale(language, country, variant);
+        }
+    }
+
+    /////////////////////////////////////////////////////////////////////
+    // methods for loading the FontConfig file                         //
+    /////////////////////////////////////////////////////////////////////
+
+    public boolean foundOsSpecificFile() {
+        return foundOsSpecificFile;
+    }
+
+    /* Smoke test to see if we can trust this configuration by testing if
+     * the first slot of a composite font maps to an installed file.
+     */
+    public boolean fontFilesArePresent() {
+        init();
+        short fontNameID = compFontNameIDs[0][0][0];
+        short fileNameID = getComponentFileID(fontNameID);
+        final String fileName = mapFileName(getComponentFileName(fileNameID));
+        Boolean exists = (Boolean)java.security.AccessController.doPrivileged(
+            new java.security.PrivilegedAction() {
+                 public Object run() {
+                     try {
+                         File f = new File(fileName);
+                         return Boolean.valueOf(f.exists());
+                     }
+                     catch (Exception e) {
+                         return Boolean.FALSE;
+                     }
+                 }
+                });
+        return exists.booleanValue();
+    }
+
+    private void findFontConfigFile() {
+
+        foundOsSpecificFile = true; // default assumption.
+        String javaHome = System.getProperty("java.home");
+        if (javaHome == null) {
+            throw new Error("java.home property not set");
+        }
+        javaLib = javaHome + File.separator + "lib";
+        String userConfigFile = System.getProperty("sun.awt.fontconfig");
+        if (userConfigFile != null) {
+            fontConfigFile = new File(userConfigFile);
+        } else {
+            fontConfigFile = findFontConfigFile(javaLib);
+        }
+    }
+
+    private void readFontConfigFile(File f) {
+        /* This is invoked here as readFontConfigFile is only invoked
+         * once per VM, and always in a privileged context, thus the
+         * directory containing installed fall back fonts is accessed
+         * from this context
+         */
+        getInstalledFallbackFonts(javaLib);
+
+        if (f != null) {
+            try {
+                FileInputStream in = new FileInputStream(f.getPath());
+                if (isProperties) {
+                    loadProperties(in);
+                } else {
+                    loadBinary(in);
+                }
+                in.close();
+                if (true) {
+                    logger.config("Read logical font configuration from " + f);
+                }
+            } catch (IOException e) {
+                if (true) {
+                    logger.config("Failed to read logical font configuration from " + f);
+                }
+            }
+        }
+        String version = getVersion();
+        if (!"1".equals(version)) {
+            logger.config("Unsupported fontconfig version: " + version);
+        }
+    }
+
+    public class TTFilter implements java.io.FilenameFilter{
+        public boolean accept(File dir,String name) {
+            return(name.endsWith(".ttf") ||
+                   name.endsWith(".TTF") ||
+                   name.endsWith(".ttc") ||
+                   name.endsWith(".TTC"));
+        }
+    }			 
+
+    public class T2KFilter implements java.io.FilenameFilter{
+        public boolean accept(File dir,String name) {
+            return(name.endsWith(".t2k") ||
+                   name.endsWith(".T2K"));
+        }
+    }			 
+
+    public class T1Filter implements java.io.FilenameFilter{
+        public boolean accept(File dir,String name) {
+            return(name.endsWith(".ps") ||
+                   name.endsWith(".PS") ||
+                   name.endsWith(".pfb") ||
+                   name.endsWith(".PFB") ||
+                   name.endsWith(".pfa") ||
+                   name.endsWith(".PFA"));
+        }
+    }
+
+    protected void getInstalledFallbackFonts(String javaLib) {
+        String fallbackDirName = javaLib + File.separator +
+            "fonts" + File.separator + "fallback";
+
+        File fallbackDir = new File(fallbackDirName);
+        if (fallbackDir.exists() && fallbackDir.isDirectory()) {
+            String[] ttfs = fallbackDir.list(new TTFilter());
+            String[] t1s = fallbackDir.list(new T1Filter());
+            int numTTFs = (ttfs == null) ? 0 : ttfs.length;
+            int numT1s = (t1s == null) ? 0 : t1s.length;
+            int len = numTTFs + numT1s;
+            if (numTTFs + numT1s == 0) {
+                return;
+            }
+            installedFallbackFontFiles = new String[len];
+            for (int i=0; i<numTTFs; i++) {
+                installedFallbackFontFiles[i] =
+                    fallbackDir + File.separator + ttfs[i];
+            }
+            for (int i=0; i<numT1s; i++) {
+                installedFallbackFontFiles[i+numTTFs] =
+                    fallbackDir + File.separator + t1s[i];
+            }
+            System.err.println("environment.registerFontsInDir(fallbackDirName);");
+        }
+    }
+
+    private File findImpl(String fname) {
+        File f = new File(fname + ".properties");
+        if (f.canRead()) {
+            isProperties = true;
+            return f;
+        }
+        f = new File(fname + ".bfc");
+        if (f.canRead()) {
+            isProperties = false;
+            return f;
+        }
+        return null;
+    }
+
+    private File findFontConfigFile(String javaLib) {
+        String baseName = javaLib + File.separator + "fontconfig";
+        File configFile;
+        if (osVersion != null && osName != null) {
+            configFile = findImpl(baseName + "." + osName + "." + osVersion);
+            if (configFile != null) {
+                return configFile;
+            }
+        }
+        if (osName != null) {
+            configFile = findImpl(baseName + "." + osName);
+            if (configFile != null) {
+                return configFile;
+            }
+        }
+        if (osVersion != null) {
+            configFile = findImpl(baseName + "." + osVersion);
+            if (configFile != null) {
+                return configFile;
+            }
+        }
+        foundOsSpecificFile = false;
+
+        configFile = findImpl(baseName);
+        if (configFile != null) {
+            return configFile;
+        }
+        return null;
+    }
+
+    /* Initialize the internal data tables from binary format font
+     * configuration file.
+     */
+    public static void loadBinary(InputStream inStream) throws IOException {
+        DataInputStream in = new DataInputStream(inStream);
+        head = readShortTable(in, HEAD_LENGTH);
+        int[] tableSizes = new int[INDEX_TABLEEND];
+        for (int i = 0; i < INDEX_TABLEEND; i++) {
+            tableSizes[i] = head[i + 1] - head[i];
+        }
+        table_scriptIDs       = readShortTable(in, tableSizes[INDEX_scriptIDs]);
+        table_scriptFonts     = readShortTable(in, tableSizes[INDEX_scriptFonts]);
+        table_elcIDs          = readShortTable(in, tableSizes[INDEX_elcIDs]);
+        table_sequences        = readShortTable(in, tableSizes[INDEX_sequences]);
+        table_fontfileNameIDs = readShortTable(in, tableSizes[INDEX_fontfileNameIDs]);
+        table_componentFontNameIDs = readShortTable(in, tableSizes[INDEX_componentFontNameIDs]);
+        table_filenames       = readShortTable(in, tableSizes[INDEX_filenames]);
+        table_awtfontpaths    = readShortTable(in, tableSizes[INDEX_awtfontpaths]);
+        table_exclusions      = readShortTable(in, tableSizes[INDEX_exclusions]);
+        table_proportionals   = readShortTable(in, tableSizes[INDEX_proportionals]);
+        table_scriptFontsMotif   = readShortTable(in, tableSizes[INDEX_scriptFontsMotif]);
+        table_alphabeticSuffix   = readShortTable(in, tableSizes[INDEX_alphabeticSuffix]);
+        table_stringIDs       = readShortTable(in, tableSizes[INDEX_stringIDs]);
+
+        //StringTable cache
+        stringCache = new String[table_stringIDs.length + 1];
+
+        int len = tableSizes[INDEX_stringTable];
+        byte[] bb = new byte[len * 2];
+        table_stringTable = new char[len];
+        in.read(bb);
+        int i = 0, j = 0;
+        while (i < len) {
+           table_stringTable[i++] = (char)(bb[j++] << 8 | (bb[j++] & 0xff));
+        }
+        if (verbose) {
+            dump();
+        }
+    }
+
+    /* Generate a binary format font configuration from internal data
+     * tables.
+     */
+    public static void saveBinary(OutputStream out) throws IOException {
+        DataOutputStream dataOut = new DataOutputStream(out);
+        writeShortTable(dataOut, head);
+        writeShortTable(dataOut, table_scriptIDs);
+        writeShortTable(dataOut, table_scriptFonts);
+        writeShortTable(dataOut, table_elcIDs);
+        writeShortTable(dataOut, table_sequences);
+        writeShortTable(dataOut, table_fontfileNameIDs);
+        writeShortTable(dataOut, table_componentFontNameIDs);
+        writeShortTable(dataOut, table_filenames);
+        writeShortTable(dataOut, table_awtfontpaths);
+        writeShortTable(dataOut, table_exclusions);
+        writeShortTable(dataOut, table_proportionals);
+        writeShortTable(dataOut, table_scriptFontsMotif);
+        writeShortTable(dataOut, table_alphabeticSuffix);
+        writeShortTable(dataOut, table_stringIDs);
+        //stringTable
+        dataOut.writeChars(new String(table_stringTable));
+        out.close();
+        if (verbose) {
+            dump();
+        }
+        sanityCheck();
+    }
+
+    //private static boolean loadingProperties;
+    private static short stringIDNum;
+    private static short[] stringIDs;
+    private static StringBuffer stringTable;
+
+    public static void loadProperties(InputStream in) throws IOException {
+        //loadingProperties = true;
+        //StringID starts from "1", "0" is reserved for "not defined"
+        stringIDNum = 1;
+        stringIDs = new short[1000];
+        stringTable = new StringBuffer(4096);
+
+        if (verbose && logger == null) {
+            logger = Logger.getLogger("sun.awt.FontConfiguration");
+        }
+        new PropertiesHandler().load(in);
+
+        //loadingProperties = false;
+        stringIDs = null;
+        stringTable = null;
+    }
+
+
+    /////////////////////////////////////////////////////////////////////
+    // methods for initializing the FontConfig                         //
+    /////////////////////////////////////////////////////////////////////
+
+    /**
+     *  set initLocale, initEncoding and initELC for this FontConfig object
+     *  currently we just simply use the startup locale and encoding
+     */
+    private void initFontConfig() {
+        initLocale = startupLocale;
+        initEncoding = encoding;
+        if (preferLocaleFonts && !willReorderForStartupLocale()) {
+            preferLocaleFonts = false;
+        }
+        initELC = getInitELC();
+        initAllComponentFonts();
+    }
+
+    //"ELC" stands for "Encoding.Language.Country". This method returns
+    //the ID of the matched elc setting of "initLocale" in elcIDs table.
+    //If no match is found, it returns the default ID, which is
+    //"NULL.NULL.NULL" in elcIDs table.
+    private short getInitELC() {
+        if (initELC != -1) {
+            return initELC;
+        }
+        HashMap  elcIDs = new HashMap();
+        for (int i = 0; i < table_elcIDs.length; i++) {
+            elcIDs.put(getString(table_elcIDs[i]), new Short((short)i));
+        }
+        String language = initLocale.getLanguage();
+        String country = initLocale.getCountry();
+        String elc;
+        if (elcIDs.containsKey(elc=initEncoding + "." + language + "." + country)
+            || elcIDs.containsKey(elc=initEncoding + "." + language)
+            || elcIDs.containsKey(elc=initEncoding)) {
+            initELC = ((Number)elcIDs.get(elc)).shortValue();
+        } else {
+            initELC = ((Number)elcIDs.get("NULL.NULL.NULL")).shortValue();
+        }
+        int i = 0;
+        while (i < table_alphabeticSuffix.length) {
+            if (initELC == table_alphabeticSuffix[i]) {
+                alphabeticSuffix = getString(table_alphabeticSuffix[i + 1]);
+                return initELC;
+            }
+            i += 2;
+        }
+        return initELC;
+    }
+
+    public static boolean verbose;
+    private short    initELC = -1;
+    private Locale   initLocale;
+    private String   initEncoding;
+    private String   alphabeticSuffix;
+
+    private short[][][] compFontNameIDs = new short[NUM_FONTS][NUM_STYLES][];
+    private int[][][] compExclusions = new int[NUM_FONTS][][];
+    private int[] compCoreNum = new int[NUM_FONTS];
+
+    private Set coreFontNameIDs = new HashSet();
+    private Set fallbackFontNameIDs = new HashSet();
+
+    private void initAllComponentFonts() {
+        short[] fallbackScripts = getFallbackScripts();
+        for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
+            short[] coreScripts = getCoreScripts(fontIndex);
+            compCoreNum[fontIndex] = coreScripts.length;
+            /*
+            System.out.println("coreScriptID=" + table_sequences[initELC * 5 + fontIndex]);
+            for (int i = 0; i < coreScripts.length; i++) {
+            System.out.println("  " + i + " :" + getString(table_scriptIDs[coreScripts[i]]));
+            }
+            */
+            //init exclusionRanges
+            int[][] exclusions = new int[coreScripts.length][];
+            for (int i = 0; i < coreScripts.length; i++) {
+                exclusions[i] = getExclusionRanges(coreScripts[i]);
+            }
+            compExclusions[fontIndex] = exclusions;
+            //init componentFontNames
+            for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {
+                int index;
+                short[] nameIDs = new short[coreScripts.length + fallbackScripts.length];
+                //core
+                for (index = 0; index < coreScripts.length; index++) {
+                    nameIDs[index] = getComponentFontID(coreScripts[index],
+                                               fontIndex, styleIndex);
+//                    if (preferLocaleFonts && localeMap != null &&
+  //                      sun.font.FontManager.usingAlternateFontforJALocales()) {
+    //                    nameIDs[index] = remapLocaleMap(fontIndex, styleIndex,
+      //                                                  coreScripts[index], nameIDs[index]);
+        //            }
+                    if (preferPropFonts) {
+                        nameIDs[index] = remapProportional(fontIndex, nameIDs[index]);
+                    }
+                    //System.out.println("nameid=" + nameIDs[index]);
+                    coreFontNameIDs.add(new Short(nameIDs[index]));
+                }
+                //fallback
+                for (int i = 0; i < fallbackScripts.length; i++) {
+                    short id = getComponentFontID(fallbackScripts[i],
+                                               fontIndex, styleIndex);
+//                    if (preferLocaleFonts && localeMap != null &&
+  //                      sun.font.FontManager.usingAlternateFontforJALocales()) {
+    //                    id = remapLocaleMap(fontIndex, styleIndex, fallbackScripts[i], id);
+      //              }
+                    if (preferPropFonts) {
+                        id = remapProportional(fontIndex, id);
+                    }
+                    if (contains(nameIDs, id, index)) {
+                        continue;
+                    }
+                    /*
+                      System.out.println("fontIndex=" + fontIndex + ", styleIndex=" + styleIndex
+                           + ", fbIndex=" + i + ",fbS=" + fallbackScripts[i] + ", id=" + id);
+                    */
+                    fallbackFontNameIDs.add(new Short(id));
+                    nameIDs[index++] = id;
+                }
+                if (index < nameIDs.length) {
+                    short[] newNameIDs = new short[index];
+                    System.arraycopy(nameIDs, 0, newNameIDs, 0, index);
+                    nameIDs = newNameIDs;
+                }
+                compFontNameIDs[fontIndex][styleIndex] = nameIDs;
+            }
+        }
+   }
+
+   private short remapLocaleMap(int fontIndex, int styleIndex, short scriptID, short fontID) {
+        String scriptName = getString(table_scriptIDs[scriptID]);
+
+        String value = (String)localeMap.get(scriptName);
+        if (value == null) {
+            String fontName = fontNames[fontIndex];
+            String styleName = styleNames[styleIndex];
+            value = (String)localeMap.get(fontName + "." + styleName + "." + scriptName);
+        }
+        if (value == null) {
+            return fontID;
+        }
+
+        for (int i = 0; i < table_componentFontNameIDs.length; i++) {
+            String name = getString(table_componentFontNameIDs[i]);
+            if (value.equalsIgnoreCase(name)) {
+                fontID = (short)i;
+                break;
+            }
+        }
+        return fontID;
+    }
+
+    public static boolean hasMonoToPropMap() {
+        return table_proportionals != null && table_proportionals.length != 0;
+    }
+
+    private short remapProportional(int fontIndex, short id) {
+    if (preferPropFonts &&
+        table_proportionals.length != 0 &&
+        fontIndex != 2 &&         //"monospaced"
+        fontIndex != 4) {         //"dialoginput"
+            int i = 0;
+            while (i < table_proportionals.length) {
+                if (table_proportionals[i] == id) {
+                    return table_proportionals[i + 1];
+                }
+                i += 2;
+            }
+        }
+        return id;
+    }
+
+    /////////////////////////////////////////////////////////////////////
+    // Methods for handling font and style names                       //
+    /////////////////////////////////////////////////////////////////////
+    protected static final int NUM_FONTS = 5;
+    protected static final int NUM_STYLES = 4;
+    protected static final String[] fontNames
+            = {"serif", "sansserif", "monospaced", "dialog", "dialoginput"};
+    protected static final String[] publicFontNames
+            = {SERIF, SANS_SERIF, MONOSPACED, DIALOG,
+               DIALOG_INPUT};
+    protected static final String[] styleNames
+            = {"plain", "bold", "italic", "bolditalic"};
+
+    /**
+     * Checks whether the given font family name is a valid logical font name.
+     * The check is case insensitive.
+     */
+    public static boolean isLogicalFontFamilyName(String fontName) {
+        return isLogicalFontFamilyNameLC(fontName.toLowerCase(Locale.ENGLISH));
+    }
+
+    /**
+     * Checks whether the given font family name is a valid logical font name.
+     * The check is case sensitive.
+     */
+    public static boolean isLogicalFontFamilyNameLC(String fontName) {
+        for (int i = 0; i < fontNames.length; i++) {
+            if (fontName.equals(fontNames[i])) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Checks whether the given style name is a valid logical font style name.
+     */
+    private static boolean isLogicalFontStyleName(String styleName) {
+        for (int i = 0; i < styleNames.length; i++) {
+            if (styleName.equals(styleNames[i])) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Checks whether the given font face name is a valid logical font name.
+     * The check is case insensitive.
+     */
+    public static boolean isLogicalFontFaceName(String fontName) {
+        return isLogicalFontFaceNameLC(fontName.toLowerCase(Locale.ENGLISH));
+    }
+
+   /**
+    * Checks whether the given font face name is a valid logical font name.
+    * The check is case sensitive.
+    */
+    public static boolean isLogicalFontFaceNameLC(String fontName) {
+        int period = fontName.indexOf('.');
+        if (period >= 0) {
+            String familyName = fontName.substring(0, period);
+            String styleName = fontName.substring(period + 1);
+            return isLogicalFontFamilyName(familyName) &&
+                    isLogicalFontStyleName(styleName);
+        } else {
+            return isLogicalFontFamilyName(fontName);
+        }
+    }
+
+    protected static int getFontIndex(String fontName) {
+        return getArrayIndex(fontNames, fontName);
+    }
+
+    protected static int getStyleIndex(String styleName) {
+        return getArrayIndex(styleNames, styleName);
+    }
+
+    private static int getArrayIndex(String[] names, String name) {
+        for (int i = 0; i < names.length; i++) {
+            if (name.equals(names[i])) {
+                return i;
+            }
+        }
+        assert false;
+        return 0;
+    }
+
+    protected static int getStyleIndex(int style) {
+        switch (style) {
+            case Font.PLAIN:
+                return 0;
+            case Font.BOLD:
+                return 1;
+            case Font.ITALIC:
+                return 2;
+            case Font.BOLD | Font.ITALIC:
+                return 3;
+            default:
+                return 0;
+        }
+    }
+
+    protected static String getFontName(int fontIndex) {
+        return fontNames[fontIndex];
+    }
+
+    protected static String getStyleName(int styleIndex) {
+        return styleNames[styleIndex];
+    }
+
+    /**
+     * Returns the font face name for the given logical font
+     * family name and style.
+     * The style argument is interpreted as in java.awt.Font.Font.
+     */
+    public static String getLogicalFontFaceName(String familyName, int style) {
+        assert isLogicalFontFamilyName(familyName);
+        return familyName.toLowerCase(Locale.ENGLISH) + "." + getStyleString(style);
+    }
+
+    /**
+     * Returns the string typically used in properties files
+     * for the given style.
+     * The style argument is interpreted as in java.awt.Font.Font.
+     */
+    public static String getStyleString(int style) {
+        return getStyleName(getStyleIndex(style));
+    }
+
+    /**
+     * Returns a fallback name for the given font name. For a few known
+     * font names, matching logical font names are returned. For all
+     * other font names, defaultFallback is returned.
+     * defaultFallback differs between AWT and 2D.
+     */
+    public abstract String getFallbackFamilyName(String fontName, String defaultFallback);
+
+    /**
+     * Returns the 1.1 equivalent for some old 1.0 font family names for
+     * which we need to maintain compatibility in some configurations.
+     * Returns null for other font names.
+     */
+    protected String getCompatibilityFamilyName(String fontName) {
+        fontName = fontName.toLowerCase(Locale.ENGLISH);
+        if (fontName.equals("timesroman")) {
+            return "serif";
+        } else if (fontName.equals("helvetica")) {
+            return "sansserif";
+        } else if (fontName.equals("courier")) {
+            return "monospaced";
+        }
+        return null;
+    }
+
+    protected static String[] installedFallbackFontFiles = null;
+
+    /**
+     * Maps a file name given in the font configuration file
+     * to a format appropriate for the platform.
+     */
+    protected String mapFileName(String fileName) {
+        return fileName;
+    }
+
+    //////////////////////////////////////////////////////////////////////
+    //  reordering                                                      //
+    //////////////////////////////////////////////////////////////////////
+
+    /* Mappings from file encoding to font config name for font supporting
+     * the corresponding language. This is filled in by initReorderMap()
+     */
+    protected HashMap reorderMap = null;
+
+    /* Platform-specific mappings */
+    protected abstract void initReorderMap();
+
+    /* Move item at index "src" to "dst", shuffling all values in
+     * between down
+     */
+    private void shuffle(String[] seq, int src, int dst) {
+        if (dst >= src) {
+            return;
+        }
+        String tmp = seq[src];
+        for (int i=src; i>dst; i--) {
+            seq[i] = seq[i-1];
+        }
+        seq[dst] = tmp;
+    }
+
+    /* Called to determine if there's a re-order sequence for this locale/
+     * encoding. If there's none then the caller can "bail" and avoid
+     * unnecessary work
+     */
+    public static boolean willReorderForStartupLocale() {
+        return getReorderSequence() != null;
+    }
+
+    private static Object getReorderSequence() {
+        if (fontConfig.reorderMap == null) {
+             fontConfig.initReorderMap();
+        }
+        HashMap reorderMap = fontConfig.reorderMap;
+
+        /* Find the most specific mapping */
+        String language = startupLocale.getLanguage();
+        String country = startupLocale.getCountry();
+        Object val = reorderMap.get(encoding + "." + language + "." + country);
+        if (val == null) {
+            val = reorderMap.get(encoding + "." + language);
+        }
+        if (val == null) {
+            val = reorderMap.get(encoding);
+        }
+        return val;
+    }
+
+    /* This method reorders the sequence such that the matches for the
+     * file encoding are moved ahead of other elements.
+     * If an encoding uses more than one font, they are all moved up.
+     */
+     private void reorderSequenceForLocale(String[] seq) {
+        Object val =  getReorderSequence();
+        if (val instanceof String) {
+            for (int i=0; i< seq.length; i++) {
+                if (seq[i].equals(val)) {
+                    shuffle(seq, i, 0);
+                    return;
+                }
+            }
+        } else if (val instanceof String[]) {
+            String[] fontLangs = (String[])val;
+            for (int l=0; l<fontLangs.length;l++) {
+                for (int i=0; i<seq.length;i++) {
+                    if (seq[i].equals(fontLangs[l])) {
+                        shuffle(seq, i, l);
+                    }
+                }
+            }
+        }
+    }
+
+    private static Vector splitSequence(String sequence) {
+        //String.split would be more convenient, but incurs big performance penalty
+        Vector parts = new Vector();
+        int start = 0;
+        int end;
+        while ((end = sequence.indexOf(',', start)) >= 0) {
+            parts.add(sequence.substring(start, end));
+            start = end + 1;
+        }
+        if (sequence.length() > start) {
+            parts.add(sequence.substring(start, sequence.length()));
+        }
+        return parts;
+    }
+
+    protected String[] split(String sequence) {
+        Vector v = splitSequence(sequence);
+        return (String[])v.toArray(new String[0]);
+    }
+
+    ////////////////////////////////////////////////////////////////////////
+    // Methods for extracting information from the fontconfig data for AWT//
+    ////////////////////////////////////////////////////////////////////////
+    private Hashtable charsetRegistry = new Hashtable(5);
+
+    /**
+     * Returns FontDescriptors describing the physical fonts used for the
+     * given logical font name and style. The font name is interpreted
+     * in a case insensitive way.
+     * The style argument is interpreted as in java.awt.Font.Font.
+     */
+    public FontDescriptor[] getFontDescriptors(String fontName, int style) {
+        assert isLogicalFontFamilyName(fontName);
+        fontName = fontName.toLowerCase(Locale.ENGLISH);
+        int fontIndex = getFontIndex(fontName);
+        int styleIndex = getStyleIndex(style);
+        return getFontDescriptors(fontIndex, styleIndex);
+    }
+    private FontDescriptor[][][] fontDescriptors =
+        new FontDescriptor[NUM_FONTS][NUM_STYLES][];
+
+    private FontDescriptor[] getFontDescriptors(int fontIndex, int styleIndex) {
+        FontDescriptor[] descriptors = fontDescriptors[fontIndex][styleIndex];
+        if (descriptors == null) {
+            descriptors = buildFontDescriptors(fontIndex, styleIndex);
+            fontDescriptors[fontIndex][styleIndex] = descriptors;
+        }
+        return descriptors;
+    }
+
+    private FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
+        String fontName = fontNames[fontIndex];
+        String styleName = styleNames[styleIndex];
+
+        short[] scriptIDs = getCoreScripts(fontIndex);
+        short[] nameIDs = compFontNameIDs[fontIndex][styleIndex];
+        String[] sequence = new String[scriptIDs.length];
+        String[] names = new String[scriptIDs.length];
+        for (int i = 0; i < sequence.length; i++) {
+            names[i] = getComponentFontName(nameIDs[i]);
+            sequence[i] = getScriptName(scriptIDs[i]);
+            if (alphabeticSuffix != null && "alphabetic".equals(sequence[i])) {
+                sequence[i] = sequence[i] + "/" + alphabeticSuffix;
+            }
+        }
+        int[][] fontExclusionRanges = compExclusions[fontIndex];
+
+        FontDescriptor[] descriptors = new FontDescriptor[names.length];
+
+        for (int i = 0; i < names.length; i++) {
+            String awtFontName;
+            String encoding;
+
+            awtFontName = makeAWTFontName(names[i], sequence[i]);
+
+            // look up character encoding
+            encoding = getEncoding(names[i], sequence[i]);
+            if (encoding == null) {
+                encoding = "default";
+            }
+            CharsetEncoder enc
+                    = getFontCharsetEncoder(encoding.trim(), awtFontName);
+
+            // we already have the exclusion ranges
+            int[] exclusionRanges = fontExclusionRanges[i];
+
+            // create descriptor
+            System.err.println("enc ignored and used null");
+            descriptors[i] = new FontDescriptor(awtFontName, null, exclusionRanges);
+        }
+        return descriptors;
+    }
+
+    /**
+     * Returns the AWT font name for the given platform font name and
+     * character subset.
+     */
+    protected String makeAWTFontName(String platformFontName,
+            String characterSubsetName) {
+        return platformFontName;
+    }
+
+    /**
+     * Returns the java.io name of the platform character encoding for the
+     * given AWT font name and character subset. May return "default"
+     * to indicate that getDefaultFontCharset should be called to obtain
+     * a charset encoder.
+     */
+    protected abstract String getEncoding(String awtFontName,
+            String characterSubsetName);
+
+    private CharsetEncoder getFontCharsetEncoder(final String charsetName,
+            String fontName) {
+
+        Charset fc = null;
+        if (charsetName.equals("default")) {
+            fc = (Charset) charsetRegistry.get(fontName);
+        } else {
+            fc = (Charset) charsetRegistry.get(charsetName);
+        }
+        if (fc != null) {
+            return fc.newEncoder();
+        }
+
+        if (!charsetName.startsWith("sun.awt.") && !charsetName.equals("default")) {
+            fc = Charset.forName(charsetName);
+        } else {
+            Class fcc = (Class) AccessController.doPrivileged(new PrivilegedAction() {
+                    public Object run() {
+                        try {
+                            return Class.forName(charsetName, true,
+                                                 Thread.currentThread().getContextClassLoader());
+                        } catch (ClassNotFoundException e) {
+                        }
+                        return null;
+                    }
+                });
+
+            if (fcc != null) {
+                try {
+                    fc = (Charset) fcc.newInstance();
+                } catch (Exception e) {
+                }
+            }
+        }
+        if (fc == null) {
+            fc = getDefaultFontCharset(fontName);
+        }
+
+        if (charsetName.equals("default")){
+            charsetRegistry.put(fontName, fc);
+        } else {
+            charsetRegistry.put(charsetName, fc);
+        }
+        return fc.newEncoder();
+    }
+
+    protected abstract Charset getDefaultFontCharset(
+            String fontName);
+
+    /* This retrieves the platform font directories (path) calculated
+     * by setAWTFontPathSequence(String[]). The default implementation
+     * returns null, its expected that X11 platforms may return
+     * non-null.
+     */
+    public HashSet getAWTFontPathSet() {
+        return null;
+    }
+
+    ////////////////////////////////////////////////////////////////////////
+    // methods for extracting information from the fontconfig data for 2D //
+    ////////////////////////////////////////////////////////////////////////
+
+    /**
+     * Returns an array of composite font descriptors for all logical font
+     * faces.
+     * If the font configuration file doesn't specify Lucida Sans Regular
+     * or the given fallback font as component fonts, they are added here.
+     */
+    public CompositeFontDescriptor[] get2DCompositeFontInfo() {
+        CompositeFontDescriptor[] result =
+                new CompositeFontDescriptor[NUM_FONTS * NUM_STYLES];
+        String defaultFontFile = "environment.getDefaultFontFile()";
+        String defaultFontFaceName = "environment.getDefaultFontFaceName()";
+
+        for (int fontIndex = 0; fontIndex < NUM_FONTS; fontIndex++) {
+            String fontName = publicFontNames[fontIndex];
+
+            // determine exclusion ranges for font
+            // AWT uses separate exclusion range array per component font.
+            // 2D packs all range boundaries into one array.
+            // Both use separate entries for lower and upper boundary.
+            int[][] exclusions = compExclusions[fontIndex];
+            int numExclusionRanges = 0;
+            for (int i = 0; i < exclusions.length; i++) {
+                numExclusionRanges += exclusions[i].length;
+            }
+            int[] exclusionRanges = new int[numExclusionRanges];
+            int[] exclusionRangeLimits = new int[exclusions.length];
+            int exclusionRangeIndex = 0;
+            int exclusionRangeLimitIndex = 0;
+            for (int i = 0; i < exclusions.length; i++) {
+                int[] componentRanges = exclusions[i];
+                for (int j = 0; j < componentRanges.length; ) {
+                    int value = componentRanges[j];
+                    exclusionRanges[exclusionRangeIndex++] = componentRanges[j++];
+                    exclusionRanges[exclusionRangeIndex++] = componentRanges[j++];
+                }
+                exclusionRangeLimits[i] = exclusionRangeIndex;
+            }
+            // other info is per style
+            for (int styleIndex = 0; styleIndex < NUM_STYLES; styleIndex++) {
+                int maxComponentFontCount = compFontNameIDs[fontIndex][styleIndex].length;
+                boolean sawDefaultFontFile = false;
+                // fall back fonts listed in the lib/fonts/fallback directory
+                if (installedFallbackFontFiles != null) {
+                    maxComponentFontCount += installedFallbackFontFiles.length;
+                }
+                String faceName = fontName + "." + styleNames[styleIndex];
+
+                // determine face names and file names of component fonts
+                String[] componentFaceNames = new String[maxComponentFontCount];
+                String[] componentFileNames = new String[maxComponentFontCount];
+
+                int index;
+                for (index = 0; index < compFontNameIDs[fontIndex][styleIndex].length; index++) {
+                    short fontNameID = compFontNameIDs[fontIndex][styleIndex][index];
+                    short fileNameID = getComponentFileID(fontNameID);
+                    componentFaceNames[index] = getFaceNameFromComponentFontName(getComponentFontName(fontNameID));
+                    componentFileNames[index] = mapFileName(getComponentFileName(fileNameID));
+                    if (componentFileNames[index] == null ||
+                        needToSearchForFile(componentFileNames[index])) {
+                        componentFileNames[index] = getFileNameFromComponentFontName(getComponentFontName(fontNameID));
+                    }
+                    if (!sawDefaultFontFile &&
+                        defaultFontFile.equals(componentFileNames[index])) {
+                        sawDefaultFontFile = true;
+                    }
+                    /*
+                    System.out.println(publicFontNames[fontIndex] + "." + styleNames[styleIndex] + "."
+                        + getString(table_scriptIDs[coreScripts[index]]) + "=" + componentFileNames[index]);
+                    */
+                }
+
+                //"Lucida Sans Regular" is not in the list, we add it here
+                if (!sawDefaultFontFile) {
+                    int len = 0;
+                    if (installedFallbackFontFiles != null) {
+                        len = installedFallbackFontFiles.length;
+                    }
+                    if (index + len == maxComponentFontCount) {
+                        String[] newComponentFaceNames = new String[maxComponentFontCount + 1];
+                        System.arraycopy(componentFaceNames, 0, newComponentFaceNames, 0, index);
+                        componentFaceNames = newComponentFaceNames;
+                        String[] newComponentFileNames = new String[maxComponentFontCount + 1];
+                        System.arraycopy(componentFileNames, 0, newComponentFileNames, 0, index);
+                        componentFileNames = newComponentFileNames;
+                    }
+                    componentFaceNames[index] = defaultFontFaceName;
+                    componentFileNames[index] = defaultFontFile;
+                    index++;
+                }
+
+                if (installedFallbackFontFiles != null) {
+                    for (int ifb=0; ifb<installedFallbackFontFiles.length; ifb++) {
+                        componentFaceNames[index] = null;
+                        componentFileNames[index] = installedFallbackFontFiles[ifb];
+                        index++;
+                    }
+                }
+
+                if (index < maxComponentFontCount) {
+                    String[] newComponentFaceNames = new String[index];
+                    System.arraycopy(componentFaceNames, 0, newComponentFaceNames, 0, index);
+                    componentFaceNames = newComponentFaceNames;
+                    String[] newComponentFileNames = new String[index];
+                    System.arraycopy(componentFileNames, 0, newComponentFileNames, 0, index);
+                    componentFileNames = newComponentFileNames;
+                }
+                // exclusion range limit array length must match component face name
+                // array length - native code relies on this
+
+                int[] clippedExclusionRangeLimits = exclusionRangeLimits;
+                if (index != clippedExclusionRangeLimits.length) {
+                    int len = exclusionRangeLimits.length;
+                    clippedExclusionRangeLimits = new int[index];
+                    System.arraycopy(exclusionRangeLimits, 0, clippedExclusionRangeLimits, 0, len);
+                    //padding for various fallback fonts
+                    for (int i = len; i < index; i++) {
+                        clippedExclusionRangeLimits[i] = exclusionRanges.length;
+                    }
+                }
+                /*
+                System.out.println(faceName + ":");
+                for (int i = 0; i < componentFileNames.length; i++) {
+                    System.out.println("    " + componentFaceNames[i]
+                         + "  -> " + componentFileNames[i]);
+                }
+                */
+                result[fontIndex * NUM_STYLES + styleIndex]
+                        = new CompositeFontDescriptor(
+                            faceName,
+                            compCoreNum[fontIndex],
+                            componentFaceNames,
+                            componentFileNames,
+                            exclusionRanges,
+                            clippedExclusionRangeLimits);
+            }
+        }
+        return result;
+    }
+
+    protected abstract String getFaceNameFromComponentFontName(String componentFontName);
+    protected abstract String getFileNameFromComponentFontName(String componentFontName);
+
+    /*
+    public class 2dFont {
+        public String platformName;
+        public String fontfileName;
+    }
+    private 2dFont [] componentFonts = null;
+    */
+
+    /* Used on Linux to test if a file referenced in a font configuration
+     * file exists in the location that is expected. If it does, no need
+     * to search for it. If it doesn't then unless its a fallback font,
+     * return that expensive code should be invoked to search for the font.
+     */
+    HashMap existsMap;
+    public boolean needToSearchForFile(String fileName) {
+        if (true) { // !environment.isLinux) {
+            return false;
+        } else if (existsMap == null) {
+           existsMap = new HashMap();
+        }
+        Boolean exists = (Boolean)existsMap.get(fileName);
+        if (exists == null) {
+            /* call getNumberCoreFonts() to ensure these are initialised, and
+             * if this file isn't for a core component, ie, is a for a fallback
+             * font which very typically isn't available, then can't afford
+             * to take the start-up penalty to search for it.
+             */
+            getNumberCoreFonts();
+            if (!coreFontFileNames.contains(fileName)) {
+                exists = Boolean.TRUE;
+            } else {
+                exists = Boolean.valueOf((new File(fileName)).exists());
+                existsMap.put(fileName, exists);
+                if (exists == Boolean.FALSE) {
+                    logger.warning("Couldn't locate font file " + fileName);
+                }
+            }
+        }
+        return exists == Boolean.FALSE;
+    }
+
+    private int numCoreFonts = -1;
+    private String[] componentFonts = null;
+    HashMap  filenamesMap = new HashMap();
+    HashSet  coreFontFileNames = new HashSet();
+
+    /* Return the number of core fonts. Note this isn't thread safe but
+     * a calling thread can call this and getPlatformFontNames() in either
+     * order.
+     */
+    public int getNumberCoreFonts() {
+        if (numCoreFonts == -1) {
+            numCoreFonts = coreFontNameIDs.size();
+            Short[] emptyShortArray = new Short[0];
+            Short[] core = (Short[])coreFontNameIDs.toArray(emptyShortArray);
+            Short[] fallback = (Short[])fallbackFontNameIDs.toArray(emptyShortArray);
+
+            int numFallbackFonts = 0;
+            int i;
+            for (i = 0; i < fallback.length; i++) {
+                if (coreFontNameIDs.contains(fallback[i])) {
+                    fallback[i] = null;
+                    continue;
+                }
+                numFallbackFonts++;
+            }
+            componentFonts = new String[numCoreFonts + numFallbackFonts];
+            String filename = null;
+            for (i = 0; i < core.length; i++) {
+                short fontid = ((Number)core[i]).shortValue();
+                short fileid = getComponentFileID(fontid);
+                componentFonts[i] = getComponentFontName(fontid);
+                String compFileName = getComponentFileName(fileid);
+                if (compFileName != null) {
+                    coreFontFileNames.add(compFileName);
+                }
+                filenamesMap.put(componentFonts[i], mapFileName(compFileName));
+            }
+            for (int j = 0; j < fallback.length; j++) {
+                if (fallback[j] != null) {
+                    short fontid = ((Number)fallback[j]).shortValue();
+                    short fileid = getComponentFileID(fontid);
+                    componentFonts[i] = getComponentFontName(fontid);
+                    filenamesMap.put(componentFonts[i],
+                                     mapFileName(getComponentFileName(fileid)));
+                    i++;
+                }
+            }
+        }
+        return numCoreFonts;
+    }
+
+    /* Return all platform font names used by this font configuration.
+     * The first getNumberCoreFonts() entries are guaranteed to be the
+     * core fonts - ie no fall back only fonts.
+     */
+    public String[] getPlatformFontNames() {
+        if (numCoreFonts == -1) {
+            getNumberCoreFonts();
+        }
+        return componentFonts;
+    }
+
+    /**
+     * Returns a file name for the physical font represented by this platform font name,
+     * if the font configuration has such information available, or null if the
+     * information is unavailable. The file name returned is just a hint; a null return
+     * value doesn't necessarily mean that the font is unavailable, nor does a non-null
+     * return value guarantee that the file exists and contains the physical font.
+     * The file name can be an absolute or a relative path name.
+     */
+    public String getFileNameFromPlatformName(String platformName) {
+        // get2DCompositeFontInfo
+        //     ->  getFileNameFromComponentfontName()  (W/M)
+        //       ->   getFileNameFromPlatformName()
+        // it's a waste of time on Win32, but I have to give X11 a chance to
+        // call getFileNameFromXLFD()
+        return (String)filenamesMap.get(platformName);
+    }
+
+    /**
+     * Returns a configuration specific path to be appended to the font
+     * search path.
+     */
+    public String getExtraFontPath() {
+        return getString(head[INDEX_appendedfontpath]);
+    }
+
+    public String getVersion() {
+        return getString(head[INDEX_version]);
+    }
+
+    /* subclass support */
+    protected static FontConfiguration getFontConfiguration() {
+        return fontConfig;
+    }
+
+    protected void setFontConfiguration() {
+        fontConfig = this;      /* static initialization */
+    }
+
+    //////////////////////////////////////////////////////////////////////
+    // FontConfig data tables and the index constants in binary file    //
+    //////////////////////////////////////////////////////////////////////
+    /* The binary font configuration file begins with a short[] "head", which
+     * contains the offsets to the starts of the individual data table which
+     * immediately follow. Teh current implemention includes the tables shown
+     * below.
+     *
+     * (00) table_scriptIDs    :stringIDs of all defined CharacterSubsetNames
+     * (01) table_scriptFonts  :scriptID x fontIndex x styleIndex->
+     *                          PlatformFontNameID mapping. Each scriptID might
+     *                          have 1 or 20 entries depends on if it is defined
+     *                          via a "allfonts.CharacterSubsetname" or a list of
+     *                          "LogicalFontName.StyleName.CharacterSubsetName"
+     *                          entries, positive entry means it's a "allfonts"
+     *                          entry, a negative value means this is a offset to
+     *                          a NUM_FONTS x NUM_STYLES subtable.
+     * (02) table_elcIDs       :stringIDs of all defined ELC names, string
+     *                          "NULL.NULL.NULL" is used for "default"
+     * (03) table_sequences    :elcID x logicalFont -> scriptIDs table defined
+     *                          by "sequence.allfonts/LogicalFontName.ELC" in
+     *                          font configuration file, each "elcID" has
+     *                          NUM_FONTS (5) entries in this table.
+     * (04) table_fontfileNameIDs
+     *                         :stringIDs of all defined font file names
+     * (05) table_componentFontNameIDs
+     *                         :stringIDs of all defined PlatformFontNames
+     * (06) table_filenames    :platformFontNamesID->fontfileNameID mapping
+     *                          table, the index is the platformFontNamesID.
+     * (07) table_awtfontpaths :CharacterSubsetNames->awtfontpaths mapping table,
+     *                          the index is the CharacterSubsetName's stringID
+     *                          and content is the stringID of awtfontpath.
+     * (08) table_exclusions   :scriptID -> exclusionRanges mapping table,
+     *                          the index is the scriptID and the content is
+                                a id of an exclusionRanges int[].
+     * (09) table_proportionals:list of pairs of PlatformFontNameIDs, stores
+     *                          the replacement info defined by "proportional"
+     *                          keyword.
+     * (10) table_scriptFontsMotif
+     *                         :same as (01) except this table stores the
+     *                          info defined with ".motif" keyword
+     * (11) table_alphabeticSuffix
+     *                         :elcID -> stringID of alphabetic/XXXX entries
+     * (12) table_stringIDs    :The index of this table is the string ID, the
+     *                          content is the "start index" of this string in
+     *                          stringTable, use the start index of next entry
+     *                          as the "end index".
+     * (13) table_stringTable  :The real storage of all character strings defined
+     *                          /used this font configuration, need a pair of
+     *                          "start" and "end" indices to access.
+     * (14) reserved
+     * (15) table_fallbackScripts
+     *                         :stringIDs of fallback CharacterSubsetnames, stored
+     *                          in the order of they are defined in sequence.fallback.
+     * (16) table_appendedfontpath
+     *                         :stringtID of the "appendedfontpath" defined.
+     * (17) table_version   :stringID of the version number of this fontconfig file.
+     */
+    private static final int HEAD_LENGTH = 20;
+    private static final int INDEX_scriptIDs = 0;
+    private static final int INDEX_scriptFonts = 1;
+    private static final int INDEX_elcIDs = 2;
+    private static final int INDEX_sequences = 3;
+    private static final int INDEX_fontfileNameIDs = 4;
+    private static final int INDEX_componentFontNameIDs = 5;
+    private static final int INDEX_filenames = 6;
+    private static final int INDEX_awtfontpaths = 7;
+    private static final int INDEX_exclusions = 8;
+    private static final int INDEX_proportionals = 9;
+    private static final int INDEX_scriptFontsMotif = 10;
+    private static final int INDEX_alphabeticSuffix = 11;
+    private static final int INDEX_stringIDs = 12;
+    private static final int INDEX_stringTable = 13;
+    private static final int INDEX_TABLEEND = 14;
+    private static final int INDEX_fallbackScripts = 15;
+    private static final int INDEX_appendedfontpath = 16;
+    private static final int INDEX_version = 17;
+
+    private static short[] head;
+    private static short[] table_scriptIDs;
+    private static short[] table_scriptFonts;
+    private static short[] table_elcIDs;
+    private static short[] table_sequences;
+    private static short[] table_fontfileNameIDs;
+    private static short[] table_componentFontNameIDs;
+    private static short[] table_filenames;
+    protected static short[] table_awtfontpaths;
+    private static short[] table_exclusions;
+    private static short[] table_proportionals;
+    private static short[] table_scriptFontsMotif;
+    private static short[] table_alphabeticSuffix;
+    private static short[] table_stringIDs;
+    private static char[]  table_stringTable;
+
+    private static void sanityCheck() {
+        int errors = 0;
+
+        //This method will only be called during build time, do we
+        //need do PrivilegedAction?
+        String osName = (String)java.security.AccessController.doPrivileged(
+                            new java.security.PrivilegedAction() {
+            public Object run() {
+                return System.getProperty("os.name");
+            }
+        });
+
+        //componentFontNameID starts from "1"
+        for (int ii = 1; ii < table_filenames.length; ii++) {
+            if (table_filenames[ii] == -1) {
+                System.out.println("\n Warning: "
+                                   + "<filename."
+                                   + getString(table_componentFontNameIDs[ii])
+                                   + "> entry is missing!!!");
+                if (osName.indexOf("Linux") == -1) {
+                    errors++;
+                }
+            }
+        }
+        for (int ii = 0; ii < table_scriptIDs.length; ii++) {
+            short fid = table_scriptFonts[ii];
+            if (fid == 0) {
+                System.out.println("\n Error: <allfonts."
+                                   + getString(table_scriptIDs[ii])
+                                   + "> entry is missing!!!");
+                errors++;
+                continue;
+            } else if (fid < 0) {
+                fid = (short)-fid;
+                for (int iii = 0; iii < NUM_FONTS; iii++) {
+                    for (int iij = 0; iij < NUM_STYLES; iij++) {
+                        int jj = iii * NUM_STYLES + iij;
+                        short ffid = table_scriptFonts[fid + jj];
+                        if (ffid == 0) {
+                            System.out.println("\n Error: <"
+                                           + getFontName(iii) + "."
+                                           + getStyleName(iij) + "."
+                                           + getString(table_scriptIDs[ii])
+                                           + "> entry is missing!!!");
+                            errors++;
+                        }
+                    }
+                }
+            }
+        }
+        if ("SunOS".equals(osName)) {
+            for (int ii = 0; ii < table_awtfontpaths.length; ii++) {
+                if (table_awtfontpaths[ii] == 0) {
+                    String script = getString(table_scriptIDs[ii]);
+                    if (script.indexOf("lucida") != -1 ||
+                        script.indexOf("dingbats") != -1 ||
+                        script.indexOf("symbol") != -1) {
+                        continue;
+                    }
+                    System.out.println("\nError: "
+                                       + "<awtfontpath."
+                                       + script
+                                       + "> entry is missing!!!");
+                    errors++;
+                }
+            }
+        }
+        if (errors != 0) {
+            System.out.println("!!THERE ARE " + errors + " ERROR(S) IN "
+                               + "THE FONTCONFIG FILE, PLEASE CHECK ITS CONTENT!!\n");
+            System.exit(1);
+
+        }
+    }
+
+    //dump the fontconfig data tables
+    private static void dump() {
+        System.out.println("\n----Head Table------------");
+        for (int ii = 0; ii < HEAD_LENGTH; ii++) {
+            System.out.println("  " + ii + " : " + head[ii]);
+        }
+        System.out.println("\n----scriptIDs-------------");
+        printTable(table_scriptIDs, 0);
+        System.out.println("\n----scriptFonts----------------");
+        for (int ii = 0; ii < table_scriptIDs.length; ii++) {
+            short fid = table_scriptFonts[ii];
+            if (fid >= 0) {
+                System.out.println("  allfonts."
+                                   + getString(table_scriptIDs[ii])
+                                   + "="
+                                   + getString(table_componentFontNameIDs[fid]));
+            }
+        }
+        for (int ii = 0; ii < table_scriptIDs.length; ii++) {
+            short fid = table_scriptFonts[ii];
+            if (fid < 0) {
+                fid = (short)-fid;
+                for (int iii = 0; iii < NUM_FONTS; iii++) {
+                    for (int iij = 0; iij < NUM_STYLES; iij++) {
+                        int jj = iii * NUM_STYLES + iij;
+                        short ffid = table_scriptFonts[fid + jj];
+                        System.out.println("  "
+                                           + getFontName(iii) + "."
+                                           + getStyleName(iij) + "."
+                                           + getString(table_scriptIDs[ii])
+                                           + "="
+                                           + getString(table_componentFontNameIDs[ffid]));
+                    }
+                }
+
+            }
+        }
+        System.out.println("\n----elcIDs----------------");
+        printTable(table_elcIDs, 0);
+        System.out.println("\n----sequences-------------");
+        for (int ii = 0; ii< table_elcIDs.length; ii++) {
+            System.out.println("  " + ii + "/" + getString((short)table_elcIDs[ii]));
+            short[] ss = getShortArray(table_sequences[ii * NUM_FONTS + 0]);
+            for (int jj = 0; jj < ss.length; jj++) {
+                System.out.println("     " + getString((short)table_scriptIDs[ss[jj]]));
+            }
+        }
+        System.out.println("\n----fontfileNameIDs-------");
+        printTable(table_fontfileNameIDs, 0);
+
+        System.out.println("\n----componentFontNameIDs--");
+        printTable(table_componentFontNameIDs, 1);
+        System.out.println("\n----filenames-------------");
+        for (int ii = 0; ii < table_filenames.length; ii++) {
+            if (table_filenames[ii] == -1) {
+                System.out.println("  " + ii + " : null");
+            } else {
+                System.out.println("  " + ii + " : "
+                   + getString(table_fontfileNameIDs[table_filenames[ii]]));
+            }
+        }
+        System.out.println("\n----awtfontpaths---------");
+        for (int ii = 0; ii < table_awtfontpaths.length; ii++) {
+            System.out.println("  " + getString(table_scriptIDs[ii])
+                               + " : "
+                               + getString(table_awtfontpaths[ii]));
+        }
+        System.out.println("\n----proportionals--------");
+        for (int ii = 0; ii < table_proportionals.length; ii++) {
+            System.out.println("  "
+                   + getString((short)table_componentFontNameIDs[table_proportionals[ii++]])
+                   + " -> "
+                   + getString((short)table_componentFontNameIDs[table_proportionals[ii]]));
+        }
+        int i = 0;
+        System.out.println("\n----alphabeticSuffix----");
+        while (i < table_alphabeticSuffix.length) {
+          System.out.println("    " + getString(table_elcIDs[table_alphabeticSuffix[i++]])
+                             + " -> " + getString(table_alphabeticSuffix[i++]));
+        }
+        System.out.println("\n----String Table---------");
+        System.out.println("    stringID:    Num =" + table_stringIDs.length);
+        System.out.println("    stringTable: Size=" + table_stringTable.length * 2);
+
+        System.out.println("\n----fallbackScriptIDs---");
+        short[] fbsIDs = getShortArray(head[INDEX_fallbackScripts]);
+        for (int ii = 0; ii < fbsIDs.length; ii++) {
+          System.out.println("  " + getString(table_scriptIDs[fbsIDs[ii]]));
+        }
+        System.out.println("\n----appendedfontpath-----");
+        System.out.println("  " + getString(head[INDEX_appendedfontpath]));
+        System.out.println("\n----Version--------------");
+        System.out.println("  " + getString(head[INDEX_version]));
+    }
+
+
+    //////////////////////////////////////////////////////////////////////
+    // Data table access methods                                        //
+    //////////////////////////////////////////////////////////////////////
+
+    /* Return the fontID of the platformFontName defined in this font config
+     * by "LogicalFontName.StyleName.CharacterSubsetName" entry or
+     * "allfonts.CharacterSubsetName" entry in properties format fc file.
+     */
+    protected static short getComponentFontID(short scriptID, int fontIndex, int styleIndex) {
+        short fid = table_scriptFonts[scriptID];
+        //System.out.println("fid=" + fid + "/ scriptID=" + scriptID + ", fi=" + fontIndex + ", si=" + styleIndex);
+        if (fid >= 0) {
+            //"allfonts"
+            return fid;
+        } else {
+            return table_scriptFonts[-fid + fontIndex * NUM_STYLES + styleIndex];
+        }
+    }
+
+    /* Same as getCompoentFontID() except this method returns the fontID define by
+     * "xxxx.motif" entry.
+     */
+    protected static short getComponentFontIDMotif(short scriptID, int fontIndex, int styleIndex) {
+        if (table_scriptFontsMotif.length == 0) {
+            return 0;
+        }
+        short fid = table_scriptFontsMotif[scriptID];
+        if (fid >= 0) {
+            //"allfonts" > 0 or "not defined" == 0
+            return fid;
+        } else {
+            return table_scriptFontsMotif[-fid + fontIndex * NUM_STYLES + styleIndex];
+        }
+    }
+
+    private static int[] getExclusionRanges(short scriptID) {
+        short exID = table_exclusions[scriptID];
+        if (exID == 0) {
+            return EMPTY_INT_ARRAY;
+        } else {
+            char[] exChar = getString(exID).toCharArray();
+            int[] exInt = new int[exChar.length / 2];
+            int i = 0;
+            for (int j = 0; j < exInt.length; j++) {
+                exInt[j] = (exChar[i++] << 16) + (exChar[i++] & 0xffff);
+            }
+            return exInt;
+        }
+    }
+
+    private static boolean contains(short IDs[], short id, int limit) {
+        for (int i = 0; i < limit; i++) {
+            if (IDs[i] == id) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /* Return the PlatformFontName from its fontID*/
+    protected static String getComponentFontName(short id) {
+        if (id < 0) {
+            return null;
+        }
+        return getString(table_componentFontNameIDs[id]);
+    }
+
+    private static String getComponentFileName(short id) {
+        if (id < 0) {
+            return null;
+        }
+        return getString(table_fontfileNameIDs[id]);
+    }
+
+    //componentFontID -> componentFileID
+    private static short getComponentFileID(short nameID) {
+        return table_filenames[nameID];
+    }
+
+    private static String getScriptName(short scriptID) {
+        return getString(table_scriptIDs[scriptID]);
+    }
+
+   private HashMap reorderScripts;
+   protected short[] getCoreScripts(int fontIndex) {
+        short elc = getInitELC();
+        /*
+          System.out.println("getCoreScripts: elc=" + elc + ", fontIndex=" + fontIndex);
+          short[] ss = getShortArray(table_sequences[elc * NUM_FONTS + fontIndex]);
+          for (int i = 0; i < ss.length; i++) {
+              System.out.println("     " + getString((short)table_scriptIDs[ss[i]]));
+          }
+          */
+        short[] scripts = getShortArray(table_sequences[elc * NUM_FONTS + fontIndex]);
+        if (preferLocaleFonts) {
+            if (reorderScripts == null) {
+                reorderScripts = new HashMap();
+            }
+            String[] ss = new String[scripts.length];
+            for (int i = 0; i < ss.length; i++) {
+                ss[i] = getScriptName(scripts[i]);
+                reorderScripts.put(ss[i], new Short(scripts[i]));
+            }
+            reorderSequenceForLocale(ss);
+            for (int i = 0; i < ss.length; i++) {
+                scripts[i] = ((Number)reorderScripts.get(ss[i])).shortValue();
+            }
+        }
+         return scripts;
+    }
+
+    private static short[] getFallbackScripts() {
+        return getShortArray(head[INDEX_fallbackScripts]);
+    }
+
+    private static void printTable(short[] list, int start) {
+        for (int i = start; i < list.length; i++) {
+            System.out.println("  " + i + " : " + getString(list[i]));
+        }
+    }
+
+    private static short[] readShortTable(DataInputStream in, int len )
+        throws IOException {
+        if (len == 0) {
+            return EMPTY_SHORT_ARRAY;
+        }
+        short[] data = new short[len];
+        byte[] bb = new byte[len * 2];
+        in.read(bb);
+        int i = 0,j = 0;
+        while (i < len) {
+            data[i++] = (short)(bb[j++] << 8 | (bb[j++] & 0xff));
+        }
+        return data;
+    }
+
+    private static void writeShortTable(DataOutputStream out, short[] data)
+        throws IOException {
+        for (int i = 0; i < data.length; i++) {
+            out.writeShort(data[i]);
+        }
+    }
+
+    private static short[] toList(HashMap map) {
+        short[] list = new short[map.size()];
+        for (int i = 0; i < list.length; i++) {
+            list[i] = -1;
+        }
+        Iterator iterator = map.entrySet().iterator();
+        while (iterator.hasNext()) {
+            Entry entry = (Entry )iterator.next();
+            list[((Number)entry.getValue()).shortValue()] = getStringID((String)entry.getKey());
+        }
+        return list;
+    }
+
+    //runtime cache
+    private static String[] stringCache;
+    protected static String getString(short stringID) {
+        if (stringID == 0)
+            return null;
+        /*
+        if (loadingProperties) {
+            return stringTable.substring(stringIDs[stringID],
+                                         stringIDs[stringID+1]);
+        }
+        */
+        //sync if we want it to be MT-enabled
+        if (stringCache[stringID] == null){
+            stringCache[stringID] =
+              new String (table_stringTable,
+                          table_stringIDs[stringID],
+                          table_stringIDs[stringID+1] - table_stringIDs[stringID]);
+        }
+        return stringCache[stringID];
+    }
+
+    private static short[] getShortArray(short shortArrayID) {
+        String s = getString(shortArrayID);
+        char[] cc = s.toCharArray();
+        short[] ss = new short[cc.length];
+        for (int i = 0; i < cc.length; i++) {
+            ss[i] = (short)(cc[i] & 0xffff);
+        }
+        return ss;
+    }
+
+    private static short getStringID(String s) {
+        if (s == null) {
+            return (short)0;
+        }
+        short pos0 = (short)stringTable.length();
+        stringTable.append(s);
+        short pos1 = (short)stringTable.length();
+
+        stringIDs[stringIDNum] = pos0;
+        stringIDs[stringIDNum + 1] = pos1;
+        stringIDNum++;
+        if (stringIDNum + 1 >= stringIDs.length) {
+            short[] tmp = new short[stringIDNum + 1000];
+            System.arraycopy(stringIDs, 0, tmp, 0, stringIDNum);
+            stringIDs = tmp;
+        }
+        return (short)(stringIDNum - 1);
+    }
+
+    private static short getShortArrayID(short sa[]) {
+        char[] cc = new char[sa.length];
+        for (int i = 0; i < sa.length; i ++) {
+            cc[i] = (char)sa[i];
+        }
+        String s = new String(cc);
+        return getStringID(s);
+    }
+
+    //utility "empty" objects
+    private static final int[] EMPTY_INT_ARRAY = new int[0];
+    private static final String[] EMPTY_STRING_ARRAY = new String[0];
+    private static final short[] EMPTY_SHORT_ARRAY = new short[0];
+    private static final String UNDEFINED_COMPONENT_FONT = "unknown";
+
+    //////////////////////////////////////////////////////////////////////////
+    //Convert the FontConfig data in Properties file to binary data tables  //
+    //////////////////////////////////////////////////////////////////////////
+    static class PropertiesHandler {
+        public void load(InputStream in) throws IOException {
+            initLogicalNameStyle();
+            initHashMaps();
+            FontProperties fp = new FontProperties();
+            fp.load(in);
+            initBinaryTable();
+        }
+
+        private void initBinaryTable() {
+            //(0)
+            head = new short[HEAD_LENGTH];
+            head[INDEX_scriptIDs] = (short)HEAD_LENGTH;
+
+            table_scriptIDs = toList(scriptIDs);
+            //(1)a: scriptAllfonts scriptID/allfonts -> componentFontNameID
+            //   b: scriptFonts    scriptID -> componentFontNameID[20]
+            //if we have a "allfonts.script" def, then we just put
+            //the "-platformFontID" value in the slot, otherwise the slot
+            //value is "offset" which "offset" is where 20 entries located
+            //in the table attached.
+            head[INDEX_scriptFonts] = (short)(head[INDEX_scriptIDs]  + table_scriptIDs.length);
+            int len = table_scriptIDs.length + scriptFonts.size() * 20;
+            table_scriptFonts = new short[len];
+
+            Iterator iterator = scriptAllfonts.entrySet().iterator();
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                table_scriptFonts[((Number)entry.getKey()).intValue()] = (short)((Number)entry.getValue()).shortValue();
+            }
+            int off = table_scriptIDs.length;
+            iterator = scriptFonts.entrySet().iterator();
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                table_scriptFonts[((Number)entry.getKey()).intValue()] = (short)-off;
+                Short[] v = (Short[])entry.getValue();
+                int i = 0;
+                while (i < 20) {
+                    if (v[i] != null) {
+                        table_scriptFonts[off++] = v[i].shortValue();
+                    } else {
+                        table_scriptFonts[off++] = 0;
+                    }
+                    i++;
+                }
+            }
+
+            //(2)
+            head[INDEX_elcIDs] = (short)(head[INDEX_scriptFonts]  + table_scriptFonts.length);
+            table_elcIDs = toList(elcIDs);
+
+            //(3) sequences  elcID -> XXXX[1|5] -> scriptID[]
+            head[INDEX_sequences] = (short)(head[INDEX_elcIDs]  + table_elcIDs.length);
+            table_sequences = new short[elcIDs.size() * NUM_FONTS];
+            iterator = sequences.entrySet().iterator();
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                //table_sequences[entry.getKey().intValue()] = (short)-off;
+                int k = ((Number)entry.getKey()).intValue();
+                short[] v = (short[])entry.getValue();
+                /*
+                  System.out.println("elc=" + k + "/" + getString((short)table_elcIDs[k]));
+                  short[] ss = getShortArray(v[0]);
+                  for (int i = 0; i < ss.length; i++) {
+                  System.out.println("     " + getString((short)table_scriptIDs[ss[i]]));
+                  }
+                  */
+                if (v.length == 1) {
+                    //the "allfonts" entries
+                    for (int i = 0; i < NUM_FONTS; i++) {
+                        table_sequences[k * NUM_FONTS + i] = v[0];
+                    }
+                } else {
+                    for (int i = 0; i < NUM_FONTS; i++) {
+                        table_sequences[k * NUM_FONTS + i] = v[i];
+                    }
+                }
+            }
+            //(4)
+            head[INDEX_fontfileNameIDs] = (short)(head[INDEX_sequences]  + table_sequences.length);
+            table_fontfileNameIDs = toList(fontfileNameIDs);
+
+            //(5)
+            head[INDEX_componentFontNameIDs] = (short)(head[INDEX_fontfileNameIDs]  + table_fontfileNameIDs.length);
+            table_componentFontNameIDs = toList(componentFontNameIDs);
+
+            //(6)componentFontNameID -> filenameID
+            head[INDEX_filenames] = (short)(head[INDEX_componentFontNameIDs]  + table_componentFontNameIDs.length);
+            table_filenames = new short[table_componentFontNameIDs.length];
+            for (int i = 0; i < table_filenames.length; i++) {
+                table_filenames[i] = -1;
+            }
+            iterator = filenames.entrySet().iterator();
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                table_filenames[((Number)entry.getKey()).shortValue()] = ((Number)entry.getValue()).shortValue();
+            }
+
+            //(7)scriptID-> awtfontpath
+            //the paths are stored as scriptID -> stringID in awtfontpahts
+            head[INDEX_awtfontpaths] = (short)(head[INDEX_filenames]  + table_filenames.length);
+            table_awtfontpaths = new short[table_scriptIDs.length];
+            iterator = awtfontpaths.entrySet().iterator();
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                table_awtfontpaths[((Number)entry.getKey()).shortValue()] = ((Number)entry.getValue()).shortValue();
+            }
+
+            //(8)exclusions
+            head[INDEX_exclusions] = (short)(head[INDEX_awtfontpaths]  + table_awtfontpaths.length);
+            table_exclusions = new short[scriptIDs.size()];
+            iterator = exclusions.entrySet().iterator();
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                int[] exI = (int[])entry.getValue();
+                char[] exC = new char[exI.length * 2];
+                int j = 0;
+                for (int i = 0; i < exI.length; i++) {
+                    exC[j++] = (char) (exI[i] >> 16);
+                    exC[j++] = (char) (exI[i] & 0xffff);
+                }
+                table_exclusions[((Number)entry.getKey()).shortValue()] = getStringID(new String (exC));
+            }
+            //(9)proportionals
+            head[INDEX_proportionals] = (short)(head[INDEX_exclusions]  + table_exclusions.length);
+            table_proportionals = new short[proportionals.size() * 2];
+            iterator = proportionals.entrySet().iterator();
+            int j = 0;
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                table_proportionals[j++] = ((Number)entry.getKey()).shortValue();
+                table_proportionals[j++] = ((Number)entry.getValue()).shortValue();
+            }
+
+            //(10) see (1) for info, the only difference is "xxx.motif"
+            head[INDEX_scriptFontsMotif] = (short)(head[INDEX_proportionals] + table_proportionals.length);
+            if (scriptAllfontsMotif.size() != 0 || scriptFontsMotif.size() != 0) {
+                len = table_scriptIDs.length + scriptFontsMotif.size() * 20;
+                table_scriptFontsMotif = new short[len];
+
+                iterator = scriptAllfontsMotif.entrySet().iterator();
+                while (iterator.hasNext()) {
+                    Entry entry = (Entry )iterator.next();
+                    table_scriptFontsMotif[((Number)entry.getKey()).intValue()] =
+                      (short)((Number)entry.getValue()).shortValue();
+                }
+                off = table_scriptIDs.length;
+                iterator = scriptFontsMotif.entrySet().iterator();
+                while (iterator.hasNext()) {
+                    Entry entry = (Entry )iterator.next();
+                    table_scriptFontsMotif[((Number)entry.getKey()).intValue()] = (short)-off;
+                    Short[] v = (Short[])entry.getValue();
+                    int i = 0;
+                    while (i < 20) {
+                        if (v[i] != null) {
+                            table_scriptFontsMotif[off++] = v[i].shortValue();
+                        } else {
+                            table_scriptFontsMotif[off++] = 0;
+                        }
+                        i++;
+                    }
+                }
+            } else {
+                table_scriptFontsMotif = EMPTY_SHORT_ARRAY;
+            }
+
+            //(11)short[] alphabeticSuffix
+            head[INDEX_alphabeticSuffix] = (short)(head[INDEX_scriptFontsMotif] + table_scriptFontsMotif.length);
+            table_alphabeticSuffix = new short[alphabeticSuffix.size() * 2];
+            iterator = alphabeticSuffix.entrySet().iterator();
+            j = 0;
+            while (iterator.hasNext()) {
+                Entry entry = (Entry )iterator.next();
+                table_alphabeticSuffix[j++] = ((Number)entry.getKey()).shortValue();
+                table_alphabeticSuffix[j++] = ((Number)entry.getValue()).shortValue();
+            }
+
+            //(15)short[] fallbackScriptIDs; just put the ID in head
+            head[INDEX_fallbackScripts] = getShortArrayID(fallbackScriptIDs);
+
+            //(16)appendedfontpath
+            head[INDEX_appendedfontpath] = getStringID(appendedfontpath);
+
+            //(17)version
+            head[INDEX_version] = getStringID(version);
+
+            //(12)short[] StringIDs
+            head[INDEX_stringIDs] = (short)(head[INDEX_alphabeticSuffix] + table_alphabeticSuffix.length);
+            table_stringIDs = new short[stringIDNum + 1];
+            System.arraycopy(stringIDs, 0, table_stringIDs, 0, stringIDNum + 1);
+
+            //(13)StringTable
+            head[INDEX_stringTable] = (short)(head[INDEX_stringIDs] + stringIDNum + 1);
+            table_stringTable = stringTable.toString().toCharArray();
+            //(14)
+            head[INDEX_TABLEEND] = (short)(head[INDEX_stringTable] + stringTable.length());
+
+            //StringTable cache
+            stringCache = new String[table_stringIDs.length];
+        }
+
+        //////////////////////////////////////////////
+        private HashMap scriptIDs;
+        //elc -> Encoding.Language.Country
+        private HashMap elcIDs;
+        //componentFontNameID starts from "1", "0" reserves for "undefined"
+        private HashMap componentFontNameIDs;
+        private HashMap fontfileNameIDs;
+        private HashMap logicalFontIDs;
+        private HashMap fontStyleIDs;
+
+        //componentFontNameID -> fontfileNameID
+        private HashMap  filenames;
+
+        //elcID -> allfonts/logicalFont -> scriptID list
+        //(1)if we have a "allfonts", then the length of the
+        //   value array is "1", otherwise it's 5, each font
+        //   must have their own individual entry.
+        //scriptID list "short[]" is stored as an ID
+        private HashMap sequences;
+
+        //scriptID ->logicFontID/fontStyleID->componentFontNameID,
+        //a 20-entry array (5-name x 4-style) for each script
+        private HashMap scriptFonts;
+
+        //scriptID -> componentFontNameID
+        private HashMap scriptAllfonts;
+
+        //scriptID -> exclusionRanges[]
+        private HashMap exclusions;
+
+        //scriptID -> fontpath
+        private HashMap awtfontpaths;
+
+        //fontID -> fontID
+        private HashMap proportionals;
+
+        //scriptID -> componentFontNameID
+        private HashMap scriptAllfontsMotif;
+
+        //scriptID ->logicFontID/fontStyleID->componentFontNameID,
+        private HashMap scriptFontsMotif;
+
+        //elcID -> stringID of alphabetic/XXXX
+        private HashMap alphabeticSuffix;
+
+        private short[] fallbackScriptIDs;
+        private String version;
+        private String appendedfontpath;
+
+        private void initLogicalNameStyle() {
+            logicalFontIDs = new HashMap();
+            fontStyleIDs = new HashMap();
+            logicalFontIDs.put("serif",      new Short((short)0));
+            logicalFontIDs.put("sansserif",  new Short((short)1));
+            logicalFontIDs.put("monospaced", new Short((short)2));
+            logicalFontIDs.put("dialog",     new Short((short)3));
+            logicalFontIDs.put("dialoginput",new Short((short)4));
+            fontStyleIDs.put("plain",      new Short((short)0));
+            fontStyleIDs.put("bold",       new Short((short)1));
+            fontStyleIDs.put("italic",     new Short((short)2));
+            fontStyleIDs.put("bolditalic", new Short((short)3));
+        }
+
+        private void initHashMaps() {
+            scriptIDs = new HashMap();
+            elcIDs = new HashMap();
+            componentFontNameIDs = new HashMap();
+            /*Init these tables to allow componentFontNameID, fontfileNameIDs
+              to start from "1".
+            */
+            componentFontNameIDs.put("", new Short((short)0));
+
+            fontfileNameIDs = new HashMap();
+            filenames = new HashMap();
+            sequences = new HashMap();
+            scriptFonts = new HashMap();
+            scriptAllfonts = new HashMap();
+            exclusions = new HashMap();
+            awtfontpaths = new HashMap();
+            proportionals = new HashMap();
+            scriptFontsMotif = new HashMap();
+            scriptAllfontsMotif = new HashMap();
+            alphabeticSuffix = new HashMap();
+            fallbackScriptIDs = EMPTY_SHORT_ARRAY;
+            /*
+              version
+              appendedfontpath
+            */
+        }
+
+        private int[] parseExclusions(String key, String exclusions) {
+            if (exclusions == null) {
+                return EMPTY_INT_ARRAY;
+            }
+            // range format is xxxx-XXXX,yyyyyy-YYYYYY,.....
+            int numExclusions = 1;
+            int pos = 0;
+            while ((pos = exclusions.indexOf(',', pos)) != -1) {
+                numExclusions++;
+                pos++;
+            }
+            int[] exclusionRanges = new int[numExclusions * 2];
+            pos = 0;
+            int newPos = 0;
+            for (int j = 0; j < numExclusions * 2; ) {
+                String lower, upper;
+                int lo = 0, up = 0;
+                try {
+                    newPos = exclusions.indexOf('-', pos);
+                    lower = exclusions.substring(pos, newPos);
+                    pos = newPos + 1;
+                    newPos = exclusions.indexOf(',', pos);
+                    if (newPos == -1) {
+                        newPos = exclusions.length();
+                    }
+                    upper = exclusions.substring(pos, newPos);
+                    pos = newPos + 1;
+                    int lowerLength = lower.length();
+                    int upperLength = upper.length();
+                    if (lowerLength != 4 && lowerLength != 6
+                        || upperLength != 4 && upperLength != 6) {
+                        throw new Exception();
+                    }
+                    lo = Integer.parseInt(lower, 16);
+                    up = Integer.parseInt(upper, 16);
+                    if (lo > up) {
+                        throw new Exception();
+                    }
+                } catch (Exception e) {
+                    if (logger != null) {
+                        logger.config("Failed parsing " + key +
+                                  " property of font configuration.");
+
+                    }
+                    return EMPTY_INT_ARRAY;
+                }
+                exclusionRanges[j++] = lo;
+                exclusionRanges[j++] = up;
+            }
+            return exclusionRanges;
+        }
+
+        private Short getID(HashMap map, String key) {
+            Short ret = (Short)map.get(key);
+            if ( ret == null) {
+                map.put(key, new Short((short)map.size()));
+                return (Short)map.get(key);
+            }
+            return ret;
+        }
+
+        class FontProperties extends Properties {
+            public synchronized Object put(Object k, Object v) {
+                parseProperty((String)k, (String)v);
+                return null;
+            }
+        }
+
+        private void parseProperty(String key, String value) {
+            if (key.startsWith("filename.")) {
+                //the only special case is "MingLiu_HKSCS" which has "_" in its
+                //facename, we dont want to replace the "_" with " "
+                key = key.substring(9);
+                if (!"MingLiU_HKSCS".equals(key)) {
+                    key = key.replace('_', ' ');
+                }
+                Short faceID = getID(componentFontNameIDs, key);
+                Short fileID = getID(fontfileNameIDs, value);
+                //System.out.println("faceID=" + faceID + "/" + key + " -> "
+                //    + "fileID=" + fileID + "/" + value);
+                filenames.put(faceID, fileID);
+            } else if (key.startsWith("exclusion.")) {
+                key = key.substring(10);
+                exclusions.put(getID(scriptIDs,key), parseExclusions(key,value));
+            } else if (key.startsWith("sequence.")) {
+                key = key.substring(9);
+                boolean hasDefault = false;
+                boolean has1252 = false;
+
+                //get the scriptID list
+                String[] ss = (String[])splitSequence(value).toArray(EMPTY_STRING_ARRAY);
+                short [] sa = new short[ss.length];
+                for (int i = 0; i < ss.length; i++) {
+                    if ("alphabetic/default".equals(ss[i])) {
+                        //System.out.println(key + " -> " + ss[i]);
+                        ss[i] = "alphabetic";
+                        hasDefault = true;
+                    } else if ("alphabetic/1252".equals(ss[i])) {
+                        //System.out.println(key + " -> " + ss[i]);
+                        ss[i] = "alphabetic";
+                        has1252 = true;
+                    }
+                    sa[i] = getID(scriptIDs, ss[i]).shortValue();
+                    //System.out.println("scriptID=" + si[i] + "/" + ss[i]);
+                }
+                //convert the "short[] -> string -> stringID"
+                short scriptArrayID = getShortArrayID(sa);
+                Short elcID = null;
+                int dot = key.indexOf('.');
+                if (dot == -1) {
+                    if ("fallback".equals(key)) {
+                        fallbackScriptIDs = sa;
+                        return;
+                    }
+                    if ("allfonts".equals(key)) {
+                        elcID = getID(elcIDs, "NULL.NULL.NULL");
+                    } else {
+                        if (logger != null) {
+                            logger.config("Error sequence def: <sequence." + key + ">");
+                        }
+                        return;
+                    }
+                } else {
+                    elcID = getID(elcIDs, key.substring(dot + 1));
+                    //System.out.println("elcID=" + elcID + "/" + key.substring(dot + 1));
+                    key = key.substring(0, dot);
+                }
+                short[] scriptArrayIDs = null;
+                if ("allfonts".equals(key)) {
+                    scriptArrayIDs = new short[1];
+                    scriptArrayIDs[0] = scriptArrayID;
+                } else {
+                    scriptArrayIDs = (short[])sequences.get(elcID);
+                    if (scriptArrayIDs == null) {
+                       scriptArrayIDs = new short[5];
+                    }
+                    Integer fid = (Integer)logicalFontIDs.get(key);
+                    if (fid == null) {
+                        if (logger != null) {
+                            logger.config("Unrecognizable logicfont name " + key);
+                        }
+                        return;
+                    }
+                    //System.out.println("sequence." + key + "/" + id);
+                    scriptArrayIDs[fid.intValue()] = scriptArrayID;
+                }
+                sequences.put(elcID, scriptArrayIDs);
+                if (hasDefault) {
+                    alphabeticSuffix.put(elcID, new Short(getStringID("default")));
+                } else
+                if (has1252) {
+                    alphabeticSuffix.put(elcID, new Short(getStringID("1252")));
+                }
+            } else if (key.startsWith("allfonts.")) {
+                key = key.substring(9);
+                if (key.endsWith(".motif")) {
+                    key = key.substring(0, key.length() - 6);
+                    //System.out.println("motif: all." + key + "=" + value);
+                    scriptAllfontsMotif.put(getID(scriptIDs,key), getID(componentFontNameIDs,value));
+                } else {
+                    scriptAllfonts.put(getID(scriptIDs,key), getID(componentFontNameIDs,value));
+                }
+            } else if (key.startsWith("awtfontpath.")) {
+                key = key.substring(12);
+                //System.out.println("scriptID=" + getID(scriptIDs, key) + "/" + key);
+                awtfontpaths.put(getID(scriptIDs, key), new Short(getStringID(value)));
+            } else if ("version".equals(key)) {
+                version = value;
+            } else if ("appendedfontpath".equals(key)) {
+                appendedfontpath = value;
+            } else if (key.startsWith("proportional.")) {
+                key = key.substring(13).replace('_', ' ');
+                //System.out.println(key + "=" + value);
+                proportionals.put(getID(componentFontNameIDs, key),
+                                  getID(componentFontNameIDs, value));
+            } else {
+                //"name.style.script(.motif)", we dont care anything else
+                int dot1, dot2;
+                boolean isMotif = false;
+
+                dot1 = key.indexOf('.');
+                if (dot1 == -1) {
+                    if (logger != null) {
+                        logger.config("Failed parsing " + key +
+                                  " property of font configuration.");
+
+                    }
+                    return;
+                }
+                dot2 = key.indexOf('.', dot1 + 1);
+                if (dot2 == -1) {
+                    if (logger != null) {
+                        logger.config("Failed parsing " + key +
+                                  " property of font configuration.");
+
+                    }
+                    return;
+                }
+                if (key.endsWith(".motif")) {
+                    key = key.substring(0, key.length() - 6);
+                    isMotif = true;
+                    //System.out.println("motif: " + key + "=" + value);
+                }
+                Integer nameID = (Integer)logicalFontIDs.get(key.substring(0, dot1));
+                Integer styleID = (Integer)fontStyleIDs.get(key.substring(dot1+1, dot2));
+                Short scriptID = getID(scriptIDs, key.substring(dot2 + 1));
+                if (nameID == null || styleID == null) {
+                    if (logger != null) {
+                        logger.config("unrecognizable logicfont name/style at " + key);
+                    }
+                    return;
+                }
+                Short[] pnids;
+                if (isMotif) {
+                    pnids = (Short[])scriptFontsMotif.get(scriptID);
+                } else {
+                    pnids = (Short[])scriptFonts.get(scriptID);
+                }
+                if (pnids == null) {
+                    pnids =  new Short[20];
+                }
+                pnids[nameID.intValue() * NUM_STYLES + styleID.intValue()]
+                  = getID(componentFontNameIDs, value);
+                /*
+                System.out.println("key=" + key + "/<" + nameID + "><" + styleID
+                                     + "><" + scriptID + ">=" + value
+                                     + "/" + getID(componentFontNameIDs, value));
+                */
+                if (isMotif) {
+                    scriptFontsMotif.put(scriptID, pnids);
+                } else {
+                    scriptFonts.put(scriptID, pnids);
+                }
+            }
+        }
+    }
+}